clinkerduplicate-symbol

Why is my code not throwing a duplicate symbol conflict


Why is my following code not throwing duplicate symbol conflict?

I referred to name mangling, but that seems only when there is difference in parameters. But, here there is not difference in parameters. But, still it does not throw conflict. Why?

good.c

#include <stdio.h>

void printGood() {
    printf("I am good");
}

perfect.c

#include <stdio.h>

void printGood() {
    printf("I am perfect");
}

A.c

extern void printGood();

void bringGood() {
    printGood();
}

B.c

extern void printGood();

void bringPerfect() {
    printGood();
}

orchestrator.c

#include <stdio.h>

void bringGood();
void bringPerfect();

int main() {
    printf("bringing good");
    bringGood();
    printf("bringing perfect");
    bringPerfect();
    return 1;
}

compile line:

gcc -g -c good.c
gcc -g -c perfect.c

gcc -g -c A.c
gcc -g -c B.c

gcc -g -c orchestrator.c

ar rcs libA.a perfect.o A.o
ar rcs libB.a  good.o B.o

gcc -o orchestrator orchestrator.o -L.  -lA -lB


Solution

  • Why is my following code not throwing duplicate symbol conflict?

    The linker looks for undefined symbols in the libraries in the order in which they are specified in the linker line. When it finds a symbol in a library, it uses that definition and stops. It does not check whether that symbol is defined in any of the other libraries specified in the linker line.

    In your case, if the linker finds a symbol in A.lib, it stops there. It does not look for the symbol in B.lib.

    With your commands, the linker will find function printGood() in object perfect.o in library A. It will not use the function of the same name in good.o from library B. So you effectively link orchestrator.o, A.o, B.o and perfect.o. That's why the executable program prints I am perfect twice and not I am good.

    Multiple definition errors are reported only when the object files used in the linker line contain multiple definitions.

    You will see the error if you use:

    gcc -o orchestrator orchestrator.o a.o b.o perfect.o good.o