1

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?

Community
  • 1
  • 1
CarmeloS
  • 7,868
  • 8
  • 56
  • 103
  • The OP is trying to understand the fundamental difference between .c and .h files. IMHO, "translation unit" does not explain that. – sigjuice Apr 23 '11 at 10:18
  • 1
    I think the OP is actually confused about how the compiler works (i.e. he may expect that because `main.c` included `x.h` the compiler would know to look for `x.c`), but in any case there *is* a question here and it is *not* identical to the proposed duplicate. – dmckee --- ex-moderator kitten Apr 23 '11 at 18:51
  • Possible duplicate of [What is a "translation unit" in C++](https://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c) – Cœur Jul 11 '18 at 16:54

5 Answers5

4

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
Mat
  • 202,337
  • 40
  • 393
  • 406
1

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
sigjuice
  • 28,661
  • 12
  • 68
  • 93
0

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

Tommy
  • 1,277
  • 1
  • 11
  • 22
0

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.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
0

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

Jess
  • 2,991
  • 3
  • 27
  • 40