gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:52:07 24 4
gpt4 key购买 nike

由于我正在制作我的头文件之一,因此目前正在尝试在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com