ARM Technical Support Knowledge Articles

HEADER FILE IS BEING PROCESSED MORE THAN ONCE

Applies to: General Topics

Answer


Information in this article applies to:


QUESTION

I have written the following header file 'header.h' and included it in several .c source files:

#ifndef header
  #define header

  unsigned char x;

#endif

When I build my project, the linker complains that x is being redefined, however, I thought the preprocessor directives used would ensure the file is only processed once.

ANSWER

The scope of the '#define header' is limited to each source file. So for each source file, header is undefined and the variable x is redefined. The linker then sees x defined in more than one object file and complains.

There are two solutions to this problem.

  1. Move '#define header' out of the header file and into each .c source file except for one of them, placing the #define before the #include. For example:
    #define header
    #include "header.h"
    

    This ensures that the header file is only processed for one .c source file.

  2. Move your variable declarations into a separate .c source file, then create a new header file that simply declares the global variables as extern. This new header file can then be included in every .c source file without the need for any preprocessor directives.

For example, you may create a file called 'globals.c' containing:

unsigned char x;

Then create a header file called 'globals.h' containing:

extern unsigned char x;

Simply include the header file 'globals.h' in each .c source file.

Article last edited on: 2005-07-09 12:16:25

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential