Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› Avoiding Duplicate Declarations

Avoiding Duplicate Declarations

C Programming Tricks

Avoiding duplicate declarations:

Now here is a neat preprocessor trick. It is similar in style to the standard way of forcing header files to be included only once. Almost every header file looks like this:

 #ifndef _SOMEHEADER_H_
 #define _SOMEHEADER_H_
 
 /* Header file body... */
 
 #endif /* ! _SOMEHEADER_H_ */
 

This #ifdef's out the body of the header file on second and subsequent includes; this avoids duplicate declarations and potential infinite recursion in inclusion. Smart compilers (such as gcc) don't even open the file the second time it's referenced.

Here's how to use preprocessor to avoid declaring global variables two times (one, as extern, in header file, and one in .c file). In your header file, use the following code:

 #ifdef I_AM_MAIN
 #define GLOBAL /*nothing*/
 #else
 #define GLOBAL extern
 #endif
 
 /* Global variables declared below... */
 GLOBAL int foo;
 GLOBAL char *bar;
 /* etc. */
 

Just include the header file as usual; all the GLOBAL declarations will be converted to extern. And in exactly one source file (usually the main file of the project), insert the line

 #define I_AM_MAIN
 

before including the header file. As a result, the variables will be declared without extern, and storage will be allocated for them. This trick avoids duplicate declarations and helps keep variable declarations in sync (just think of the consequences of declaring a char x[]; in one file as extern char *x in another...) It is trivial to write a macro to handle initializations of global variables declared in this way.

Oh, and one more thing: don't call global variables foo or bar.

Partners