MeloS
MeloS

Reputation: 7938

relationship between .h and .c file in C

Possible Duplicate:
What is a “translation unit” in C++

Possible duplicate: What is a "translation unit" in C++

x.h :

void f();

x.c :

void f(){}

main.c :

#include"x.h"
int main(){
    f();
}

then I use: gcc -o a.out main.c why it say f is a undefined symbol?

Upvotes: 1

Views: 1304

Answers (5)

Jess
Jess

Reputation: 3049

It should say this during compiling, but probably during linking. You haven't compiled x.c yet (gcc -c x.c)?

Upvotes: 0

sigjuice
sigjuice

Reputation: 29777

This is because x.h merely contains a declaration, which does not define a symbol. x.c contains the definition.

Try

gcc -o a.out main.c x.c

Upvotes: 1

Robin Green
Robin Green

Reputation: 33083

Because f isn't defined in x.h, it's only declared. You need to link x.o into your executable. If you are not using an IDE, you might want to set up a Makefile to handle this, and call make to build your project.

Upvotes: 0

Tommy
Tommy

Reputation: 1267

You also have to include the x.h in the x.c file, and make sure that the definition is not used twice by the following code:

#ifndef X_H
#define X_H
f();
#endif

And then use gcc -o a.out main.c x.c

Upvotes: 0

Mat
Mat

Reputation: 206841

That's a linker error. You need to compile main.c and x.c at the same time, or compile them separately without linking and link the resulting object files.

For example:

gcc -o x.o -c x.c
gcc -o main.o -c main.c
gcc -o myexecutable main.o x.o

Upvotes: 4

Related Questions