c++ boost library problem: cannot find -lboost_system ld returned 1 exit status

I have a problem with boost. After I installed boost with following command

sudo apt-get install python-dev 
sudo apt-get install libboost-python1.54 
sudo apt-get install libboost-system1.54 libboost-filesystem1.54 
tar -zxf Boost-2014.10.tar.gz 
cd ~/build-2014.10/ 
./bootstrap.sh 
sudo ./b2 install -j8 --prefix=/usr --libdir=/usr/lib --includedir=/usr/include --build-type=minimal variant=release --layout=tagged threading=single threading=multi

boost version is 1.57. Then I run an example to test. code like

#include <iostream>
using namespace std;
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
int main(){
    cout<<"hello"<<endl;
     int a=boost::lexical_cast<int>("123456");
     cout<<"boost "<<a<<endl;
     return 1;} 

Then I compile it, error shows

g++ test -o test.cpp -lboost_system
/usr/bin/ld: cannot find -lboost_system
collect2: error: ld returned 1 exit status

If I remove line

#include <boost/filesystem.hpp>

and compile it with

g++ test -o test.cpp it works.

How to solve it?


Solution 1:

Make sure you understand the difference between header files and libraries.

Header files (like /usr/include/boost/filesystem.hpp) is what you use in your source code as part of your #include directive. The C++ preprocessor reads that file and adds a bunch of declarations to your program.

A library is a compiled collection of various functions, static data and other stuff. When you use parameter -lboost_system you tell the compiler "Compile my program and link it with library libboost_system".

Your linker complains that it can't find that library (/usr/bin/ld: cannot find -lboost_system). The likely reason is that script ./bootstrap.sh did not install boost in the proper directories.

From here on you have a couple of options.

If you want to stick to Boost-2014.10.tar.gz you are on your own.

I would recommend installing package libboost-dev. It will install whatever is the current version of boost for your system and will put all files in the proper places.

And finally: when you removed the #include line from your file it worked but only because your program does not use any functionality from boost::system. If you were to use any boost classes/functions you would get compile errors if you don't have proper headers included.