您可以查看代码以获取更多信息.
文件main.c
#ifndef VAR #define VAR int var; #endif int main(){}
文件other.c
#ifndef VAR #define VAR int var; #endif
用gcc编译
gcc main.c other.c >> success
用g编译
g++ main.c other.c Output: /tmp/ccbd0ACf.o:(.bss+0x0): multiple definition of `var' /tmp/cc8dweC0.o:(.bss+0x0): first defined here collect2: ld returned 1 exit status
我的gcc和g版本:
gcc --version gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Copyright (C) 2011 Free Software Foundation,Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. g++ --version g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 Copyright (C) 2011 Free Software Foundation,Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
解决方法
J.5 Common extensions
The following extensions are widely used in many systems,but are not portable to all
implementations. […]J.5.11 Multiple external definitions
There may be more than one external definition for the identifier of an object,with or
without the explicit use of the keyword extern; if the definitions disagree,or more than
one is initialized,the behavior is undefined (6.9.2).
但从形式上讲,C和C语言中的多重定义错误完全相同.让你的C编译器表现得更迂腐(如果它有一个选项,禁用扩展),你的C编译器也应该生成与C编译器完全相同的错误.
同样,您的代码包含变量var的多个定义,这在C和C中都是错误的.你的#ifdef指令根本没有解决任何问题. Preperocessor指令在这里无法帮助你.预处理器在每个翻译单元中本地和独立地工作.它无法跨翻译单位看到.
如果要创建全局变量(即所有翻译单元共享的同一变量),则需要对该变量进行一个且仅一个定义
int var;
在一个且只有一个翻译单元.所有其他翻译单元应接收var的非定义声明
extern int var;
后者通常放在头文件中.
如果您需要在每个翻译单元中使用独立的变量var,只需在每个翻译单元中将其定义为
static int var;
(尽管在C中,静态的使用现在已被弃用并被无名空间名称取代).