这是VC++ 2010的BUG吗?关于在头文件中声明一个常量对象 [英] Is this a BUG of VC++ 2010? About declaring a constant object in a header

查看:24
本文介绍了这是VC++ 2010的BUG吗?关于在头文件中声明一个常量对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几行代码值一千字:

我有三个简单的文件:header.h、main.cpp、other.cpp

I have three simple files: header.h, main.cpp, other.cpp

==== CODE BEGIN ====

// header.h  
  #pragma once  

const void* p = 0;

// main.cpp

  #include "header.h"

int main()
{
    return 0;
}

// other.cpp

  #include "header.h"
==== CODE END ====

编译最简单的项目时,VC++ 2010报错如下:

When compiling the simplest project, the VC++ 2010 complains as follows:

ClCompile:
  other.cpp
  main.cpp
  Generating Code...
other.obj : error LNK2005: "void const * const p" (?p@@3PBXB) already defined in main.obj
D:\Test\Debug\bug.exe : fatal error LNK1169: one or more multiply defined symbols found

Build FAILED.

Time Elapsed 00:00:00.29
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我确定这是 VC++ 2010 的一个 bug,因为以下两个引用:

I am sure this is a bug of VC++ 2010, because of the following two references:

  1. C++ 标准说:(在 n3126 的第 140 页)

  1. The C++ standard says: (at page 140 of n3126)

"对象声明为 const 而不是明确声明的 extern 有内部联动."

"Objects declared const and not explicitly declared extern have internal linkage."

  • MSDN :

    "在 C 中,常量值默认为外部链接,因此它们可以出现仅在源文件中.在 C++ 中,常量值默认为内部链接,这允许它们出现在标题中文件.

    "In C, constant values default to external linkage, so they can appear only in source files. In C++, constant values default to internal linkage, which allows them to appear in header files.

    也可以使用const关键字在指针声明中."

    The const keyword can also be used in pointer declarations."

  • 推荐答案

    const void *p = 0;p 定义为指向 const void,但p本身定义为const.由于您的 p 不是 const 对象,因此为其提供内部链接的规则不适用,因此它具有外部链接.

    const void *p = 0; defines p as a pointer to const void, but does not define p itself to be const at all. Since your p is not a const object, the rule giving it internal linkage does not apply, so it has external linkage.

    void *const p = 0; 会将 p 定义为常量指针.void const * const p 会将 p 定义为指向 const void 的 const 指针.

    void *const p = 0; would define p as a const pointer. void const * const p would define p as a const pointer to const void.

    这篇关于这是VC++ 2010的BUG吗?关于在头文件中声明一个常量对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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