Re: References static in header files
Dave the Funkatron ha scritto:
Hey all,
Suppose I have a value somewhere, declared in a header like so:
int someValue;
then defined in a cpp file like so:
int someValue = 9;
That all compiles nicely.
Really? That surprises me. You are openly violating the ODR because "int
somevalue;" is a *definition*, not a declaration, so you have multiple
definitions of the same object. The program is ill-formed and the only
thing that may make such a program work is a blasphemy called "tentative
definitions" that is allowed by C but it's forbidden in C++. Probably
you are using GCC in such a way that tentative definitions are allowed
in C++.
To make your program well-formed you *must* use extern keyword in the
header file.
That all compiles nicely. However, if that variable were a reference
to an int, it wouldn't work so well. If I merely declare it in the
header like this:
int& someOtherValue;
I get an error from GCC saying
test.h:13: error: 'someOtherValue' declared as reference but not
initialized
However, if I define the value in the header like this:
int& someOtherValue = someValue;
I run into problems at link-time if I include that header from
multiple cpp files. I also tried
extern int& someOtherValue;
just for kicks, but no go. Any ideas on how to get around this would
be appreciated.
As another poster already remarked, there must be a better way to
achieve what you want (which is not clear from your words) that would
avoid the use of a global reference.
Anyway, if you can't redesign you application, the quickest way is to
use a pointer instead of a reference.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]