c - 多个定义,即使我正在使用 extern 并包含守卫

标签 c makefile global-variables extern

这是我的头文件。

#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/

相关文章:

c - 同一用户不同进程读写文件时文件模式的影响

python - 全局变量没有传递,说它不被识别?

c - 避免使用相似的结构重复代码 C

android - 将 Android NDK make 文件重构为模块

c++ - GNU 使 : A better way of using both C/C++ targets with different commands

c++ - 从链接中排除目标文件

android - 如何使全局对象的数据适应微调器

ruby - 获取在 Ruby 中打印的最后一行

c - 为什么 GCC pad 与 NOP 一起起作用?

c - 重写 C 中的函数调用