在C++中的全局变量的编译重新声明错误,但不是在C

在C++中的全局变量的编译重新声明错误,但不是在C

问题描述:

假设我有这三个文件:在C++中的全局变量的编译重新声明错误,但不是在C

//a.h header 
#include <stdio.h> 
int int_variable; 

void a_f() 
{ 
    printf("int_variable: %d\n", int_variable) 
    int_variable++; 
} 

BH

//b.h header 
#include <stdio.h> 
int int_variable; 

void b_f() 
{ 
    printf("int_variable: %d\n", int_variable) 
    int_variable++; 
} 

主.C

//main.c 
#include "a.h" 
#include "b.h" 

int main() 
{ 
    a_f(); 
    b_f(); 
    return 0; 
} 

为什么编译在C++中产生重新定义的错误,但在C不? 我是C++开发人员,然后在C++中对我有意义,但为什么在C中这不是错误?

当我执行中生成的代码,输出为:

int变量:0

int变量:1

+7

复制(在某种程度上)。见http://*.com/questions/2331584/global-variable-implementation/2331782#2331782和http://*.com/questions/1987413/inclusion-of-unused-symbols-in-object-files-by -compiler-在-C-VS-C/1987495#1987495。答案是:C有暂时的定义,C++没有。 – 2010-03-16 23:34:18

+0

重复! – 2010-03-16 23:39:35

+1

对不起,我真的搜索过,但我看到我用错误的关键字做了这个:P,谢谢Alok。 – coelhudo 2010-03-16 23:42:24

在C中,这两个变量实际上结合成一个变量,因为它们都没有明确的初始化。

如果同时你的.h文件更改为:

// a.h 
int int_variable = 0; 

和:

// b.h 
int int_variable = 0; 

你会得到一个重新定义的错误。在头文件

全局变量应该只与“外部”修改器一起使用。没有例外。向前声明你的变量在一个或多个头文件中(最好只有一个),然后在一个编译单元中定义它。