Next: , Previous: Comments, Up: Gnulib


1.2 Header files

It is a tradition to use CPP tricks to avoid parsing the same header file more than once, which might cause warnings. The trick is to wrap the content of the header file (say, foo.h) in a block, as in:

     #ifndef FOO_H
     # define FOO_H
     ...
     body of header file goes here
     ...
     #endif /* FOO_H */

Whether to use FOO_H or _FOO_H is a matter of taste and style. The C89 and C99 standards reserve all identifiers that begin with an underscore and either an uppercase letter or another underscore, for any use. Thus, in theory, an application might not safely assume that _FOO_H has not already been defined by a library. On the other hand, using FOO_H will likely lead the higher risk of collisions with other symbols (e.g., KEY_H, XK_H, BPF_H, which are CPP macro constants, or COFF_LONG_H, which is a CPP macro function). Your preference may depend on whether you consider the header file under discussion as part of the application (which has its own namespace for CPP symbols) or a supporting library (that shouldn't interfere with the application's CPP symbol namespace).

Adapting C header files for use in C++ applications can use another CPP trick, as in:

     # ifdef __cplusplus
     extern "C"
     {
     # endif
     ...
     body of header file goes here
     ...
     # ifdef __cplusplus
     }
     # endif

The idea here is that __cplusplus is defined only by C++ implementations, which will wrap the header file in an `extern "C"' block. Again, whether to use this trick is a matter of taste and style. While the above can be seen as harmless, it could be argued that the header file is written in C, and any C++ application using it should explicitly use the `extern "C"' block itself. Your preference might depend on whether you consider the API exported by your header file as something available for C programs only, or for C and C++ programs alike.