2

How can I use both C++ shared and static libraries in a same Linux program?

When managing with g++, I've tried to arrange -static command ahead and behind the libraries I don't want to link statically, but with no results. ld through g++ complains about where are the .a files of the shared libraries (cannot find -lwhatever error).

EDIT: the problem isn't the cannot find -lwhatever error, since it just happens because there isn't static version of the specified library. What I'm trying to do is to specify which libraries are to be statically linked and which are to be dynamically.

0

2 Answers 2

6

Assuming a static libfoo.a and a dynamic libbar.so you could use

g++ -o prog main.o other.o -Wl,-Bstatic -lfoo -Wl,-Bdynamic -lbar

You should avoid calling functions in a static library from a dynamic one; this would be ugly.

hint

The -Wl options to g++ are used to pass arguments to the ld linker invoked by g++.

You may want to use g++ -v to understand how g++ invokes ld, and you could also use g++ -v -Wl,--verbose to also ask ld to be verbose.

Sign up to request clarification or add additional context in comments.

5 Comments

OK, so you are forcing it to look for the static or dynamic version of some lib. But if you only have a static version of foo and a dynamic version of bar. Do you really need to specify static/dynamic??
I think your answer is addressing the issue. When I use your parameters it looks ld accepts them but further I got the error cannot find -lgcc_s. Then, I add the -static-libgcc flag and I got the error dynamic STT_GNU_IFUNC symbol strcmp with pointer equality in /usr/lib/gcc/x86_64-linux-gnu/4.6.1/../../../x86_64-linux-gnu/libc.a(strcmp.o)' can not be used when making an executable; recompile with -fPIE and relink with -pie` Any suggestion? I'm investigating on this.
Ups, in this case I think -Bstatic and -Bdynamic have no effect, those commands are only for VxWorks: gcc.gnu.org/onlinedocs/gcc-4.3.4/gcc/VxWorks-Options.html. On my project nothing happens with or without them.
I wrote -Wl,-Bstatic which passes -Bstatic to ld, so should have some effect (and also works on x86). Use g++ -v to understand how ld is run by gcc, and use g++ -v -Wl,--verbose to understand what ld is doing.
Thanks Basile, you were absolutely right. My question was too much newbie. But your feedback has been very useful for me. :)
2

You do not need to specify -static or -dynamic. The format of the file you link with specify if it is a shared or a static link. You just need to choose the correct file to link with.

1 Comment

OK, I reading little bit to fast, you mean both static and shared libstdc++ ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.