开发者

Why I'm not getting "Multiple definition" error from the g++?

开发者 https://www.devze.com 2023-02-04 09:30 出处:网络
I tried to link my executable program with 2 static libraries using g++. The 2 static libraries have the same function name. I\'m expecting a "multiple definition" linking error from the lin

I tried to link my executable program with 2 static libraries using g++. The 2 static libraries have the same function name. I'm expecting a "multiple definition" linking error from the linker, but I did not received. Can anyone help to explain why is this so?

staticLibA.h

#ifndef _STATIC_LIBA_HEADER
#define _STATIC_LIBA_HEADER

int hello(void);

#endif

staticLibA.cpp

#include "staticLibA.h"

int hello(void)
{
    printf("\nI'm in staticLibA\n");
    return 0;
}

output:

g++ -c -Wall -fPIC -m32 -o staticLibA.o staticLibA.cpp          开发者_如何学JAVA                                                                   
ar -cvq ../libstaticLibA.a staticLibA.o                                                                                                                           
a - staticLibA.o 

staticLibB.h

#ifndef _STATIC_LIBB_HEADER
#define _STATIC_LIBB_HEADER

int hello(void);

#endif

staticLibB.cpp

#include "staticLibB.h"

int hello(void)
{
    printf("\nI'm in staticLibB\n");
    return 0;
}

output:

g++ -c -Wall -fPIC -m32 -o staticLibB.o staticLibB.cpp 
ar -cvq ../libstaticLibB.a staticLibB.o 
a - staticLibB.o

main.cpp

extern int hello(void);

int main(void)
{
 hello();
 return 0;
}

output:

g++ -c  -o main.o main.cpp
g++ -o multipleLibsTest main.o  -L. -lstaticLibA -lstaticLibB -lstaticLibC -ldl -lpthread -lrt


The linker does not look at staticLibB, because by the time staticLibA is linked, there are no unfulfilled dependencies.


That's an easy one. An object is only pulled out of a library if the symbol referenced hasn't already been defined. Only one of the hellos are pulled (from A). You'd get errors if you linked with the .o files.


When the linker tries to link main.o into multipleLibsTest and sees that hello() is unresolved, it starts searching the libraries in the order given on the command line. It will find the definition of hello() in staticLibA and will terminate the search.

It will not look in staticLibB or staticLibC at all.

If staticLibB.o contained another symbol not in staticLibA and that was pulled into the final executable, you then get a multiple definition of hello error, as individual .o files are pulled out of the library and two of them would have hello(). Reversing the order of staticLibA and staticLibB on the link command line would then make that error go away.

0

精彩评论

暂无评论...
验证码 换一张
取 消