Matteo Ceccarello
Matteo Ceccarello

Reputation: 231

How gcc linker works in including files

This is really a newbie question. I'm learning C, and I don't understand how to link together different files.

I have a header like

/* file2.h */

int increment(int x);

and a C file

/* file2.c */

#include "file2.h"

int increment(int x)
{
    return x+1;
}

Now I want to include the header in file1.c in order to use the function increment. From what I have understood I have to do something like:

/* file1.c*/

#include "file2.h"

int main()
{
    int y = increment(1);
    return 0;
}

But when I try to compile the whole thing, using

gcc -o program file1.c

I get an error message like

/tmp/ccDdiWyO.o: In function `main':
file1.c:(.text+0xe): undefined reference to `increment'
collect2: ld returned 1 exit status

However if I include also file2.c

/* file1.c*/

#include "file2.h"
#include "file2.c"  /* <--- here it is! */

int main()
{
    int y = increment(1);
    return 0;
}

Everything works as expected.

But if I have understood only the header file (with only declarations in it) has to be included. So how can I inform gcc that the definition of function increment declared in file2.h is in file2.c?

Upvotes: 2

Views: 1182

Answers (2)

fazo
fazo

Reputation: 1827

gcc -o program file2.c file1.c

this will compile file1.c and file2.c and link them together.

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 225172

The easiest way is to compile them both directly:

$ gcc -o program file1.c file2.c

But for more complicated systems you might want to do it in steps. Here's a simple command line recipe:

$ gcc -c file1.c
$ gcc -c file2.c
$ gcc -o program file1.o file2.o

Even better for something complicated like this would be to use make, though.

Aside from your specific problem, why are you using GCC? You could use clang and get better error messages, faster compiling, and feel like you're living in the future!

Upvotes: 7

Related Questions