开发者

static const C++ class member initialized gives a duplicate symbol error when linking

开发者 https://www.devze.com 2022-12-31 01:34 出处:网络
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];

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 };
开发者_Go百科

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消