开发者

Declaring an array whose size is declared as extern const

I have a problem initializing an array whose size is defined as extern const. I have always followed the rule that global variables should be declared as extern in the header files and their corresponding definitions should be in one of the implementation files in order to avoid variable redeclaration errors. This approach worked fine till I had to initialize an array with whose size is defined as an extern const. I get an error that a constant expression is expected. However, if I try to assign a value to the const variable the compiler correctly complains that a value cannot be assigned to a constant variable. This actually proves that the compiler does see the variable as a constant. Why then is an error reported when I try to declare an array of the same size?

Is there any way to avoid this without using #define? I would also like to know the reason for this error.

Package.h:

#ifndef PACKAGE_H
#define PACKAGE_H

extern const int SIZE;

#endif

Package.cpp:

#include "Package.h"

const int SIZE = 10;

Foo.cpp:

#include "Package.h"

int main()
{
    // SIZE = 5; // error - cannot ass开发者_开发问答ign value to a constant variable
    // int Array[SIZE]; // error - constant expression expected
    return 0;
}


The constant is external, so it is defined in another compilation unit (.o file). Therefore the compiler cannot determine the size of your array at compilation time; it is not known until link time what the value of the constant will be.


Well, it sees the variable as const qualified, not as a constant expression.


Since it's just an int I would remove the extern and make it a definition rather than a declaration. The reason I say this is that even though this approach places a separate instance of the integer in each source file that includes the header I would imagine that most compilers will optimise out its use. In fact it's impossible for the compiler to optimise out its use if you don't so it won't get optimised out from simple arithmetic expressions.

Since it's declared const it will have internal linkage and so you won't get any multiply-defined symbol problems by doing it this way.


I believe the problem here is that if you declare your variable as extern, it is allowed to be in a different module (.o file) or even in a dynamic library (.dll/.so). This of course means, that the compiler might not be able to resolve the variable content at compile time thus refusing to use the value where a const is required.

My opinion is, that it is perfectly ok not to use extern here and declare it directly in the header file, as it is an int value anyway which will be inlined when used anywhere in the code. I usually use extern const only when working with strings, since I want to make sure that only one instance of the string is generated at runtime.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜