Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined reference to <function name>

Tags:

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,

like image 522
user1508893 Avatar asked Oct 03 '12 05:10

user1508893


People also ask

How do you fix a undefined reference in C++?

You can fix undefined reference in C++ by investigating the linker error messages and then providing the missing definition for the given symbols. Note that not all linker errors are undefined references, and the same programmer error does not cause all undefined reference errors.

How do you fix undefined error in C?

c file. The error: undefined reference to function show() has appeared on the terminal shell as predicted. To solve this error, simply open the file and make the name of a function the same in its function definition and function call. So, we used to show(), i.e., small case names to go further.

How do you solve undefined references to Main?

The error: undefined reference to 'main' in C program is a very stupid mistake by the programmer, it occurs when the main() function does not exist in the program. If you used main() function and still the error is there, you must check the spelling of the main() function.

How do I fix linker error?

You can fix the errors by including the source code file that contains the definitions as part of the compilation. Alternatively, you can pass . obj files or . lib files that contain the definitions to the linker.


1 Answers

 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.

like image 195
Jonathan Leffler Avatar answered Sep 29 '22 04:09

Jonathan Leffler