c - GCC 和 Makefile(一个函数的多个声明,即使只有一个?)

标签 c gcc makefile

由于我正在制作我的头文件之一,因此目前正在尝试在 Debian 上使用 GCC 以及 makefile。每当我尝试“制作”makefile 时,都会收到如下错误:

setup.o: In function 'setup':

setup.c:(.text+0x0): multiple definition of `setup'

finalkek.o:finalkek.c:(.text+0x0): first defined here

collect2: ld returned 1 exit status

make: *** [projExec] Error 1

我的 makefile 如下所示:

projExec: finalkek.o setup.o
    gcc -o projExec finalkek.o setup.o

finalkek.o: finalkek.c setup.h
    gcc -c finalkek.c

setup.o: setup.c
    gcc -c setup.c

finalkek.c 是我的主文件,setup 是我的 header 。

在我的主文件中,这是我唯一一次提到它:

include "setup.h" // Using the double quotes for a custom header...

void main()
{

setup();

       rest of code here...

}

在我的头文件 setup.h 中,我有这样的内容:

void setup()
{

      rest of code here...

}

最佳答案

我注意到的一些事情:虽然技术上允许,但在头文件中实现整个函数是有缺陷的做法。头文件仅用于原型(prototype)(即 void setup(void); 而不是整个 void setup(void) { ... })。你的 setup.c 里有什么?另外,Make 不应该这样工作。

finalkek.o: finalkek.c setup.h
    gcc -c finalkek.c

您不应该直接编译头文件,因为它不应该有实际的实现,而只有原型(prototype)。这就是预处理器所做的事情,使用指令 #include,它获取指定 header 的全部内容,然后将其放在 C 文件中。因此,通过告诉 Make 编译 setup.h,您将该文件的内容包含在项目中两次,这可能会导致错误。

就像其他人所说的那样,将函数 setup() 的实际代码移至 setup.c(如果合适)。 setup.h 应该如下所示:

#ifndef SETUP_H
#define SETUP_H

void setup(void);

#endif

#ifndef SETUP_H、#define SETUP_H#endif 行是头文件的格式化工具,可防止您多次包含同一文件.

然后是随附的 setup.c:

#include "setup.h"

void setup(void) {
    // your code here
}

finalkek.c:

int main(void) {
    setup();

    // rest of code here
}

关于c - GCC 和 Makefile(一个函数的多个声明,即使只有一个?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47744291/

相关文章:

c++ - 如何获取 UPS 的状态?

linux - 生成文件错误 "/usr/bin/f77: Illegal option: -autodouble"

bash - 使用变量创建命令

c - double in decimal 和 floating 的精确值?

c - 我的 Vigenere Cypher CS50 有什么问题

c - 嵌入时如何使用LuaJIT的ffi模块?

c++ - 不同 C++ 编译器之间自动类型推导不匹配

gcc - gcc从stdin读取gnu readline()的编译错误

C - 具有命名参数的函数指针类型

makefile - 将目录中的所有C文件编译为单独的程序