Saturday, November 22, 2014

Undefined References to Boost Libraries - Solution

Yesterday, I was trying to compile a C++ source that uses Gnuplot-iostream interface. I issued the following compilation command:
$ g++ -std=c++11 -lboost_iostreams -lboost_system -lboost_filesystem ProcessScheduler.cpp 
/tmp/cchNNC8H.o: In function `__static_initialization_and_destruction_0(int, int)':
ProcessScheduler.cpp:(.text+0xc52): undefined reference to `boost::system::generic_category()'
ProcessScheduler.cpp:(.text+0xc5e): undefined reference to `boost::system::generic_category()'
ProcessScheduler.cpp:(.text+0xc6a): undefined reference to `boost::system::system_category()'
collect2: error: ld returned 1 exit status
I even had libboost-system-dev, libboost-filesystem-dev and libboost-iostreams-dev installed.
After searching for over an hour, I found that the problem was with how new g++ treated the command-line options.

The solution was to change the position of arguments.
$ g++ -std=c++11  ProcessScheduler.cpp  -lboost_iostreams -lboost_system -lboost_filesystem
So, adding linker parameters after source file worked.
The page at Link Options - GCC states that:
-l library [...] It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded. [...]