这是我的头文件。
#ifndef P6_H
#define P6_H
#include <stdio.h>
void FoundationC();
void StructureC();
void PlumbingC();
void ElectricC();
void HVACC();
void SheatingC();
extern int DAYS;
#endif
我正在使用 makefile 进行所有编译。它能够编译单个 .o 文件文件,但是当它尝试将这些文件转换为单个可执行文件时,它说变量 DAYS 有多个定义,即使它是外部的并且在每个单独的声明和初始化中也是如此。我之前让这个工作,但无法弄清楚为什么它现在不起作用。 哦,这是我的 makefile 代码
all:
gcc -c P6.c
gcc -c foundations.c
gcc -c structure.c
gcc -c plumbing.c
gcc -c electric.c
gcc -c hvac.c
gcc -c sheating.c
gcc P6.h P6.o foundations.o structure.o plumbing.o electric.o hvac.o sheating.o -o P6
我意识到 P6.h 可能不必包含在命令中,但包含守卫应该无关紧要,不是吗?
另外,如果这个问题是一个骗局,我很抱歉,但我之前确实在寻找答案,这个问题在个人层面上让我发疯,尽管事实上这是针对学校的。
这是我得到的错误。
gcc -c P6.c
gcc -c foundations.c
gcc -c structure.c
gcc -c plumbing.c
gcc -c electric.c
gcc -c hvac.c
gcc -c sheating.c
gcc P6.h P6.o foundations.o structure.o plumbing.o electric.o hvac.o sheating.o -o P6
structure.o:(.data+0x0): multiple definition of `DAYS'
foundations.o:(.data+0x0): first defined here
plumbing.o:(.data+0x0): multiple definition of `DAYS'
foundations.o:(.data+0x0): first defined here
electric.o:(.data+0x0): multiple definition of `DAYS'
foundations.o:(.data+0x0): first defined here
hvac.o:(.data+0x0): multiple definition of `DAYS'
foundations.o:(.data+0x0): first defined here
sheating.o:(.data+0x0): multiple definition of `DAYS'
foundations.o:(.data+0x0): first defined here
collect2: error: ld returned 1 exit status
make: *** [all] Error 1
最佳答案
为了帮助大家理解,下面是对@FUZxxl的回答的扩展,是正确的。如果您的编译单元中有以下内容(编译单元是 .c 源文件加上所有包含的 .h 文件):
extern int DAYS;
...
int DAYS = 1;
然后 DAYS
的第二个声明会覆盖声明它是一个 extern
的第一个声明。因此,该变量现在不再是一个 extern
,如果您在多个源文件中执行此操作,您现在就会有多个定义,并且链接器会报错。
如果您必须初始化 DAYS
,那么您可以在一个地方执行此操作,最好是在主文件中。
关于c - 多个定义,即使我正在使用 extern 并包含守卫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33952345/