C g+中的多重定义+;?

C g+中的多重定义+;?,c,gcc,makefile,g++,C,Gcc,Makefile,G++,代码如下: global.h #ifndef GLOBAL_H #define GLOBAL_H #include <stdio.h> int test; void test_fun(void); #endif #ifndef GLOBAL_H #define GLOBAL_H #include <iostream> int test; void test_fun(void); #endif main.c #include "global.h" void tes

代码如下:

global.h

#ifndef GLOBAL_H
#define GLOBAL_H
#include <stdio.h>
int test;

void test_fun(void);
#endif
#ifndef GLOBAL_H
#define GLOBAL_H
#include <iostream>
int test;

void test_fun(void);
#endif
main.c

#include "global.h"

void test_fun()
{
    printf("%d\n", test);
}
#include "global.h"

int main(void)
{
    test_fun();
    test = 1;
    printf("%d\n", test);
}
使用gcc编译器生成文件

main: main.o global.o
    gcc -o main main.o global.o

main.o: main.c global.h
    gcc -c main.c
global.o: global.c global.h
    gcc -c global.c

clean:
    rm -f global.o main.o main
main: main.o global.o
    g++ -o main main.o global.o

main.o: main.cpp global.h
    g++ main.cpp
global.o: global.cpp global.h
    g++ global.cpp

clean:
    rm -f global.o main.o main
这很有效

<>但是,当我将代码更改为C++时,如下:

global.h

#ifndef GLOBAL_H
#define GLOBAL_H
#include <stdio.h>
int test;

void test_fun(void);
#endif
#ifndef GLOBAL_H
#define GLOBAL_H
#include <iostream>
int test;

void test_fun(void);
#endif
上面的代码抛出输出:

global.o:(.bss+0x0): multiple definition of `test'

这里的不同之处是什么。。。您使用的是不同的编程语言

您已经进行了
int测试
位于包含在2个TUs中的标头中,因此出现错误。翻译单元
main.c
(或.cpp,取决于使用的编译器)和
global.c
都包含
global.h
,这会导致两个对象文件中相同变量的两个定义,从而导致链接器错误

通过
test
作为
test\u fun
的论据,从而避免使用全局变量

如果您必须在TU之间共享变量,则删除
int test
global.h
main.cpp
do

int test;
extern int test;
global.cpp
do

int test;
extern int test;
另一方面,由于它是一个全局变量,
test
将被初始化为
0
,因此当您
test_-fun()时,它将在
main
中被初始化
,它应该打印
0
,然后将其设置为1后,它将打印
1


从语言的角度来看,但至于它为什么与C编译器(如GCC)一起工作,是因为它们实现了。

我认为这与我使用
.C
文件还是
.cpp
文件无关。我刚才确认了我用“代码> > CPP</代码>文件取代了所有的<代码> .c/代码>文件,结果仍然是一样的。@ CARLSE0429—G+ +讲C++,GCC讲C,就像让一个法国人理解希腊语一样。Ed Heal是对的。在GCC中使用C++获得错误是很容易的。我认为你应该解释OPS问题:“为什么这个代码编译成C,但是编译成C++时产生这个错误?它看起来像是它使用C++支持的C子集。”C++支持C,但是可以有不同的行为。这就是为什么我们有
extern“C”
。我想你拼错了“extern”谢谢,我知道如何避免这个错误,但我想知道为什么
cpp
中的代码不能是
C++
程序?@Charles0429:这是因为C允许的暂定定义;看到我刚才添加的最后一行了。谢谢@legends2k,最后一行解决了我的问题。@Charles0429:很高兴这有帮助,但是,我发现它在C中也是非法的,现在检查最后一行,我已经用详细信息更新了它。可能的重复