C header issue: #include and “undefined reference”

孤人 提交于 2019-12-03 07:42:22

问题


Alright, I've been trying to work with this for the longest time, and I simply can't seem to get it to work right. I have three files, main.c, hello_world.c, and hello_world.h. For whatever reason they don't seem to compile nicely, and I really just can't figure out why...

Here are my source files. First hello_world.c:

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

int hello_world(void) {
  printf("Hello, Stack Overflow!\n");
  return 0;
}

Then hello_world.h, simple:

int hello_world(void);

And then finally main.c:

#include "hello_world.h"

int main() {
  hello_world();
  return 0;
}

When I put it into GCC, this is what I get:

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

Anyone able to help me out? I'm really stuck on this, but I'm 99 percent sure it's a really simple fix.


回答1:


gcc main.c hello_world.c -o main

Also, always use header guards:

#ifndef HELLO_WORLD_H
#define HELLO_WORLD_H

/* header file contents go here */

#endif /* HELLO_WORLD_H */



回答2:


You are not including hello_world.c in compilation.

   gcc hello_world.c main.c   -o main



回答3:


You are not linking against hello_world.c.

An easy way to do this is to run this compilation command:

cc -o main main.c hello_world.c

More complicated projects often use build scripts or make files that separate the compilation and linking commands, but the above command (combining both steps) should do fine for small projects.




回答4:


You should link object file compled from your second .c file hello_world.c with your main.o

try this

cc -c main.c
cc -c hello_world.c
cc *.o -o hello_world



回答5:


Ya it seems you have forgotten to link hello_world.c. I will be gcc hello_world.c main.c -o main. If the number of files are less we can use this approach but in larger projects better to use Make files or some compilation scripts.



来源:https://stackoverflow.com/questions/10357117/c-header-issue-include-and-undefined-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!