问题
When I try to compile the following with g++:
const int zero;
int main()
{
return 0;
}
I get an error about an uninitialized const 'zero'
. I thought that global variables were default initialized to 0 [1] ? Why isn't this the case here?
VS compiles this fine.
[1] For example, see https://stackoverflow.com/a/10927293/331785
回答1:
My gcc is slightly more verbose:
$ g++ zeroconst.c
zeroconst.c:1:11: error: uninitialized const ‘zero’ [-fpermissive]
We see that -fpermissive
option will allow this to compile.
See this question on uninitialized const for a reference to C++ standard (the problem is C++-specific).
As cited at GCC wiki:
As mandated by the C++ standard (8.5 [decl.init], para 9 in C++03, para 6 in C++0x), G++ does not allows objects of const-qualified type to be default initialized unless the type has a user-declared default constructor. Code that fails to compile can be fixed by providing an initializer...
回答2:
G++ requires that you initialize your constant during definition.
来源:https://stackoverflow.com/questions/14568830/why-wont-gcc-compile-uninitialized-global-const