c&c ++默认全局变量链接,多个声明和定义问题

Bos*_*iaw 27 c c++ multiple-definition-error one-definition-rule linkage

例如:

code1.c/.cpp

int a;

// ... and so on
Run Code Online (Sandbox Code Playgroud)

code2.c/.cpp

int a;

int main(void) {
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

去编译:

$gcc code1.c code2.c      # this is fine
$

$g++ code1.cpp code2.cpp  # this is dead
/tmp/ccLY66HQ.o:(.bss+0x0): multiple definition of `a'
/tmp/ccnIOmPC.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

C&C++之间是否存在全局变量链接差异?

CB *_*ley 21

这不是严格合法的.int a;是C中的暂定定义.允许多个暂定定义,每个对象的每个翻译单元最多有一个非暂定定义,在C中有外部链接,但程序中所有翻译单元只有一个定义.

它是一种通常实现的扩展,允许在C中的多个翻译单元进行临时定义,只要不超过一个翻译单元包含非暂定定义,但它不是严格标准的.

在C++ int a;中只是一个定义 - 没有暂定的概念 - 在程序的翻译单元中有一个对象的多个定义仍然是非法的.

对于C案例,您可能希望看一下这个问题.


Art*_*cto 5

这在两者中都是非法的,但 C 编译器通常会实现扩展。看到这个答案