Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 541
Matteo Ceccarello Avatar asked Jan 17 '26 20:01

Matteo Ceccarello


2 Answers

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!

like image 100
Carl Norum Avatar answered Jan 20 '26 11:01

Carl Norum


gcc -o program file2.c file1.c

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

like image 34
fazo Avatar answered Jan 20 '26 11:01

fazo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!