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.
#1 by prasad on November 19, 2007 - 4:10 pm
global variables can be declared in header files but initialized in only one file so that there is no error(dublicate symbol)
#2 by tread on November 22, 2007 - 4:50 am
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 by dsoodak on October 27, 2008 - 6:09 pm
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 by naicul on October 13, 2009 - 2:56 pm
thank you for this post.
#5 by galego on May 6, 2010 - 4:13 pm
nice tip! exactly how I would do it!
#6 by Krzysztow on September 1, 2010 - 7:55 pm
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.
#7 by Sushma on October 19, 2010 - 6:12 am
Thanks. Got a clarity about global variable usage.
#8 by sachin on November 28, 2011 - 10:49 am
Very nice answer, was very helpful..Thank u so much….
#9 by magpie on June 11, 2012 - 4:22 pm
Wow, saved me a lot of searching. Thanks!
#10 by serbia on September 24, 2012 - 8:10 pm
Thanks