saplingPro
saplingPro

Reputation: 21319

getting errors while trying to link one c file to another

I am trying to separately compile each of the c file and then link them together as a single executable file. Following are the 2 c files :

file1.c

#include <stdio.h>

void display();
int count;

int main() {
 printf("Inside the function main\n");
 count = 10;
 display();
}

file2.c

#include <stdio.h>

extern int count;
void display() {
  printf("Sunday mornings are beautiful !\n");
  printf("%d\n",count);
}

But when I try to compile them , I get some errors :

When I compile file1.c

gcc file1.c -o file1
/tmp/ccV5kaGA.o: In function `main':
file1.c:(.text+0x20): undefined reference to `display'
collect2: ld returned 1 exit status

When I compile file2.c

gcc file2.c -o file2
/usr/lib/gcc/i686-redhat-linux/4.6.3/../../../crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
/tmp/cczHziYd.o: In function `display':
file2.c:(.text+0x14): undefined reference to `count'
collect2: ld returned 1 exit status

What mistake am I committing ?

Upvotes: 1

Views: 821

Answers (3)

mickeyreiss
mickeyreiss

Reputation: 490

You have two options here:

1) Compile both c files in one compilation unit. This means that each file is compiled and then they are immediately linked.

gcc file1.c file2.c -o program

The downside to this technique is that a change to either file will require complete recompilation from scratch. In a larger project, this could be a waste of time.

2) Use a .h file to declare the functions and include this .h file in both .c files. Be sure to #include your .h file in each .c file that invokes or implements its functions.

file1.h:

void display();

Then, compile each .c file with the -c flag. This prevents gcc from linking the code prematurely. Finally, link the two compiled files with gcc.

In summary:

gcc -c file1.c -o file1.o
gcc -c file2.c -o file2.o
gcc file1.o file2.o -o myprogram

I would recommend taking a look at Makefiles, which can help you automate this process.

Upvotes: 2

Brian Cain
Brian Cain

Reputation: 14619

You must link them into a single executable.

gcc -c file1.c -o file1.o
gcc -c file2.c -o file2.o
gcc file1.o file2.o -o theprogram

Upvotes: 2

Michael Burr
Michael Burr

Reputation: 340168

You are compiling each separately, but the problem is that you're also trying to link them separately.

gcc file1.c file2.c  -o theprogram   # compile and link both files

or:

gcc -c file1.c        # only compiles to file1.o
gcc -c file2.c        # only compiles to file2.o

gcc file1.o file2.o -o the program   # links them together

Upvotes: 4

Related Questions