Is this a BUG of VC++ 2010? About declaring a constant object in a header

只愿长相守 提交于 2019-12-13 06:44:10

问题


Several lines of code are worth a thousand words:

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

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

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

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

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

  2. The MSDN says:

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

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


回答1:


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; would define p as a const pointer. void const * const p would define p as a const pointer to const void.




回答2:


If you define the variable in a header file that is included more than once, the linker finds a definition for each inclusion. You should declare the variable in the header file and define it once and only once, in a single .cpp file.

Header file:

extern const void* p;

cpp file:

const void* p = 0;



回答3:


Maybe it should be void* const p?



来源:https://stackoverflow.com/questions/4185275/is-this-a-bug-of-vc-2010-about-declaring-a-constant-object-in-a-header

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