I'm writing the header of a kernel module. The header is known to the module, but also used by callers in user space. This is a problem, because some types used should be included from different files depending on whether the header is currently in user or kernel space (or so this question makes me think).
I don't want to maintain two separate header files, so I've been thinking of a solution like this:
#ifndef IN_KERNEL
#include <stdint.h>
#else
#include <linux/types.h>
With IN_KERNEL being defined somewhere in my kernel code. Is there a preprocessor constant that already does this?
From reading this, it seems that an existing constant used for this purpose is __KERNEL__.
#ifndef __KERNEL__
#include <stdint.h>
#else
#include <linux/types.h>
#endif
I was studying the code for the Kilo text editor here:
https://github.com/antirez/kilo/blob/master/kilo.c
And I noticed that the includes defined stdlib.h twice (UPDATE: Comments are mine):
#include <termios.h>
#include <stdlib.h> // first time
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h> // second time
#include <ctype.h>
Is this merely an error? Or is there something to it? I ask because the author of the code doesn't seem like someone who makes a lot of mistakes. I wouldn't want to suggest a change in ignorance.
As stdlib.h has an include guard, there is no point in including it twice. Probably the mistake was caused by merging two files, both dependant on stdlib.h.
There is no harm in including a standard header more than once, although it is totally unnecessary.
The C standard says the following about this:
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.
There's no reason to include a particular header file twice. If the file has proper include guards, the second inclusion will have no effect. If it does not have include guards, you'll likely get a slew of errors for multiple definitions for typedefs, among others.
In the case of system headers, they almost always have include guards. The contents of stdlib.h might look something like this:
#ifndef _STDLIB_H
#define _STDLIB_H 1
...
// type definitions, #defines, declarations, etc.
...
#endif /* stdlib.h */
The first time stdlib.h is included, the #ifndef will evaluate to true, _STDLIB_H is defined, and the remaining contents are inserted into the file being compiled. The second time stdlib.h is included, the #ifndef will evaluate to false since _STDLIB_H is defined and the contents of the file between the #ifndef and #endif will not be inserted again.
Most UNIX/Linux systems do this. In contrast, Microsoft is known for not managing its OS specific include files properly. If you included them in the wrong order you'll end up with lots of errors.
The only scenario it can make a difference is when one of the includes is undefining some symbols (including the include guards) from the previous includes. Consider 2 files:
1.h:
#define A 1
2.h:
#undef A
Now, the following sequence:
#include "1.h"
#include "2.h"
int B = A;
will produce an error, as A is undefined.
The following sequence will be just fine:
#include "1.h"
#include "2.h"
#include "1.h"
int B = A;
Now, if 1.h has the include guards:
1.h:
#ifndef GUARD_1
#define GUARD_1
#define A 1
#endif
The 2.h can do:
#undef GUARD_1
#undef A
and cause the same effect.
Now to stdlib.h. You can compose something like this in your x.h header:
#undef _STDLIB_H // Kill the include guard of stdlib.h
#undef NULL // Undefine some important symbol from stdlib.h
Now, this sequence:
#include <stdlib.h>
#include "x.h"
will have NULL undefined
And this:
#include <stdlib.h>
#include "x.h"
#include <stdlib.h>
will have it defined.
Though not directly applicable to <stdlib.h>, a reason for including a user-defined header file twice: Testing if including the header file twice incurs a problem.
Example: Consider a pair of files foo.h and foo.c declaring and implementing a bunch of foo_ functions, defines, types, etc.
File foo.c
#include "foo.h"
#include "foo.h"
rest of foo.c code ...
A 2nd calling of an include file should not cause a problem and foo.c tests that.
OTOH, foo.c did not test if including a header file only once is OK.
I would like to use
#include <time.h>
clock_gettime(CLOCK_TAI, &...);
but unfortunately CLOCK_TAI is not defined in stock time.h header (in openSUSE 13.2 at least). It is however defined in linux/time.h and actually supported by the operating system. But if I include the latter header, it provokes a bunch of declaration conflicts — versus both time.h and bits/types.h. Including only the linux/time.h does not help, as time.h and/or bits/types.h will be implicitly included by common headers, like unistd.h or stdlib.h, anyway.
So I tried to resolve conflicts manually. Particularly, the first compiler error message was about timespec redeclaration, so I wrote in my code:
#include <time.h>
#if defined(__timespec_defined) && !defined(_STRUCT_TIMESPEC)
#define _STRUCT_TIMESPEC
#endif
#include <linux/time.h>
It worked, but not without yet another conflict with itimerspec redeclaration, which is declared unconditionally in both headers and is not concluded with definitions of any include guards. So I decided to ban implicit time.h inclusion altogether:
#include <linux/time.h>
#ifndef _TIME_H
#define _TIME_H
#endif
This continued with compiler complaining about timeval redeclaration. So I banned implicit bits/types.h inclusion as well:
#include <linux/time.h>
#ifndef _TIME_H
#define _TIME_H
#endif
#ifndef _BITS_TYPES_H
#define _BITS_TYPES_H
#endif
Alright, but this removes important basic declarations as well, upon which common types like size_t are based. So I tried to go in the opposite direction and disable linux/types.h inclusion:
#ifndef _LINUX_TYPES_H
#define _LINUX_TYPES_H
#endif
#include <linux/time.h>
#ifndef _TIME_H
#define _TIME_H
#endif
As you can guess, it resulted in system-specific types like __kernel_time_t being missing, which leaded to inability to declare timespec and so on.
Thus I am wondering: is it at all possible to use linux/… headers in combination with stdlib.h and other commonly included files? Are there other ways to access system-specific CLOCK_TAI value?
I am still new to C. I have a question regarding source and header files. I have a header file like this:
#ifndef MISC_H_
#define MISC_H_
#define BYTE 8
#include <stdbool.h>
#include <stdio.h>
#include "DataStruct.h"
bool S_areEqual(char *firstString, char *secondString); /* (1) */
bool S_randomDataStructureCheck(char *string, DataStruct *data); /* (2) */
#endif
bool is used in the function parameters, and thus, I have it in the source as well. Do I have to #include <stdbool.h> in both the header file and the source file? Are there circumstances where I would and where I wouldn't?
What if I had a typedef in another header file that was used in the header as a function parameter? Do I have to #include "DataStruct.h" in both the header file and the source file?
What is the standard?
No you don't have to include in both header and source (.c) file. If you have included in a header that is included by the source then it will be available to the source as well. The order of header inclusion can be important when some headers depend on others. See this answer for more detail.
As an aside, you will notice the lines
#ifndef MISC_H_
#define MISC_H_
That ensures that the header is only included once.
Update
From the comments:
so in the source, you just include its respective header?
If you mean, should a source file only include its respective header, then it depends. Generally, files should include the files that they need.
If a source file needs a header, but that header is not needed by its own header file, then the include should go in the source rather than its header. One reason is that it is just conceptually cleaner that each file includes only the files that it needs, so it is easy to tell what the dependencies are. The other reason is that it reduces the impacts of change.
Lets look at an example. Say you have foo.c and foo.h and foo.c needs foodep.h to compile, but foo.h doesn't:
Option 1: foo.h
#include "foodep.h"
Now imagine that there are a number of other files foo1.h, foo2.h, foo3.h, etc that include foo.h. Then, any change to foodep.h affects all of those other files and their dependent header and source files.
Option 2: foo.c
#include "foodep.h"
Now, no other files have visibility of foodep.h. A change to foodep.h only impacts foo.c.
Generally, try to apply the same practices as you do with Object Oriented programming - encapsulate and minimize the scope of change.
The simple way to view this is that you should always include the headers which provide functions/aliases/macros you are using in your program, whether they actually need to be included should be left to compiler.
This is because every header is defined under #ifdef - #endif clause conditioned on some header-specific MACRO (And it is necessary to do this if you define your own header, to avoid multiple inclusions and thus avoid painful compiler errors).
Thus, my advice, if you are using bool in your program, you should include stdbool.h. If the compiler has already included it in definition of some other header, it will not include stdbool again.
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.