gpt4 book ai didi

c - 如何组织头文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:17 24 4
gpt4 key购买 nike

以这种方式使用头文件会出现错误“对 somefunc 的 undefined reference ”。确保看到 somefunc.c 以便不会发生此错误的正确方法是什么?似乎只是在 main.c 中包含 somefile.h 不足以查看 somefile.c

中的定义

ma​​in.c

#include "somefile.h"
int main() {
somefunc();
return 0;
}

somefile.h

#ifndef SOMEFILE_H
#define SOMEFILE_H

void somefunc();

#endif

somefile.c

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

void somefunc() {
printf("hello\n");
}

我不明白为什么会出现错误,因为这与我在寻找答案时一直在观看的教程和视频中使用错误的方式相同。上面的代码是之前给出的答案,但仍然有同样的错误。

最佳答案

somefunc 的 undefined reference 是链接器错误,而不是编译器错误。

这意味着,虽然在编译 main.c 时找到了 header somefile.h,但您并未编译文件 somefile.cmain.c 一起。因此,当链接发生时,链接器无法在任何目标文件中找到 somefunc 的实现来解析来自 main() 的调用。

如果您使用的是 GCC 或 Clang,只需将两个源文件编译为您的命令,例如

gcc somefunc.c main.c -o output

如果您改用 IDE,请确保在构建应用程序时 somefile.cmain.c 一起编译。

关于c - 如何组织头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32814508/

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