This might be a dumb question, but maybe someone can provide some insight.
I have some global variables defined in a header file (yes yes I know that\'s bad, but thi
Don't define variables in headers - that is evil.
Only ever declare variables in headers - with an explicit extern
keyword.
The difference is that C++ expressly requires the one definition rule - there may only be one definition of any given variable with external linkage in a C++ program.
Strictly, the C standard has the same requirement. However, Appendix J of the standard lists a common extension of allowing multiple uninitialized definitions to be treated as one - it is called 'common definitions' because it is similar to the behaviour of COMMON blocks in (old school) Fortran (Fortran IV, aka Fortran 66, and Fortran 77, for example).
Caveat: yes, if you know enough not to need to ask such questions, there can occasionally, very seldomly but just occasionally, be a reason for defining variables in a header. But such occasions are so few and far between that it is near enough accurate to say "don't define variables in headers".
Christoph raises an interesting point about 'static const
variables'. One weasel-wording way around the issue is to claim that "a constant isn't a variable". However, Christoph is right: in C++ in particular, static const 'variables' are used. In C, I thought such constants would tend to elicit 'unused' warnings from compilers; however, GCC 4.4.2 does not
give any warnings when given this minimal code:
static const int x = 3;
extern int p(void);
int p(void)
{
return(3);
}
It does not complain about the unused x
even under '-Wall -Wextra
'. So, it is OK to define constants in headers - as in 'static const SomeType constName = InitialValue;
'. At least, if your compiler is GCC, though the code also compiles without warning under Sun Studio compiler with 'cc -v
':
C compiler: /compilers/v12/SUNWspro/bin/cc
cc: Sun C 5.9 SunOS_sparc Patch 124867-09 2008/11/25
acomp: Sun C 5.9 SunOS_sparc Patch 124867-09 2008/11/25
iropt: Sun Compiler Common 12 SunOS_sparc Patch 124861-13 2009/03/10
cg: Sun Compiler Common 12 SunOS_sparc Patch 124861-13 2009/03/10
ld: Software Generation Utilities - Solaris Link Editors: 5.10-1.486