Issue
I'm building a shared library (.so) on Linux with CMake which uses Boost 1.75.0.
In CMakeLists.txt, Boost is added the following way:
find_package(Boost REQUIRED COMPONENTS system chrono filesystem date_time log iostreams program_options)
and added to the target:
target_link_libraries(mytarget PUBLIC ${Boost_LIBRARIES})
CMake finds Boost, so no problem here.
Boost is linked as a static library. When I list the linked object files, I get the correct libraries:
-- LIB_FILES: ...;/path/to/boost/debug/lib/libboost_filesystem.a;...
The library compiles and links without error.
However, when I use a simple function of the library, I get the following error:
undefined symbol: _ZNK5boost10filesystem16filesystem_error4whatEv
This symbol is indeed undefined in the library:
$ nm -g libmytarget.so | grep _ZNK5boost10filesystem16filesystem_error4whatEv
U _ZNK5boost10filesystem16filesystem_error4whatEv
The demangled name is boost::filesystem::filesystem_error::what() const
, which is defined in boost/filesystem/exception.hpp
as
namespace boost
{
namespace filesystem
{
class BOOST_FILESYSTEM_DECL filesystem_error : public std::exception
{
public:
virtual const char * what() const throw();
...
Note that my code does not call this method.
The symbol is defined in libboost_filesystem.a
, which is used by the linker, as a symbol in the text (code) section:
$ nm -g /path/to/boost/debug/lib/libboost_filesystem.a | grep _ZNK5boost10filesystem16filesystem_error4whatEv
00000000000003fa T _ZNK5boost10filesystem16filesystem_error4whatEv
My question:
I don't understand how it is possible that this symbol is undefined in the compiled library, when it is present in the statically linked lib (file libboost_filesystem.a
), which is recognized and used by the linker.
Solution
Enabling INTERPROCEDURAL_OPTIMIZATION
in CMake solved the problem:
set_target_properties(mytarget PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)
Now, the symbol is properly linked:
$ nm -g libmytarget.so | grep filesystem_error4what
00000000001cfe22 T _ZNK5boost10filesystem16filesystem_error4whatEv
But I still don't know what's going on behind the scenes and why this error pops up in the first place.
Answered By - WolfgangP