0

几行代码值一千字:

我有三个简单的文件: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 报错如下:

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 的错误,因为以下两个参考:

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

    “声明为 const 且未显式声明为 extern 的对象具有内部链接。”

  2. MSDN

    “在 C 中,常量值默认为外部链接,因此它们只能出现在源文件中。在 C++ 中,常量值默认为内部链接,这允许它们出现在头文件中。

    const 关键字也可以用在指针声明中。”

4

3 回答 3

3

const void *p = 0;定义p为指向 的指针 const void但根本没有p自身定义为const。由于 yourp不是const对象,因此赋予它内部链接的规则不适用,因此它具有外部链接。

void *const p = 0;将定义p为 const 指针。void const * const p将定义p为指向 const void 的 const 指针。

于 2010-11-15T14:33:56.077 回答
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;
于 2010-11-15T14:33:48.173 回答
0

也许它应该是 void* const p?

于 2010-11-15T14:32:33.030 回答