Boost static linking
Asked Answered
M

2

13

I am using the Boost library in Linux, GCC. After installing and building the Boost, I found that programs using Regex and Thread use shared Boost libraries. For my purposes, I need static linking. How can I change linking type? Should I rebuild the Boost, or maybe I can set linking type by defining some constant in my own projects or Boost configuration files?

Many answered 24/2, 2010 at 18:25 Comment(0)
P
20

Just add -static to your build invocation. Here is a quick example session:

$ cat boost_formatted_time.cpp
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_io.hpp>

using namespace boost::posix_time;
using namespace std;

int main(int argc, char **argv) {
  time_facet *facet = new time_facet("%d-%b-%Y %H:%M:%S");
  cout.imbue(locale(cout.getloc(), facet));
  cout << second_clock::local_time() << endl;
}
$ g++ -o /tmp/bft_dyn boost_formatted_time.cpp -lboost_date_time
$ g++ -static -o /tmp/bft_stc boost_formatted_time.cpp -lboost_date_time
$ ls -lh /tmp/bft_*
-rwxr-xr-x 1 edd edd 216K 2010-02-24 12:34 /tmp/bft_dyn    
-rwxr-xr-x 1 edd edd 1.5M 2010-02-24 12:34 /tmp/bft_stc    
$ /tmp/bft_dyn
24-Feb-2010 12:34:55
$ /tmp/bft_stc
24-Feb-2010 12:34:59
$

Note how the static binary is 1.5mb as opposed to 216kb for the dynamically-linked variant. All done on Debian testing with the default Boost packages.

Phelloderm answered 24/2, 2010 at 18:39 Comment(2)
I don't run gcc from the command line, I am using Eclipse CDT. Possibly -static switch can be passed to the linker from the Project Settings, I will try to find this way. Thank you.Many
Does -static has the effect on all libraries, when more than 1 library included?Femmine
M
0

Specify -Lpath/to/library/ to the linker.

Maclay answered 24/2, 2010 at 18:31 Comment(2)
I have no problems with a project build and library path, I just need to change the linking type: from dynamic to static.Many
That is not correct -- you need -static. The -L gives the location of the library but not the linking type. See my answer for a full session.Phelloderm

© 2022 - 2024 — McMap. All rights reserved.