views:

469

answers:

4

I am working in Linux, Eclipse CDT, g++, with Boost library. Having existing program which uses Boost thread, I try to link it statically instead of dynamically. /usr/local/lib directory contains the following files:

libbost_thread.a
libbost_thread.so
libbost_thread.1.41.0

Dynamic linking works:

g++  -o"MyProgram"  ./main.o   -lboost_thread

Static linking:

g++ -static -o"MyProgram"  ./main.o   -lboost_thread

produces huge number of messages like:

undefined reference to `pthread_mutex_init'

How can I link statically to the Boost library?

+1  A: 

Try adding -lpthread to your invocation.

Dirk Eddelbuettel
+5  A: 

For pthread_mutex_init, you want to compile/link with -pthread option:

g++ -static -pthread -o"MyProgram"  ./main.o   -lboost_thread

The problem is that functions like pthread_mutex_init are in a separate library. Dynamic libraries can include the metadata for the fact that it needs the separate library (so libboost_thread.so includes the fact that it needs libpthread).

But static libraries don't have that information. So you need to provide the reference to any necessary libraries when you link statically.

As for using -pthread instead of -lpthread, it's slightly preferable because it not only links the necessary library, but provides any other options that should be used (such a -D_REENTRANT to the compiler).

R Samuel Klatchko
+1 for mentioning the important distinction between `-lpthread` and `-pthread`
D.Shawley
-static -pthread Thank you, finally it succeeded! What is -pthread? Something boost-specific or linker option? It looks like a magic for me, but I need to understand this.I also work with Boost Program Options (-lboost_program_options), what switch should I use to link it statically?
Alex Farber
@AlexFarber: -pthread is a gcc option. It tells the compiler to properly build your code for threading.
R Samuel Klatchko
+1  A: 

On Linux a dynamic library may automatically depend on other dynamic libraries so that when you link it, you get the other libraries for free. When linking statically, there is no such system and you have to specify the other libraries manually.

Tronic
A: 

Try this:

g++  -o"MyProgram"  ./main.o   /usr/local/lib/libboost_thread.a

If you have libboost_thread.a and libbbost_thread.so and use -lboost_thread, it will link to the shared library.

Dmitry Yudakov