为什么gcc不会编译未初始化的全局常量? [英] Why won't gcc compile uninitialized global const?

查看:299
本文介绍了为什么gcc不会编译未初始化的全局常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试用g ++编译以下代码时:

  const int zero; 

int main()
{
return 0;

$ / code>

我得到一个有关未初始化的const零的错误。我认为全局变量默认初始化为0 [1]?为什么这里不是这种情况?

VS编译这个罚款。


$ b [1]例如,请参阅 https://stackoverflow.com/a/10927293/331785

解决方案

div>

我的gcc略显冗长:

  $ g ++ zeroconst.c 
zeroconst.c:1 :11:error:uninitialized const'zero'[-fpermissive]

我们看到 -fpermissive 选项将允许它编译。<​​/ p>



正如 href =http://gcc.gnu.org/wiki/VerboseDiagnostics#error:_uninitialized_const_.27d.27_.5B-fpermissive.5D.2C_note:_.27const_class_D.27_has_no_user-provided_default_constructor =nofollow noreferrer> GCC维基


按照C ++标准(C ++ 03中的8.5 [decl.init],第9段,C ++ 0x中的
第6段),G ++不允许使用const限定类型的对象
被默认初始化,除非类型有用户声明的默认
构造函数。无法编译的代码可以通过提供
初始化程序来修复...



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

解决方案

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...

这篇关于为什么gcc不会编译未初始化的全局常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆