In separating the interface from implementation in C, where is the right place to include a header file?
In the interface file (.h file) or in the implementation file (.c file)? Why?
My Sample Code:
console.h
#ifndef CONSOLE_H
#define CONSOLE_H
#include <windows.h>
void gotoxy (const WORD x, const WORD y);
void clearScreen();
#endif
console.c
#include <stdlib.h>
#include "console.h"
COORD coord = {0,0};
void gotoxy (const WORD x, const WORD y){
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void clearScreen(){
system("cls");
}
Here are some principles:
An unnecessarily included header only adds to the compilation time.
This may sound ignorable, and it generally is, but if you get into the habit of including too much, it can become an issue.
Imagine you have a general header for your project, that includes all other project headers and all the system headers they may need. So any .c file only needs to include this one header and be done with it. This is convenient. However, apart from prolonging the compilation of each .c file a bit, it also guarantees that you have to recompile the entire project every time you change a single header. And that will significantly slow down your modify-compile-test cycle.
You must avoid creating circular include dependencies.
If you do create a circular include, you are in for trouble. So, best avoid including anything unnecessary: the less you include, the less headers can trigger circular includes. Sometimes you may be required to insert a forward declaration instead of an include.
A .c file must include its .h file.
If you fail to do this, the function signatures in the .c file won't be checked against the declarations in the .h file, and madness will follow.
The problem with this principle is, that your .c file may compile fine without the include if the .h file does not define a type that is needed by the implementation. Nevertheless, the include must be there to prevent signature mismatches.
So, apart from point 3, it is prudent to only include headers that are absolutely needed, and only in the file that actually needs it. Personally, I frequently only include a header after I get a compiler error telling me that something is missing.
Include directives should always be included in the file that needs them, or to make reading and understanding your code easier.
In your example, you include windows.h inside console.h. For such a common header file, it'd be fine to leave it in console.h only. However, if you were using another library that you'd written, and was not already widely adopted, it would be wise to include it in both files to prevent future developers from having to hunt through header files searching for the one which provided functionality seen in console.c.
There are only two changes to your setup I would make. I would include all headers in the header file except for the console.h header which is necessary to include the header. Second, when you #define CONSOLE_H 1, give it a value 1 is fine. I just prevents an uninitialized tag. Looks good.
console.h
#ifndef CONSOLE_H
#define CONSOLE_H 1
#include <windows.h>
#include <stdlib.h>
void gotoxy (const WORD x, const WORD y);
void clearScreen();
#endif
console.c
#include "console.h"
COORD coord = {0,0};
void gotoxy (const WORD x, const WORD y){
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void clearScreen(){
system("cls");
}
Like it was already mentioned in comments and other answers - includes should be in the file that needs them.
However, for complex/large projects, I'd recommend to design the interfaces such that they require only handlers/references to actual data instead of actual data. This allows usage of forward declarations in header files and actual includes in the implementation files. The reason for this is avoidance of tight coupling. Tight Coupling often leads to very problematic behavior, forcing to include headers that aren't directly needed (and even creating circular dependencies, resulting in compilation failures and need for extensive changes!), increasing compilation time and harming such SW quality attributes as modularity, maintainability and scalability.
That said, there are common headers (usually part of the environment you're using) that are needed in most situations (e.g., stdio.h, windows.h etc.) - including these won't hurt the SW quality although the compilation time might still increase. One way to deal with this is to use Precompiled headers.
Related
Assuming we have 2 files DIO.c and DIO.h. I used to #include all necessary header files in DIO.h and only #include DIO.h in DIO.c. while working on drivers for ATmega32, I found out that some functions are declared implicitly while including other modules. This made me wonder is that right to include all files in header file instead of source file? and how what
i'm doing currently affects dependency?
After visiting some repos on github i found out that they never #include anything in header files, and only include everything in C file, which made me more confused about what about typedefs? how they use them without including the header file containing them?
Here is an example of DIO.h file:
#include "Dio_Private.h"
#include "Dio_Config.h"
#include "../../Utilities/Macros.h"
and here is an example of DIO.c file:
#include "DIO.h"
If the answer was that I should include all header files in C file, what about enums?
for example, if I want to use enums defined in DIO.h file in any other module, should I now seperate these enums in another header file and only #include it?
Thanks in advance :)
It's perfectly fine to #include multiple headers in one and use that (provided you use proper include guards).
Having said that, if you don't like typing multiple #includes over and over and you are thinking of creating a big one just for convenience, keep in mind that this will affect compilation time (since the contents of all the headers have to be parsed for every .c file that includes them).
#ShaneGervais is right that you should use include guards, and right that #include is somewhat like pasting the contents of the header file into your source file, but incorrect about the rest of it.
Example Dio_Private.h
#ifndef DIO_PRIVATE_H_
#define DIO_PRIVATE_H_
int dinput(char **);
int doutput(char *);
#endif
This will ensure no errors on multiple #include
Do not use #pragma once. Do not use #define __DIO_PRIVATE_H__. These are not standard C and the latter one results in undefined behavior.
Do not define your functions in a header file, especially as a beginner. For very small, very succinct functions that do not use global variables and which will not bloat your code too much if used several times over, it may be appropriate, when you more fully understand how to use them, to define them in a header file. Example:
#ifndef MYSTRDUP_H_
#define MYSTRDUP_H_
#include <stdlib.h>
#include <string.h>
static inline char *mystrdup(const char *s) {
size_t n = strlen(s) + 1;
char *r = malloc(n);
if (r) memcpy(r, s, n);
return r;
}
#endif
This question is a matter of opinion and style, and therefore probably not regarded as a "good" question for SO. I can offer advice only:
Include anything in the header file necessary to make the header file valid without requiring additional includes.
So for example if header file xxx.h references a symbol such as int32_t, then it should explicitly include stdint.h. Otherwise the user of the header file will have to "know" that stdint.h is required to be included before xxx.h, even if the subsequent source never references stdint.h type or symbols.
To not allow nested includes is a nonsense, because the user of a header file will have to know or work out what include dependencies are required and they cold be very many.
On the other hand to include headers for symbols not referenced in the header itself pulls in interfaces the user might not expect and is inefficient. You might do that when a public interface is a collation or parts in multiple headers, but you need ot be able to justify it and follow the principles of maximum cohesion, minimal coupling.
After visiting some repos on github ...
I would not assume some randomly selected repo to be definitive or even good practice or the arbiter of such. Being published on Github is not an indication of quality - it is a poor strategy to learning good coding style. You might better take your "best-practice" cues from standard or device library headers for example.
I am learning C and I am unsure where to include files. Basically I can do this in .c or in .h files:
Option 1
test.h
int my_func(char **var);
test.c
#include <stdio.h>
#include "test.h"
int my_func(char **var) {printf("%s\n", "foo");}
int main() {...}
Option 2
test.h
#include <stdio.h>
int my_func(char **var);
test.c
#include "test.h"
int my_func(char **var) {printf("%s\n", "foo");}
int main() {...}
With option 2 I would only need to include test.h in whatever .c file I need the library. Most of the examples I see use option 1.
Are there some general rules when to do what or is this a question of personal preferences?
Don't use includes, you don't need.
I'd choose something like "Option 1". Why "something like" ? Because I'd create a separate file for the main and I'd keep all declaraions inside the .h and all definitions inside the corresponding .c.
Of course, both options are valid.
If you want to include only one header in your main, you can just create a header file, containing only includes - that's a common practice. This way, you can include only one header, instead of several.
I tend to prefer Option 1, as cyclic dependencies will come and bite you very quickly in option 2, and reducing the input size is the best way to guarantee faster compile times. Option 2 tends towards including everything everywhere, whether you really need it or not.
That said, it might be best to experiment a little with what works for structuring your projects. Hard and fast rules tend to not apply universally to these kinds of questions.
both options are correct. the C standard allows both solutions
All C standard headers must be made such that they can be included several times and in any order:
Standard headers may be included in any order; each may be included
more than once in a given scope, with no effect different from being
included only once
(From Preprocessor #ifndef)
I don't think that there is a universal rule (from a "grammatical" point of view, both your options are correct and will work). What is often done is to include in the .h file the headers you need for the library (as in your option 1), either because you'll need them when working with the library (thus avoiding always including the same set of header files in your .c files, which is more error prone), or because they are mentioned in the .h file itself (e.g., if you use a int32_t as type in the function prototypes of the .h files, you will of course need to include <stdint.h> in the .h file).
I prefer to use includes in c file.
If your program is getting bigger you might forgot to include something in one header file, but it is included in one other you use.
By including them in c-file you won't lose includes, while editing other files.
I prefer Option 1. I want to know what I used in my project, and in much time, Option 1 works more effective than Option 2 in time and efficiency.
There is no rule specifying you have following a particular fashion. Even if you include / not include in test.c file, it is not going to bother much, provided you include it in test.h file and include that test.h file in test.c. Hope you are clear with that.
This is because, you have preprocessor directives like #ifndef, #define, #endif. They are called Include guards. These are used in the inbuild header files. However, when you include a file written by you, either go with your option 2, or use include guards to be safe.
The include guards work as follows.
#ifndef ANYTHING
#define ANYTHING
..
..
..
#endif
So when you include for the first time, ANYTHING is not yet defined. So ifndef returns true, then ANYTHING gets defined, and so...on.. But the next time if you include the same file ( by mistake) ifndef would return a false since ANYTHING is now defined and so the file would not be included at all. This protection is necessary to avoid duplicate declarations of variable present in the header file. That would give you a compilation error.
Hope that helps
Cheers
I came across some codes in the following way
//file.c
#include <stdlib.h>
void print(void){
printf("Hello world\n");
}
and
//file main.c
#include <stdio.h>
#include "file.c"
int main(int argc, char *argv[]){
print();
return EXIT_SUCCESS;
}
Is there any flaw in this kind of programming style? I am not able to make out the flaw although I feel so, because somewhere I read that separating the implementation into *.h and *.c file helps compiler check for consistency. I don't understand what is meant by consistency.
I would be deeply thankful for some suggestions.
--thanks
Nothing prevents you from including .c files. However, separating declaration (in .h files) and implementation (and .c files) and then including only .h files has several advantages :
Compile time. Your declaration usually changes less than your implementation. If you include only .h files, and makes a change in your implementation (in the .c file), then you only have to recompile one .c file, instead of all the files which include the modified file.
Readability and management of interfaces. All your declarations can be checked in a single glance at the (usually) small .h file whereas the .c file is filled with lines and lines of code. Moreover it helps you determine which file see which functions and variables. For example, to avoid having a global variable included where you don't want it.
It's a common expectation that the compiler should compile .c files. .h files are not directly given to the compiler. They are usually only included within .c files.
Thus, your code is expected to compile by something like:
gcc main.c file.c
rather than only gcc main.c. That command would fail in the linking stage as it sees duplicate symbols.
You're going to have problems if you include file.c in more than one source code file which combine to make a library/executable, since you'll have duplicate method implementations. The above strikes me as a poor means of sharing/reusing code, and is not to be recommended.
It is not uncommon to include data in another file if it is more convenient to separate it from the code. For example, XPM or raw BMP data in a char array could be included to embed an image in the program in this way. If the data is generated from another build step then it makes sense to include the file.
I would suggest using a different file extension to avoid confusion (e.g. *.inc, *.dat, etc.).
Yes, this is permitted.
Using this is an advanced topic.
It slows down development compile time (cheaper to compile only what is necessary).
It speeds up deployment compile time (all files are out of date).
It allows the compiler to inline functions across module boundaries.
It allows a trick to control exported symbols from a library while keeping it modular.
It might confuse the debugger.
There is nothing wrong from a C language perspective with including a .c file in a program. The C language cares not about the extension of the file, C++ in fact often omits an extension on certain header files to avoid conflicts.
But from the perspective of a programmer, yeah this is odd. Most programmers will operate on the assumption that a .c file will not be included and this can cause problems via incorrect assumptions. It's best to avoid this practice. If you find you must use it, it's a sign of poor design.
In the .h files you should place function prototypes. For example, in your code you should have:
//file.h
void print(void);
//file.c
void
print(void)
{
printf("Hello world\n");
}
//file main.c
#include <stdio.h>
#include "file.h"
int main(int argc, char *argv[]){
print();
return EXIT_SUCCESS;
}
There are only two reasons that I know of for including C files (and which make sense):
inline functions which are non trivial, but that's really a matter of style
share implementation of private (static) functions by including the same file in several other files. That's actually the only way to do it in a purely platform independent way (but toolchain specific tricks like hidden attribute for gcc, etc... are much better if they are available)
The flaws:
you compile several times the same code
if not used sparingly, it quickly leads to multiple defined symbols for public symbols, in a way which is difficult to debug (include files which include other files...)
It is bad style, but one other reason to do it is that it can be used a part of a trick using the ## token concatenation operator to do a kind of poor man's templating in C.
Note that this fairly evil, isn't recommended, and will produce code that's hard to debug and maintain, but you can do something like the following:
mytemplate.c:
MyTemplateFunction_ ## MYTYPE(MYTYPE x)
{
// function code that works with all used TYPEs
}
main.c:
#define MYTYPE float
#include "mytemplate.c"
#undef MYTYPE
#define MYTYPE int
#include "mytemplate.c"
#undef MYTYPE
int main(int, char*)
{
float f;
int i;
MyTemplateFunction_float(f);
MyTemplateFunction_int(i);
return 0;
}
The evils of macros can be exacerbated:
file1.c
#define bottom arse
file2.c
int f()
{
int arse = 4;
bottom = 3;
printf("%d", arse);
}
main.c
#include "file1.c"
#include "file2.c"
void main()
{
f();
}
Indeed a convoluted example. But usually you wouldn't notice it because a macro's scope is the file it is in.
I did actually get this bug, I was importing some lib code into a new project and couldn't be bothered to write the Makefile, so I just generated an all.cpp which included all the sources from the library. And it didn't work as expected due to macro pollution. Took me a while to figure it out.
It's fine for the programs of this length.
If I have a several header files :lets say 1.h, 2.h, 3.h.
Let's say the all three of the header files have #include <stdlib.h> and one of the include files in them.
When I have to use all 3 header files in a C file main.c,
it will have 3 copies of #include <stdlib.h> after the preprocessor.
How does the compiler handle this kind of conflict?
Is this an error or does this create any overhead?
If there are no header guards, what will happen?
Most C headers include are wrapped as follows:
#ifndef FOO_H
#define FOO_H
/* Header contents here */
#endif
The first time the preprocessor scans this, it will include the contents of the header because FOO_H is undefined; however, it also defines FOO_H preventing the header contents from being added a second time.
There is a small performance impact of having a header included multiple times: the preprocessor has to go to disk and read the header each time. This can be mitigated by adding guards in your C file to include:
#ifndef FOO_H
#include <foo.h>
#endif
This stuff is discussed in great detail in Large-Scale C++ Software Design (an excellent book).
This is usually solved with preprocessor statements:
#ifndef __STDLIB_H
#include <stdlib.h>
#define __STDLIB_H
#endif
Although I never saw it for common header files like stdlib.h, so it might just be necessary for your own header files.
The preprocessor will include all three copies, but header guards will prevent all but the first copy from being parsed.
Header guards will tell the preprocessor to convert subsequent copies of that header file to effectively nothing.
Response to edit:
Standard library headers will have the header guards. It would be very unusual and incorrect for them to not have the guards.
Similarly, it is your responsibility to use header guards on your own headers.
If header guards are missing, hypothetically, you will get a variety of errors relating to duplicate definitions.
Another point: You can redeclare a function (or extern variable) a bazillion times and the compiler will accept it:
int printf(const char*, ...);
int printf(const char*, ...);
is perfectly legal and has a small compilation overhead but no runtime overhead.
That's what happens when an unguarded include file is included more than once.
Note that it is not true for everything in an include file. You can't redeclare an enum, for example.
This is done by one of the two popular techniques, both of which are under stdlib's responsibility.
One is defining a unique constant and checking for it, to #ifdef out all the contents of the file if it is already defined.
Another is microsoft-specific #pragma once, that has an advantage of not having to even read the from the hard drive if it was already included (by remembering the exact path)
You must also do the same in all header files you produce. Or, headers that include yours will have a problem.
As far a I know regular include simply throws in the contents of another file. The standard library stdlib.h urely utilizes the code guards: http://en.wikipedia.org/wiki/Include_guard, so you end up including only one copy. However, you can break it (do try it!) if you do: #include A, #undef A_GUARD, #include A again.
Now ... why do you include a .h inside another .h? This can be ok, at least in C++, but it is best avoided. You can use forward declarations for that: http://en.wikipedia.org/wiki/Forward_declaration
Using those works for as long as your code does not need to know the size of an imported structure right in the header. You might want to turn some function arguments by value into the ones by reference / pointer to solve this issue.
Also, always utilize the include guards or #pragma once for your own header files!
As others have said, for standard library headers, the system must ensure that the effect of a header being included more than once is the same as the header being included once (they must be idempotent). An exception to that rule is assert.h, the effect of which can change depending upon whether NDEBUG is defined or not. To quote the C standard:
Standard headers may be included in any order; each may be included more than once in
a given scope, with no effect different from being included only once, except that the
effect of including <assert.h> depends on the definition of NDEBUG.
How this is done depends upon the compiler/library. A compiler system may know the names of all the standard headers, and thus not process them a second time (except assert.h as mentioned above). Or, a standard header may include compiler-specific magic (mostly #pragma statements), or "include guards".
But the effect of including any other header more than once need not be same, and then it is up to the header-writer to make sure there is no conflict.
For example, given a header:
int a;
including it twice will result in two definitions of a. This is a Bad Thing.
The easiest way to avoid conflict like this is to use include guards as defined above:
#ifndef H_HEADER_NAME_
#define H_HEADER_NAME_
/* header contents */
#endif
This works for all the compilers, and doesn't rely of compiler-specific #pragmas. (Even with the above, it is a bad idea to define variables in a header file.)
Of course, in your code, you should ensure that the macro name for include guard satisfies this:
It doesn't start with E followed by an uppercase character,
It doesn't start with PRI followed by a lowercase character or X,
It doesn't start with LC_ followed by an uppercase character,
It doesn't start with SIG/SIG_ followed by an uppercase character,
..etc. (That is why I prefer the form H_NAME_.)
As a perverse example, if you want your users guessing about certain buffer sizes, you can have a header like this (warning: don't do this, it's supposed to be a joke).
#ifndef SZ
#define SZ 1024
#else
#if SZ == 1024
#undef SZ
#define SZ 128
#else
#error "You can include me no more than two times!"
#endif
#endif
Is it necessary to #include some file, if inside a header (*.h), types defined in this file are used?
For instance, if I use GLib and wish to use the gchar basic type in a structure defined in my header, is it necessary to do a #include <glib.h>, knowing that I already have it in my *.c file?
If yes do I also have to put it between the #ifndef and #define or after the #define?
NASA's Goddard Space Flight Center (GSFC) rules for headers in C state that it must be possible to include a header in a source file as the only header, and that code using the facilities provided by that header will then compile.
This means that the header must be self-contained, idempotent and minimal:
self-contained — all necessary types are defined by including relevant headers if need be.
idempotent — compilations don't break even if it is included multiple times.
minimal — it doesn't define anything that is not needed by code that uses the header to access the facilities defined by the header.
The benefit of this rule is that if someone needs to use the header, they do not have to struggle to work out which other headers must also be included — they know that the header provides everything necessary.
The possible downside is that some headers might be included many times; that is why the multiple inclusion header guards are crucial (and why compilers try to avoid reincluding headers whenever possible).
Implementation
This rule means that if the header uses a type — such as 'FILE *' or 'size_t' - then it must ensure that the appropriate other header (<stdio.h> or <stddef.h> for example) should be included. A corollary, often forgotten, is that the header should not include any other header that is not needed by the user of the package in order to use the package. The header should be minimal, in other words.
Further, the GSFC rules provide a simple technique to ensure that this is what happens:
In the source file that defines the functionality, the header must be the first header listed.
Hence, suppose we have a Magic Sort.
magicsort.h
#ifndef MAGICSORT_H_INCLUDED
#define MAGICSORT_H_INCLUDED
#include <stddef.h>
typedef int (*Comparator)(const void *, const void *);
extern void magicsort(void *array, size_t number, size_t size, Comparator cmp);
#endif /* MAGICSORT_H_INCLUDED */
magicsort.c
#include <magicsort.h>
void magicsort(void *array, size_t number, size_t size, Comparator cmp)
{
...body of sort...
}
Note that the header must include some standard header that defines size_t; the smallest standard header that does so is <stddef.h>, though several others also do so (<stdio.h>, <stdlib.h>, <string.h>, possibly a few others).
Also, as mentioned before, if the implementation file needs some other headers, so be it, and it is entirely normal for some extra headers to be necessary. But the implementation file ('magicsort.c') should include them itself, and not rely on its header to include them. The header should only include what users of the software need; not what the implementers need.
Configuration headers
If your code uses a configuration header (GNU Autoconf and the generated 'config.h', for example), you may need to use this in 'magicsort.c':
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include "magicsort.h"
...
This is the only time I know of that the module's private header is not the very first header in the implementation file. However, the conditional inclusion of 'config.h' should probably be in 'magicsort.h' itself.
Update 2011-05-01
The URL linked above is no longer functional (404). You can find the C++ standard (582-2003-004) at EverySpec.com; the C standard (582-2000-005) seems to be missing in action.
The guidelines from the C standard were:
§2.1 UNITS
(1) Code shall be structured as units, or as stand-alone header files.
(2) A unit shall consist of a single header file (.h) and one or more body (.c) files. Collectively the header and body files are referred to as the source files.
(3) A unit header file shall contain all pertinent information required by a client unit. A unit’s
client needs to access only the header file in order to use the unit.
(4) The unit header file shall contain #include statements for all other headers required by the unit header. This lets clients use a unit by including a single header file.
(5) The unit body file shall contain an #include statement for the unit header, before all other #include statements. This lets the compiler verify that all required #include statements are in
the header file.
(6) A body file shall contain only functions associated with one unit. One body file may not
provide implementations for functions declared in different headers.
(7) All client units that use any part of a given unit U shall include the header file for unit U; this
ensures that there is only one place where the entities in unit U are defined. Client units may
call only the functions defined in the unit header; they may not call functions defined in the
body but not declared in the header. Client units may not access variables declared in the body
but not in the header.
A component contains one or more units. For example, a math library is a component that contains
multiple units such as vector, matrix, and quaternion.
Stand-alone header files do not have associated bodies; for example, a common types header does
not declare functions, so it needs no body.
Some reasons for having multiple body files for a unit:
Part of the body code is hardware or operating system dependent, but the rest is common.
The files are too large.
The unit is a common utility package, and some projects will only use a few of the
functions. Putting each function in a separate file allows the linker to exclude the ones not
used from the final image.
§2.1.1 Header include rationale
This standard requires a unit’s header to contain #include statements for all other headers required
by the unit header. Placing #include for the unit header first in the unit body allows the compiler to
verify that the header contains all required #include statements.
An alternate design, not permitted by this standard, allows no #include statements in headers; all
#includes are done in the body files. Unit header files then must contain #ifdef statements that check
that the required headers are included in the proper order.
One advantage of the alternate design is that the #include list in the body file is exactly the
dependency list needed in a makefile, and this list is checked by the compiler. With the standard
design, a tool must be used to generate the dependency list. However, all of the branch
recommended development environments provide such a tool.
A major disadvantage of the alternate design is that if a unit’s required header list changes, each file
that uses that unit must be edited to update the #include statement list. Also, the required header list
for a compiler library unit may be different on different targets.
Another disadvantage of the alternate design is that compiler library header files, and other third party
files, must be modified to add the required #ifdef statements.
A different common practice is to include all system header files before any project header files, in
body files. This standard does not follow this practice, because some project header files may
depend on system header files, either because they use the definitions in the system header, or
because they want to override a system definition. Such project header files should contain #include
statements for the system headers; if the body includes them first, the compiler does not check this.
GSFC Standard available via Internet Archive 2012-12-10
Information courtesy Eric S. Bullington:
The referenced NASA C coding standard can be accessed and downloaded via the Internet archive:
http://web.archive.org/web/20090412090730/http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard
Sequencing
The question also asks:
If yes, do I also have to put it (the #include lines) between the #ifndef and #define or after the #define.
The answer shows the correct mechanism — the nested includes, etc, should be after the #define (and the #define should be the second non-comment line in the header) — but it doesn't explain why that's correct.
Consider what happens if you place the #include between the #ifndef and #define. Suppose the other header itself includes various headers, perhaps even #include "magicsort.h" indirectly. If the second inclusion of magicsort.h occurs before #define MAGICSORT_H_INCLUDED, then the header will be included a second time before the types it defines are defined. So, in C89 and C99, any typedef type name will be erroneously redefined (C2011 allows them to be redefined to the same type), and you will get the overhead of processing the file multiple times, defeating the purpose of the header guard in the first place. This is also why the #define is the second line and is not written just before the #endif. The formula given is reliable:
#ifndef HEADERGUARDMACRO
#define HEADERGUARDMACRO
...original content of header — other #include lines, etc...
#endif /* HEADERGUARDMACRO */
A good practice is to only put #includes in an include file if the include file needs them. If the definitions in a given include file are only used in the .c file then include it only in the .c file.
In your case, i would include it in the include file between the #ifdef/#endif.
This will minimize dependencies so that files that don't need a given include won't have to be recompiled if the include file changes.
Usually, library developers protect their includes from multiple including with the #ifndef /#define / #endif "trick" so you don't have to do it.
Of course, you should check... but anyways the compiler will tell you at some point ;-) It is anyhow a good practice to check for multiple inclusions since it slows down the compilation cycle.
During compilation preprocessor just replaces #include directive by specified file content.
To prevent endless loop it should use
#ifndef SOMEIDENTIFIER
#define SOMEIDENTIFIER
....header file body........
#endif
If some header was included into another header which was included to your file
than it is not necessary to explicitly include it again, because it will be included into the file recursively
Yes it is necessary or the compiler will complain when it tries to compile code that it is not "aware" of. Think of #include's are a hint/nudge/elbow to the compiler to tell it to pick up the declarations, structures etc in order for a successful compile. The #ifdef/#endif header trick as pointed out by jldupont, is to speed up compilation of code.
It is used in instances where you have a C++ compiler and compiling plain C code as shown here
Here is an example of the trick:
#ifndef __MY_HEADER_H__
#define __MY_HEADER_H__
#ifdef __cplusplus
extern "C" {
#endif
/* C code here such as structures, declarations etc. */
#ifdef __cplusplus
}
#endif
#endif /* __MY_HEADER_H__ */
Now, if this was included multiple times, the compiler will only include it once since the symbol __MY_HEADER_H__ is defined once, which speeds up compilation times.
Notice the symbol cplusplus in the above example, that is the normal standard way of coping with C++ compiling if you have a C code lying around.
I have included the above to show this (despite not really relevant to the poster's original question).
Hope this helps,
Best regards,
Tom.
PS: Sorry for letting anyone downvote this as I thought it would be useful tidbit for newcomers to C/C++. Leave a comment/criticisms etc as they are most welcome.
You need to include the header from your header, and there's no need to include it in the .c. Includes should go after the #define so they are not unnecessarily included multiple times. For example:
/* myHeader.h */
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <glib.h>
struct S
{
gchar c;
};
#endif /* MY_HEADER_H */
and
/* myCode.c */
#include "myHeader.h"
void myFunction()
{
struct S s;
/* really exciting code goes here */
}
I use the following construct to be sure, that the needed include file is included before this include. I include all header files in source files only.
#ifndef INCLUDE_FILE_H
#error "#include INCLUDE.h" must appear in source files before "#include THISFILE.h"
#endif
What I normally do is make a single include file that includes all necessary dependencies in the right order. So I might have:
#ifndef _PROJECT_H_
#define _PROJECT_H_
#include <someDependency.h>
#include "my_project_types.h"
#include "my_project_implementation_prototypes.h"
#endif
All in project.h. Now project.h can be included anywhere with no order requirements but I still have the luxury of having my dependencies, types, and API function prototypes in different headers.
Just include all external headers in one common header file in your project, e.g. global.h and include it in all your c files:
It can look like this:
#ifndef GLOBAL_GUARD
#define GLOBAL_GUARD
#include <glib.h>
/*...*/
typedef int YOUR_INT_TYPE;
typedef char YOUR_CHAR_TYPE;
/*...*/
#endif
This file uses include guard to avoid multiple inclusions, illegal multiple definitions, etc.