rafael chen
rafael chen

Reputation: 3

I can have two main function in two static library of C++ when I link both of them?

I have three files:

test.cpp (it is empty) :


main1.cpp

int main()
{
    printf("main_1\n");
    return 0;
}

main2.cpp

int main()
{
    printf("main_2\n");
    return 0;
}

then I create two static library main1.a and main1.a.

g++ -c main1.cpp

ar r main1.a main1.o

g++ -c main2.cpp

ar r main2.a main2.o

I found that the output will different depends on the order of main1.a and main2.a as

why it will not have the error message "multiple definition of `main'" as the command?:

g++ -o out test.cpp main1.cpp main2.cpp

Upvotes: 0

Views: 542

Answers (1)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31153

The linker handles these two cases very differently (by default). When compiling code into object files and linking them the linker will not allow two strong definitions to exist. Strong here is for example a function or a variable with a set value. It will allow one strong and multiple weak ones (like a variable with a set value in one object and another with the same variable but no set value).

With static libraries the linker goes through them in the order they’re given. It looks up the exports, if any of them are needed by the other linked objects it takes it in and restarts the process in that file (to find the functions the just found function possibly needs). So in this process when it gets to the first library it checks for its exports, sees main, determines it’s needed and takes it in. Then it goes to the second library, sees main, doesn’t see it in the list of undefined symbols and just skips it.

More information can be found on Eli Bendresky’s website

Upvotes: 0

Related Questions