C头问题:#include和"未定义引用"

use*_*501 23 c gcc header header-files undefined-reference

好吧,我一直试图用这个工作的时间最长,而我似乎无法让它正常工作.我有三个文件,main.c,hello_world.c,和hello_world.h.无论出于何种原因,他们似乎没有很好地编译,我真的无法弄清楚为什么......

这是我的源文件.首先是hello_world.c:

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

int hello_world(void) {
  printf("Hello, Stack Overflow!\n");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后hello_world.h,简单:

int hello_world(void);
Run Code Online (Sandbox Code Playgroud)

最后是main.c:

#include "hello_world.h"

int main() {
  hello_world();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我把它放入GCC时,这就是我得到的:

cc     main.c   -o main
/tmp/ccSRLvFl.o: In function `main':
main.c:(.text+0x5): undefined reference to `hello_world'
collect2: ld returned 1 exit status
make: *** [main] Error 1

有人能帮帮我吗?我真的坚持这个,但我99%肯定这是一个非常简单的修复.

Lun*_*din 39

gcc main.c hello_world.c -o main
Run Code Online (Sandbox Code Playgroud)

此外,始终使用标题保护:

#ifndef HELLO_WORLD_H
#define HELLO_WORLD_H

/* header file contents go here */

#endif /* HELLO_WORLD_H */
Run Code Online (Sandbox Code Playgroud)


P.P*_*.P. 9

您没有在编译中包含hello_world.c.

   gcc hello_world.c main.c   -o main
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 5

您没有针对hello_world.c进行链接。

一种简单的方法是运行以下编译命令:

cc -o main main.c hello_world.c

较复杂的项目通常使用构建脚本或制作将编译和链接命令分开的文件,但是上述命令(将两个步骤组合在一起)对于小型项目应该很好。