James Kanze
10/2/2008 1:30:00 PM
On Oct 2, 11:23 am, "Christian Meier" <chris@no_spam.com> wrote:
> I have the following code:
> file1.h:
> static const int iValue = 5;
> <EOF>
> file2.cpp
> #include <iostream>
> #include "file1.h"
> int main(int args, char* argv[])
> {
> switch(args) {
> case iValue:
> std::cout << "Hello\n";
> }
> }
> <EOF>
> This works fine as the value of the constant "iValue" is known
> when compiling the main()-function in file2.cpp.
> I have some more cpp-files which include file1.h. Therefore I
> have a copy of "iValue" in each translation unit as it has
> internal linkage. In the executable which is made with these
> object files (translation units) I have several copies of that
> variable; all having the same value.
Maybe. Maybe not.
> Now, I would like to change the linkage of "iValue" to extern
> so that there is only one symbol for this constant in my
> executable. When I change the keyword "static" to "extern" I
> have the problem that the symbol is more than once defined in
> my executable. When I only declare the variable "iValue" in
> file1.h with external linkage ("extern const int iValue;") and
> define it in a new file called file1.cpp ("extern const iValue
> = 5;"), then I have no problem with multiple definitions but I
> have a new problem in my function main() because the value of
> "iValue" is not known when compiling file2.cpp.
> Do you have any suggestions how I can compile all my code
> without having more than one symbol for "iValue" in my
> program? Or is it not possible what I am trying to reach?
Do you have some valid reason for wanting iValue to have the
same address in every translation unit? It seems strange to me
to give an int identity, especially if you're not going to
change it. And otherwise, what's the problem with what you have
written initially?
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34