2

I have a class which has a static const array, it has to be initialized outside the class:

class foo{  
static const int array[3];  
};    
const int foo::array[3] = { 1, 2, 3 };

But then I get a duplicate symbol foo::array in foo.o and main.o foo.o hold the foo class, and main.o holds main() and uses instances of foo.
How can I share this static const array between all instances of foo? I mean, that's the idea of a static member.

1 Answer 1

10

Initialize it in your corresponding .cpp file not your .h file.

When you #include it's a pre-processor directive that basically copies the file verbatim into the location of the #include. So you are initializing it twice by including it in 2 different compilation units.

The linker sees 2 and doesn't know which one to use. If you had only initialized it in one of the source files, only one .o would contain it and you wouldn't have a problem.

3
  • Yes, right. Thanks! I keep making this dumb errors with header files and getting linker errors.
    – Petruza
    May 24, 2010 at 13:37
  • 1
    I had a question regarding this - Why don't header guards resolve the problem? -- Thanks, Sid.
    – Opt
    Jul 11, 2010 at 0:42
  • Header guards only work within the scope of a compilation unit, such as a .cpp file. If you've got multiple .cpp files in your project then each one is compiled as a separate unit. If they include the same header then it will be included one for each .cpp file, thus the symbol will be multiply defined.
    – Sean
    Sep 27, 2011 at 15:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.