开发者

Statically and dynamically linking the same library on Linux

I have a shared object/executable that link both statically and dynamically to the same library .

Library: liba.a and liba.so

liba.a created using : ar -rv liba.a a.o , contains libprint() --> prints "static5"

liba.so created using: gcc -shared -o liba.so -Wl,-h,liba.so a.o , contains libprint() prints "dynamic5" , libprint2() prints "dynamic6"

Exe b created by linking to both archive and shared object:

When linking with GCC/Linux, i find that the implementation called is ALWAYS from liba.a .

I have a function libprint() defined in liba.so, liba.a that prints out a different value. From what i see, this is based on the link order:

gcc -o b b.o liba.a liba.so -lc ./b

static5 dynamic6

gcc -o b b.o liba.so liba.a -lc ./b

dynamic5 dynamic6

Why we would intentionally need to link to the .a and .so for the same library?:

How do we get the shared object to take preference over the archive, other than link order? ( -dy / -Bdynamic does not seem to have any effect?)

1. If the shared object is missing, the exe fails with an error 2. We can place any dummy shared object with the same name , just to satisfy the dlopen() 3. Even once the shared object is loa开发者_如何学Goded , the function from the archive is called

Update #2 Here is the actual problem ( as mentioned in Statically and dynamically linking the same library )

libd.so is linked to shared object liba.so

ldd libd.so liba.so => ./liba.so

b is linked to shared-object libd.so and archive liba.a .

gcc -o b b.o libd.so liba.a -lc ldd b libd.so => ./libd.so liba.so => ./liba.so

Now, b seems to call the function from archive first, and then the shared-object.

So , even if we update the liba.so , these changes will not reflected in b . Is there any way around this ?


When you put the .a first, the linker finds libprint() in it and links it, but not libprint2(). It continues searching the libraries in order to find the other function, and finds it in the .so.

When you put the .so first, both functions are found and linked successfully, hence there's no need to look for them any further.

There should be no reason to link both the static and dynamic versions of the same library, since either should provide all functions found in the other.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜