这可能是一个愚蠢的问题,但也许有人可以提供一些见解。
我在头文件中定义了一些全局变量(是的,我知道这很糟糕,但这只是假设的情况)。我将此头文件包含在两个源文件中,然后将它们编译为两个目标文件。代码中的任何地方都没有引用全局符号。
如果源文件是 C 语言,那么编译器看起来会忽略全局符号,并且所有内容都会链接而不会出现错误。如果源文件是 C++,则符号将包含在两个目标文件中,然后我会收到链接器错误。对于 C++,当我包含标头时,我使用 extern "C"。
我使用的是VS2005的微软编译器。
这是我的代码:
头文件(test.h):
#ifndef __TEST_H
#define __TEST_H
/* declaration in header file */
void *ptr;
#endif
C源文件:
test1.c
#include "test.h"
int main( ) {
return 0;
}
test2.c
#include "test.h"
C++ 源文件:
测试1.cpp
extern "C" {
#include "test.h"
}
int main( ) {
return 0;
}
测试2.cpp
extern "C" {
#include "test.h"
}
对于 C,目标文件如下所示:
Dump of file test1.obj
File Type: COFF OBJECT
COFF SYMBOL TABLE
000 006DC627 ABS notype Static | @comp.id
001 00000001 ABS notype Static | @feat.00
002 00000000 SECT1 notype Static | .drectve
Section length 2F, #relocs 0, #linenums 0, checksum 0
004 00000000 SECT2 notype Static | .debug$S
Section length 228, #relocs 7, #linenums 0, checksum 0
006 00000004 UNDEF notype External | _ptr
007 00000000 SECT3 notype Static | .text
Section length 7, #relocs 0, #linenums 0, checksum 96F779C9
009 00000000 SECT3 notype () External | _main
00A 00000000 SECT4 notype Static | .debug$T
Section length 1C, #relocs 0, #linenums 0, checksum 0
String Table Size = 0x0 bytes
对于 C++ 来说,它们看起来像这样:
Dump of file test1.obj
File Type: COFF OBJECT
COFF SYMBOL TABLE
000 006EC627 ABS notype Static | @comp.id
001 00000001 ABS notype Static | @feat.00
002 00000000 SECT1 notype Static | .drectve
Section length 2F, #relocs 0, #linenums 0, checksum 0
004 00000000 SECT2 notype Static | .debug$S
Section length 228, #relocs 7, #linenums 0, checksum 0
006 00000000 SECT3 notype Static | .bss
Section length 4, #relocs 0, #linenums 0, checksum 0
008 00000000 SECT3 notype External | _ptr
009 00000000 SECT4 notype Static | .text
Section length 7, #relocs 0, #linenums 0, checksum 96F779C9
00B 00000000 SECT4 notype () External | _main
00C 00000000 SECT5 notype Static | .debug$T
Section length 1C, #relocs 0, #linenums 0, checksum 0
String Table Size = 0x0 bytes
我注意到,当我编译 C 源代码时,_ptr 被列为 UNDEF,而当我编译 C++ 源代码时,它被定义,这会导致链接器错误。
我知道这在现实生活中不是一件好事,我只是想理解为什么这是不同的。
Thanks.