Declaring global variables in header files

is a NO-NO! My colleague asked me why – so here is the answer.

If you do something like this:

  • Declare a variable, say ‘int glob_x’ in ‘x.h’
  • Include ‘x.h’ in ‘a.c’ and ‘b.c’
  • Try to link a.o and b.o into one executable, and you will get a linker error, duplicate symbol.

Basically, the header file is included in both the files, and the variable glob_x is now global in *both* the c files, which leads to a clash when you try to link them together.

The correct way of doing this is:

Make glob_x extern in x.h, and declare the variable in only one of your .c files. Now you can use the variable in any .c files that include x.h, and there will be no linker error.

About these ads

10 thoughts on “Declaring global variables in header files

  1. global variables can be declared in header files but initialized in only one file so that there is no error(dublicate symbol)

  2. Yes, I should correct myself, variables can be declared in a header file, as long as they are not defined there (you mean defined, not initialized – a variable need not be initialized even though its good practice).

    To quote K&R:
    Declarations specify the interpretation given to each identifier – they do not necessarily reserve storage associated with that identifier. Declarations that reserve storage are called definitions.

    An example of a declaration that does not reserve storage:
    extern int x;

    So the title of my post should be “Defining variables in header files”

    Thanks!

  3. I guess this is more or less a dead thread but thanks to the poster. I ended up going past a 64k total file size (including #included files) in my firmware compiler.

    It is kind of irritating that c compilers don’t have a more elegant solution (which doesn’t require having and maintaining 2 almost identical copies of your global header file).

  4. Thank You for the idea. I lost some hours on trying to figure out, why it doesn’t work for me and then came across Your blog… and forgot to put definition in one of cpp files.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s