Reputation: 336
I am newbie to c programming language. I have the following files in same directory under centos linux system.
game.c
game.h
main.c
game.h
#ifndef GAME_
#define GAME_
extern void game (void);
#endif
game.c
#include "game.h"
void game (void)
{
return 23;
}
main.c
#include "game.h"
int main (void)
{
game();
}
when I compile using the following command..
gcc main.c
I get the error message as below..
/tmp/ccwIlBKt.o: In function
main': main.c:(.text+0x7): undefined reference to
game' collect2: ld returned 1 exit status
What is the correct way to link my header file?
Upvotes: 3
Views: 4742
Reputation: 93
You should correct your code to this:
game.c
#include "game.h"
int game (void)
{
return 23;
}
main.c
#include "game.h"
int main (void)
{
game();
return 0;
}
Your game.c needs to have the correct return type (int rather than void) and your main method should always return 0 when done to inform that the program ended correctly.
Also I can highly recommend this book when learning C (also good for references for experienced programmers):
C Programming Language, 2nd Edition by Brian W. Kernighan
ISBN-13: 978-0131103627
Upvotes: 0
Reputation: 1833
You need to compile and link the two program.
First compile and create object files like this
gcc -c game.c
gcc -c main.c
Then you can generate executable file like this
gcc game.o main.o -o myexe
You can include library files using like this
gcc game.o main.o -o myexe -lsocket -wall
Here the lsocket is the socket library and using -wall displays if any warnings while linking the code
Upvotes: 7
Reputation: 1627
gcc game.c main.c
or
gcc *.c
You require to compile the game.c
, where the function game()
is implemented, that your main function (within main.c
) is referring to.
Also you shouldn't be returning a value from a void function. Just leave the body blank, or if you really want a return statement, just type return;
. i.e.
void game(void)
{
return;
}
Otherwise, if you want to return a value, change the declaration of the function to be:
<type-to-return> game(void)
{
return /* value */;
}
Upvotes: 0