这可能是一个愚蠢的问题,但也许有人可以提供一些见解。C或C++编译器在目标文件中包含未使用的符号
我在头文件中定义了一些全局变量(是的,我知道这很糟糕,但这只是一个假设情况)。我将这个头文件包含在两个源文件中,然后将它们编译为两个目标文件。代码中的任何地方都没有引用全局符号。
如果源文件是C,那么它看起来像编译器忽略全局符号和所有链接没有错误。如果源文件是C++,则这两个对象文件中都包含这些符号,然后出现链接器错误。对于C++,我在包含头文件时使用了extern“C”。
我正在使用VS2005的Microsoft编译器。
这里是我的代码:
头文件(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++源文件:
test1.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++源代码时,它被定义为链接器错误。
我知道这在现实生活中并不是一件好事,我只是想明白为什么这是不同的。
谢谢。
是不是真的有这样的事情在C或‘全局’变量或符号C++。所以,发布你的代码来展示你实际做了什么。 – Kylotan 2009-12-31 23:11:09
不只是代码。我们需要了解您如何构建应用程序。你使用静态动态库或只是对象文件等。 – 2009-12-31 23:37:04
我添加了该帖子的代码。我只是试图将两个目标文件链接到一个可执行文件中。 – WildCrustacean 2010-01-04 15:29:39