Strange ld error about duplicate character
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 called logoff in logoff.c, but I searched main.c for the text "logoff" and found nothing (the function is not called yet!).
If I change the function name to log_off it works. There is a second function in the file, which then raises the same error if its name does not change either.
Is there any reason why this might be happening? I have this problem on two different systems. One thing that might make a difference is that I used the same logoff.c file in another project, but it is not related to this.
source to share
Create logoff.h file only with logout function declaration like
void logoff(void);
Then in main.c include it with #include "logoff.h"
. Do not include logff.c, as the compiler will compile the function twice and the linker will see two functions of that name.
It works if you change it to log_off and then only recompile one of them. Another object file will still retain the old logout function. So the linker sees one log_off and one logoff. This is the reason it worked for you with that name.
source to share
Do you #include or #import logoff.c in main.c?
You did - well, there is your problem. logoff.c is included in main.c, so main defines _logoff and _main. Now you also compile the logoff.c file that defines _logoff. Then you try to link the two, which means the resulting binary contains the characters _main, _logoff and _logoff, which will tell you about the linker.