Next: Implementation files, Previous: Source code files, Up: Writing modules [Contents][Index]
The .h file should declare the C functions and variables that the module provides.
The .h file should be stand-alone. That is, it does not require other .h files to be included before. Rather, it includes all necessary .h files by itself.
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 C99 and C11 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.
Note that putting a #include
in an extern "C" { ... }
block yields a syntax error in C++ mode on some platforms (e.g., glibc
systems with g++ v3.3 to v4.2, AIX, IRIX). For this reason, it
is recommended to place the #include
before the extern
"C"
block.
Next: Implementation files, Previous: Source code files, Up: Writing modules [Contents][Index]