使用-D构建c代码时出错

时间:2013-10-25 07:11:33

标签: c building

当我尝试使用-D构建我的c代码文件时,出现以下错误。但是,如果我在没有-D的情况下构建它,它就可以工作。我不知道为什么。谢谢。 (我的机器是ubuntu12.10,32bit)

gcc c1.c c2.c -D DEBUG

/tmp/ccX04EIf.o:(.data+0x0): multiple definition of `g'
/tmp/cc0j9MoU.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status

这是我的源代码:

global.h

#ifdef DEBUG 
    int g = 23;
    static int init = 1;
#else
    int g;
    static int init = 0;
#endif

c1.c

#include "global.h"
int f() {
    return g + 1;
}

c2.c

#include <stdio.h>
#include "global.h"

int main() {
    if (!init) {
        g = 37;
    }
    int t = f();
    printf("calling f yields %d\n", t);

    return 0;
}

2 个答案:

答案 0 :(得分:3)

在头文件中定义变量g,这意味着它将在包含头文件的所有源文件中定义。

声明,就像

一样
extern int g;

然后在单个源文件中定义它。

答案 1 :(得分:1)

两个代码路径(有和没有DEBUG)之间的差异是g变量的初始化。没有它,它只是一个“暂定”的定义,因此符号只在真正使用它的文件中生成,即c2.o

初始化时,它是符号的真实定义,因此它也在c1.o中生成。

根据经验,头文件不应包含数据定义,只能包含声明。数据“仅声明”应使用关键字extern进行。然后,您需要在一个.c文件中定义任何此类符号。