Is there a reason why someone would include stdlib.h twice? - c

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.

Related

Multiple includes of header only library causing redefinition errors

I'm using a header only library called Nuklear. It's a header only library. I'm having trouble when using multiple includes from different files. It returns a multiple definition example:
...
obj/main.o:main.c:(.text+0x4a52b): multiple definition of `nk_sdl_font_stash_begin'
obj/components.o:components.c:(.text+0x4a56f): first defined here
obj/main.o:main.c:(.text+0x4a563): multiple definition of `nk_sdl_font_stash_end'
obj/components.o:components.c:(.text+0x4a5a7): first defined here
obj/main.o:main.c:(.text+0x4a5f4): multiple definition of `nk_sdl_handle_event'
obj/components.o:components.c:(.text+0x4a638): first defined here
obj/main.o:main.c:(.text+0x4ac9f): multiple definition of `nk_sdl_shutdown'
obj/components.o:components.c:(.text+0x4ace3): first defined here
I'm attempting to include the library into 2 files.
main.c
#define SDL_MAIN_HANDLED
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_IMPLEMENTATION
#define NK_SDL_GL3_IMPLEMENTATION
#include "nuklear.h"
#include "nuklear_sdl_gl3.h"
#include "components.h"
...
components.c
#define SDL_MAIN_HANDLED
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#define NK_INCLUDE_FIXED_TYPES
#define NK_INCLUDE_STANDARD_IO
#define NK_INCLUDE_STANDARD_VARARGS
#define NK_INCLUDE_DEFAULT_ALLOCATOR
#define NK_INCLUDE_VERTEX_BUFFER_OUTPUT
#define NK_INCLUDE_FONT_BAKING
#define NK_INCLUDE_DEFAULT_FONT
#define NK_IMPLEMENTATION
#define NK_SDL_GL3_IMPLEMENTATION
#include "nuklear.h"
#include "nuklear_sdl_gl3.h"
The Nuklear library already includes header guards so I'm not sure why this error is happening. Any advice?
From the README at GitHub:
This library is self contained in one single header file and can be used either in header only mode or in implementation mode. The header only mode is used by default when included and allows including this header in other headers and does not contain the actual implementation.
The implementation mode requires to define the preprocessor macro NK_IMPLEMENTATION in one .c/.cpp file before #includeing this file, e.g.:
#define NK_IMPLEMENTATION
#include "nuklear.h"
So, only one of main.c and components.c should include the #define NK_IMPLEMENTATION — yet you define it in both.
Fix
Remove #define NK_IMPLEMENTATION from components.c.
Do not include any other Nuklear header than nuklear.h — the instructions don't tell you to do that (at least, not on the surface; maybe there's something elsewhere that says so, but …).
The documentation also notes:
IMPORTANT: Every time you include "nuklear.h" you have to define the same optional flags. This is very important not doing it either leads to compiler errors or even worse stack corruptions.
It would probably be worth having your own header — use_nuklear.h for example, though I'm sure you'll think of a better name — that contains the correct set of NK_* options (all except NK_IMPLEMENTATION). Then #include "use_nuklear.h" in your source files. That way, if (when) you change options, you have only one place to change — and the rebuilds will be consistent.
You should only #define NK_SDL_GL3_IMPLEMENTATION in one of your .c source files before you #include "nuklear_sdl_gl3.h".
The nuklear_sdl_gl3.h file contains all the function definitions, as well as function declarations, and you only want the definitions in one place or, as you've found, your linker will complain.
nuklear_sdl_gl3.h contains data and functions. It is just very badly written. All definitions should be in the .c files and only declaration, type definitions, extern variables declarations and static inline functions should be in the header file.
You cant include this file more than once in the whole project. The guards do not work here as it is included in different compilations units.

Identifying kernel space in the preprocessor?

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

How do I detect if stdio.h is included?

I have a header foo.h file that declares a function prototype
void foo(FILE *f);
/* ... Other things that don't depend on FILE ... */
among other things.
Now obviously, to use this header, I need to do the following
#include <stdio.h>
#include "foo.h"
I would like to surround this particular prototype with something like the following:
#ifdef _STDIO_H
void foo(FILE *f);
#endif
/* ... Other things that don't depend on FILE ... */
so that I can #include "foo.h" without worrying about #include <stdio.h> in cases where I don't need that particular function.
Is the #ifdef _STDIO_H the way to go if I want my code to be portable and standards compliant?
I could find no mention of _STDIO_H in the standards document, but I see it is used in a variety of C libraries. Should I rather use something that I know to be defined in stdio.h, like EOF?
A related question: What do you do for other standard C headers, like stdlib.h?
<stdio.h> and <stdlib.h> are part of the C99 (and C11) standards. So every (hosted) standard conforming C implementation have them.
On most practical implementations, they are header files with some include guards.
A standard conforming implementation might process #include <stdio.h> very specifically, e.g. by using some database. I know no such implementation.
So simply add
#include <stdio.h>
near the top of your header file, something like
// file foo.h
#ifndef FOO_INCLUDED
#define FOO_INCLUDED
#include <stdio.h>
// other includes ...
// ...
// other stuff
#endif /* FOO_INCLUDED */
Alternatively, you could not care and document that #include "foo.h" requires a previous #include <stdio.h>; any sensible developer using a good-enough C implementation would be able to take care of that.
Actually, I was wrong in my comment on Alter Mann's deleted answer. It looks like stdin is required to be some macro, and then you might use #ifdef stdin ... endif as Alter Mann correctly answered. I believe it is not very readable, and you just want to have <stdio.h> included, either by including it yourself in your foo.h or by requiring it in your documentation.
Contrarily to C++ standard headers, C standard headers are in practice quite quick to be compiled, so I don't think it is worth to optimize the unusual case when <stdio.h> has not been included.
Open your stdio.h file (for your compiler) and see whether it has _STDIO_H or similar definition.

Suppress GCC warning "extra tokens at end of #include directive"

I'm writing a program in C intended to be compiled and run on a HP NonStop machine. However, I want to do the main development on my workstation running Linux. The HP NonStop C-Compiler requires non-standard #include directives like the following:
#include <stdio.h> nolist
For each #include directive, my workstation's GCC is complaining:
S88USF.c:139:21: warning: extra tokens at end of #include directive
How can I suppress this particular warning?
Note: On SO, similar questions have already been asked, the correct answer being along the lines of "don't give gcc any reason to complain in the first place". In this scenario however, I explicitly want to have the #include directives exactly as they are.
I know what I'm doing, I just don't know how to inform gcc about it.
One workaround would be to define a header that includes the following preproccesor macro:
//hp_workaround.h
#ifdef HP_
#define HP_INCLUDE_DIRECTIVE(x) x
#else
#define HP_INCLUDE_DIRECTIVE(x)
#endif
then guard your directives with this macro
#include "hp_workaround.h"
#include <stdio.h> HP_INCLUDE_DIRECTIVE(nolist)
Macroexpansion happening within include can probably help.
GCC will accept this:
#define nolist
#include <stdlib.h> nolist
/* maybe #undef nolist here */

Includes within header files

Should header files have #includes?
I'm generally of the opinion that this kind of hierarchical include is bad. Say you have this:
foo.h:
#include <stdio.h> // we use something from this library here
struct foo { ... } foo;
main.c
#include "foo.h"
/* use foo for something */
printf(...)
The day main.c's implementation changes, and you no longer use foo.h, the compilation will break and you must add <stdio.h> by hand.
Versus having this:
foo.h
// Warning! we depend on stdio.h
struct foo {...
main.c
#include <stdio.h> //required for foo.h, also for other stuff
#include "foo.h"
And when you stop using foo, removing it breaks nothing, but removing stdio.h will break foo.h.
Should #includes be banned from .h files?
You've outlined the two main philosophies on this subject.
My own opinion (and I think that's all that one can really have on this) is that headers should as self-contained as possible. I don't want to have to know all the dependencies of foo.h just to be able to use that header. I also despise having to include headers in a particular order.
However, the developer of foo.h should also take responsibility for making it as dependency-free as possible. For example, the foo.h header should be written to be free of a dependency on stdio.h if that's at all possible (using forward declarations can help with that).
Note that the C standard forbids a standard header from including another standard header, but the C++ standard doesn't. So you can see the problem you describe when moving from one C++ compiler version to another. For example, in MSVC, including <vector> used to bring in <iterator>, but that no longer occurs in MSVC 2010, so code that compiled before might not any more becuase you may need to specifically include <iterator>.
However, even though the C standard might seem to advocate the second philosophy, note that it also mandates that no header depend on another and that you can include headers in any order. So you get the best of both worlds, but at a cost of complexity to the implementers of the C library. They have to jump through some hoops to do this (particularly to support definitions that can be brought in through any of several headers, like NULL or size_t). I guess that the people who drafted the C++ standard decided adding that complexity to impersonators was no longer reasonable (I don't know to what degree C++ library implementors take advantage of the 'loophole' - it looks like MS might be tightening this up, even if it's not technically required).
My general recommendations are:
A file should #include what it needs.
It should not expect something else to #include something it needs.
It should not #include something it doesn't need because something else might want it.
The real test is this: you should be able to compile a source file consisting of any single #include and get no errors or warnings beyond "There is no main()". If you pass this test, then you can expect anything else to be able to #include your file with no problems. I've written a short script called "hcheck" which I use to test this:
#!/usr/bin/env bash
# hcheck: Check header file syntax (works on source files, too...)
if [ $# -eq 0 ]; then
echo "Usage: $0 <filename>"
exit 1
fi
for f in "$#" ; do
case $f in
*.c | *.cpp | *.cc | *.h | *.hh | *.hpp )
echo "#include \"$f\"" > hcheck.cc
printf "\n\033[4mChecking $f\033[0m\n"
make -s $hcheck.o
rm -f hcheck.o hcheck.cc
;;
esac
done
I'm sure there are several things that this script could do better, but it should be a good starting point.
If this is too much, and if your header files almost always have corresponding source files, then another technique is to require that the associated header be the first #include in the source file. For example:
Foo.h:
#ifndef Foo_h
#define Foo_h
/* #includes that Foo.h needs go here. */
/* Other header declarations here */
#endif
Foo.c:
#include "Foo.h"
/* other #includes that Foo.c needs go here. */
/* source code here */
This also shows the "include guards" in Foo.h that others mentioned.
By putting #include "Foo.h" first, Foo.h must #include its dependencies, otherwise you'll get a compile error.
Well, main shouldn't rely on "foo.h" in the first place for stdio. There's no harm in including something twice.
Also, perhaps foo.h doesn't really need stdio. What's more likely is that foo.c (the implementation) needs stdio.
Long story short, I think everyone should just include whatever they need and rely on include guards.
Once you get into projects with hundreds or thousands of header files, this gets untenable. Say I have a header file called "MyCoolFunction.h" that contains the prototype for MyCoolFunction(), and that function takes pointers to structs as parameters. I should be able to assume that including MyCoolFunction.h will include everything that's necessary and allow me to use that function without looking in the .h file to see what else I need to include.
If the header file needs a specific header, add it to the header file
#ifndef HEADER_GUARD_YOUR_STYLE
#define HEADER_GUARD_YOUR_STYLE
#include <stdio.h> /* FILE */
int foo(FILE *);
#endif /* HEADER GUARD */
if the code file doesn't need a header, don't add it
/* #include <stdio.h> */ /* removed because unneeded */
#include <stddef.h> /* NULL */
#include "header.h"
int main(void) {
foo(NULL);
return 0;
}
Why don't you #include stuff in the *.c file corresponding to the header?

Resources