views:

292

answers:

2

I have a project consisting of two files, main.c and logoff.c. When I try to compile them I get this error:

gcc -c -g -Wall main.c
gcc -c -g -Wall logoff.c
gcc -o main -g -Wall main.o logoff.o
ld: duplicate symbol _logoff in logoff.o and main.o

I have a function named logoff in logoff.c, but I have searched main.c for the text "logoff" and have found nothing (the function is not even called yet!).

If I change the name of the function to log_off it works. There is a second function in the file which then causes the same error unless its name is changed as well.

Is there any reason why this might occur? I have this problem on two different systems. One thing that might be relevant is that I used the same logoff.c file in another project but it is not connected to this one.

+2  A: 

Do you #include or #import logoff.c in main.c?

You did - well there's your problem. logoff.c is being included in main.c, so main defines _logoff and _main. Now you also compile logoff.c, which defines _logoff. Then you try and link the two, which means the resulting binary includes the symbols _main, _logoff and _logoff, which is exactly what the linker is telling you about.

Graham Lee
+2  A: 

Create a logoff.h file with only the function declaration of logoff, like

void logoff(void);

Then, in main.c include it with #include "logoff.h". Don't include logoff.c, as the compiler will compile the function two times, and the linker will see two functions of that name then.

It appears to work if you change it to log_off, and then only recompile one of them. The other object-file will still have the old logoff function compiled in. Thus the linker sees one log_off and one logoff. That's the reason it appeared to work for you with that name.

Johannes Schaub - litb
It seems so obvious now... thanks.
titaniumdecoy