undefined reference to <function name>

user1508893 picture user1508893 · Oct 3, 2012 · Viewed 53.4k times · Source

I have this simple test file:

#include "stack.h"

int main()
{
  Stack* stck = init_stack();

  return 0;
}

and stack.h is defined as follows:

#ifndef STACK_H
#define STACK_H

#define EMPTY_STACK -1
typedef struct stack
{
  char ch;
  struct stack* prev;
} Stack;

extern Stack* init_stack();

extern char pop(Stack*);

extern void push(Stack*, char);

#endif

These two files are in the same directory. But when I do gcc .. to build it, I keep getting the error below:

$ ls
stack.c  stack.h  teststack.c
$ gcc -o testit teststack.c 
/tmp/ccdUD3B7.o: In function `main':
teststack.c:(.text+0xe): undefined reference to `init_stack'
collect2: ld returned 1 exit status

Could anyone tell me what I did wrong here?

Thanks,

Answer

Jonathan Leffler picture Jonathan Leffler · Oct 3, 2012
 gcc -o testit teststack.c stack.c

You need to compile both C source files and link the object files; this does it all in one command.