Search code examples
cgccheaderheader-filesundefined-reference

C header issue: #include and "undefined reference"


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

Solution

  • 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 */