I write some functions to use dinamic arrays in c, without the problem of pointers ecc. , and
now that i write enough code to use it properly, i want to encapsulate all this functions in a library.
Anyway in many of this function i use memcpy() method of the string.h.
So my question is:
Need i to include string.h in the .h file?
if i use string.h in the application where i will include my own library, will it be compilated two times?
is there a way to optimising the compilation?
There aren't some guides about it online, and if there are, they are so ambiguos and confusing.
I found something about the ifdef but i don't really understand how and why use it.
Can somebody give me an example of the header file with a similar scenario, or at least a tutorial for writing header files?
This is the first time that i try to write a library in c, so all tips will be appreciate.
Your header file will be shared between the final application and your library. Therefore, the best place to include <string.h> is your header file.
Do not worry about system or standard headers being included more than once. They normally have protective #ifdefs which take care of including the code only once.
As a good practice you can also insert a custom #ifdef in your header. For instance, your header file would look like this:
/* Beginning of header file */
#ifndef ALEX_XXX_HEADER
#define ALEX_XXX_HEADER
/* Your header constants, prototypes, etc. here */
#endif
/* End of header file */
In this way, the compiler will first check whether _ALEX_XXX_HEADER has been defined. If it hasn't, it means it is the first time it hits this file. Then, it defines your header macro _ALEX_XXX_HEADER and processes all the code in the header.
If the header is included more than once, the next time the compiler finds the ##ifndef ALEX_XXX_HEADER line, it will skip the entire #ifndef clause because ALEX_XXX_HEADER was already defined the first time. In other words, it will skip the entire header file. As a result, the header code will be included once only.
Related
Couldn't stdio functions and variables be defined in header files without having to use .c files.
If not, what are .c files used for?
The functions defined in the header file have to be implemented. The .c file contains the implementation, though these have already been compiled into a static or shared library that your compiler can use.
The header file should contain a minimal description of the function to save time when compiling. If it included the entire source it'd force the compiler to rebuild it each and every time you compile which is really wasteful since that source never changes.
In effect, the header file serves as a cheat sheet on how to interact with the already compiled library.
The reason the .c files are provided is primarily for debugging, so your debugger can step through in your debug build and show you source instead of raw machine code. In rare cases you may want to look at the implementation of a particular function in order to better understand it, or in even more rare cases, identify a bug. They're not actually used to compile your program.
In your code you should only ever reference the header file version, the .h via an #include directive.
stdio.h is a standard header, required to be provided by every conforming hosted C implementation. It declares, but does not define, a number of entities, mostly library functions like putchar and scanf.
stdio.c, if it exists, is likely to be a C source file that defines the functions declared in stdio.h. There is no requirement that an implementation must make it available. It might not even exist; for example the implementations of the functions declared in stdio.h might appear in multiple *.c files.
The declaration of putchar is:
int putchar(int c);
and that's all the compiler needs to know when it sees a call to putchar in your program. The code that implements putchar is typically provided as machine code, and the linker's job is to resolve your putchar() call so it ends up invoking that code. putchar() might not even be written in C (though it probably is).
An executable program can be built from multiple *.c source files. One and only one copy of the code that implements putchar is needed for an entire program. If the implementation of putchar were in the header file, then it would be included in each separately compiled source file, creating conflicts and, at best, wasting space. The code that implements putchar() (and all the other functions in the library) only needs to be compiled once.
The .c files has specific function for any aim. For example stdio.c files has standart input-output functions to use within C program. In stdio.h header files has function prototypes for all stdio.c functions, all defines, all macros etc. When you #include <stdio.h> in your main code.c file your main code assumes there is a " int printf(const char *format, ...)" function. Returns int value and you can pass argument ..... etc. When you call printf() function actually you use stdio.c files..
There are languages where if you want to make use of something someone else has written, you say something like
import module
and that takes care of everything.
C is not one of those languages.
You could put "library" source code in a file, and then use #include to pull it in wherever you needed it. But this wouldn't work at all, for two reasons:
If you used #include to pull it in from two different source files, and then linked the two resulting object files together, everything in the "library" would be defined twice.
You might not want to deliver your "library" code as source; you might prefer to deliver it in compiled, object form.
Suppose I have a code like this
foo.h
#pragma once
#ifndef _HEADER
#define _HEADER
//code
#endif
foo.c
#include "header.h"
//code
main.c
#include "foo.h"
int main() {
return 0
}
Why should I include foo.h in foo.c? It can still work without it.
You are correct that you do not HAVE to include the module's header file in the module's C file.
There are a few reasons why you may wish to do so. (What follows is a non-exhaustive list).
As others have noted, it helps ensure that the declarations in the header file are consistent with the definitions in the C file. This is of particular importance when some or all of the routines are to be called from another module. In other words, this can help cut down on errors.
It safely and quickly allows you a little extra flexibility in where you place the routines in the file. Granted this can be achieved with forward declarations in the C file, but if the routines are going to be called from another module, then save yourself the extra typing (and possible typos) and make use of the header file inclusion. Why would you want the flexibility? It allows you to group the routines as you see fit for both maintainability and readability.
It helps to keep your list of include files leaner and cleaner. Presumably, your module's header file will include anything that it needs. Therefore, including that header file means that you don't have to explicitly include all those extra header files. Experience has taught me that a modules with lean include lists often have fewer WTF moments (as well as having a very small positive impact on compilation time).
Hope this helps.
I want to know before I dump time into what might not be a viable coding method.
If I make a header file with a function somewhere in it, double fill(char *howtofill), can I then call the function inside the header file?
Usually in C, header files are used to declare function prototypes, which will then be included in proper C files (by the compiler). These prototypes make the C file code aware about functions, hardcoded in other C files, not in headers.
If you think you need to put code in a .h file, you probably have to think again about your program architecture.
Good to know: all your .h file content will be "copy-pasted" to the C file in place of the #include "file.h" directive.
After the first step of the compiler (called preprocessing), your code will end in a single big file.
If this does not help you, can you tell us more about your problem ?
Lately I have been using header files to split up my program into separate files, (C files containing functions and header files declaring them). Every thing works fine but for some reason, I need to include <stdio.h> and <stdlib.h> in EVERY C file... or my project fails to compile. Is this expected behavior?
C modules need to know either how something is defined, or where it can find a definition. If the definition is in the header file, then you should include it in the modules that use it. Here is a link to information regarding header files.
The answer would depend on whether or not that functions might depend on other declared functions in other .c/.h files.
For example:
filea.c:
#include "filea.h";
methodA()
{
methodB();
}
fileb.c:
#include <somelibrary.h>
#include "fileb.h"
methodB();
{
somelibrarycode();
}
This will not compile unless filea.c includes the header for fileb.h as it has some external dependency that is not resolved.
If this is not what you're describing than there is some other spaghettification happening, or you accidentally statically typed functions preventing them from being seen outside of the .c file.
One possible solution to this problem is to have a single shared.h with all the other includes, but I personally don't recommend this as this merely masks the issue instead of making it readily apparently which files depend on what and establish clear lines of dependency.
They must be included some way.
Some projects require long list of includes in .c files, possibly with mandatory sort, even forcing assumption that no header includes any other header.
Some allow assuming some includes form some headers.
Some use collection headers (that include a list of small headers) and replace long lists with those.
Some go even further, using "forced header" option of compiler, so include will not appear anywhere, and declare the content to be implicitly assumed. It may go on project or whole codebase level, or combined. It plays pretty well with precompiled headers.
(And there are many more strategies, you get the figure, all with some pros&cons.)
Should I put the includes in the header file or the source file? If the header file contains the include statements, then if I include that header file in my source, then will my source file have all of the included files that were in my header? Or should I just include them in my source file only?
Only put includes in a header if the header itself needs them.
Examples:
Your function returns type size_t. Then #include <stddef.h> in the header file.
Your function uses strlen. Then #include <string.h> in the source file.
There's been quite a bit of disagreement about this over the years. At one time, it was traditional that a header only declare what was in whatever module it was related to, so many headers had specific requirements that you #include a certain set of headers (in a specific order). Some extremely traditional C programmers still follow this model (religiously, in at least some cases).
More recently, there's a movement toward making most headers standalone. If that header requires something else, the header itself handles that, ensuring that whatever it needs is included (in the correct order, if there are ordering issues). Personally, I prefer this -- especially when the order of headers can be important, it solves the problem once, instead of requiring everybody who uses it to solve the problem yet again.
Note that most headers should only contain declarations. This means adding an unnecessary header shouldn't (normally) have any effect on your final executable. The worst that happens is that it slows compilation a bit.
Your #includes should be of header files, and each file (source or header) should #include the header files it needs. Header files should #include the minimum header files necessary, and source files should also, though it's not as important for source files.
The source file will have the headers it #includes, and the headers they #include, and so on up to the maximum nesting depth. This is why you don't want superfluous #includes in header files: they can cause a source file to include a lot of header files it may not need, slowing compilation.
This means that it's entirely possible that header files might be included twice, and that can be a problem. The traditional method is to put "include guards" in header files, such as this for file foo.h:
#ifndef INCLUDE_FOO_H
#define INCLUDE_FOO_H
/* everything in header goes here */
#endif
The approach I have evolved into over twenty years is this;
Consider a library.
There are multiple C files, one internal H file and one external H file. The C files include the internal H file. The internal H file includes the external H file.
You see that from the compilers POV, as it compiles a C file, there is a hierarchy;
external -> internal -> C code
This is the correct ordering, since that which is external is everything a third party needs to use the library. That which is internal is required to compile the C code.
If header file A #includes header files B and C, then every source file that #includes A will also get B and C #included. The pre-processor literally just performs text substitution: anywhere it finds text that says #include <foo.h> it replaces it with the text of foo.h file.
There are different opinions on whether you should put #includes in headers or source files. Personally, I prefer to put all #includes in source file by default, but any header files that cannot compile without other pre-requisite headers should #include those headers themselves.
And every header file should contain an include guard to prevent it being included multiple times.
Make all of your files so that they can be built using only what they include. If you don't need an include in your header remove it. In a big project if you don't maintain this discipline you leave yourself open to breaking an entire build when someone removes an include from a header file that is being used by a consumer of that file and not even by the header.
In some environments, compilation will be fastest if one only includes the header files one needs. In other environments, compilation will be optimized if all source files can use the same primary collection of headers (some files may have additional headers beyond the common subset). Ideally, headers should be constructed so multiple #include operations will have no effect. It may be good to surround #include statements with checks for the file-to-be-included's include-guard, though that creates a dependency upon the format of that guard. Further, depending upon a system's file caching behavior, an unnecessary #include whose target ends up being completely #ifdef'ed away may not take long.
Another thing to consider is that if a function takes a pointer to a struct, one can write the prototype as
void foo(struct BAR_s *bar);
without a definition for BAR_s having to be in scope. A very handy approach for avoiding unnecessary includes.
PS--in many of my projects, there will be a file which it's expected that every module will #include, containing things like typedefs for integer sizes and a few common structures and unions [e.g.
typedef union {
unsigned long l;
unsigned short lw[2];
unsigned char lb[4];
} U_QUAD;
(Yes, I know I'd be in trouble if I moved to a big-endian architecture, but since my compiler doesn't allow anonymous structs in unions, using named identifiers for the bytes within the union would require that they be accessed as theUnion.b.b1 etc. which seems rather annoying.
You should only include files in your header that you need to declare constants and function declarations. Technically, these includes will also be included in your source file, but for clarity sake, you should only include in each file the files you actually need to use. You should also protect them in your header from multiple inclusion thusly:
#ifndef NAME_OF_HEADER_H
#define NAME_OF_HEADER_H
...definition of header file...
#endif
This prevents the header from being included multiple times, resulting in a compiler error.
Your source file will have the include statements if your put it in the header. However, in some cases it would be better to put them in the source file.
Remember that if you include that header in any other sources, they will also get the includes from the header, and that is not always desirable. You should only include stuff where it is used.