Why won't gcc compile uninitialized global const?

安稳与你 提交于 2019-12-22 09:37:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!