Linking Boost with cmake and clang - undefined ref

2019-08-14 02:34发布

问题:

In my C++ program, I am including boost's filesystem and regex headers and eventually thread support. I would like cmake and clang to link against them during build time.

I am receiving the following error:

[100%] Building CXX object CMakeFiles/a.out.dir/src/main.cpp.o
Linking CXX executable a.out
/usr/bin/ld: CMakeFiles/a.out.dir/src/main.cpp.o: undefined reference to symbol '_ZN5boost6system15system_categoryEv'
/usr/lib/libboost_system.so.1.56.0: error adding symbols: DSO missing from command line
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I believe I have included the necessary links and flags in my CmakeList file, but I must be missing the order or a flag for linking. I have lost many hairs because of this.

CMakeLists.txt

cmake_minimum_required(VERSION 2.8)

set(CMAKE_C_COMPILER clang)
set(CMAKE_CXX_COMPILER clang++)
set(TARGET_NAME "a.out")

project(${TARGET_NAME} C CXX)
file(GLOB ALL_SRC_FILES "src/*.cpp")

add_definitions("-std=c++11 -Wall -g -pthread")
find_package(Boost 1.56 COMPONENTS filesystem regex REQUIRED)
message(status ": Boost Include: ${Boost_INCLUDE_DIR}")
message(status ": Boost Libraries Dir: ${Boost_LIBRARY_DIRS}")
message(status ": Boost Libraries: ${Boost_LIBRARIES}")

include_directories(${Boost_INCLUDE_DIR})
include_directories(/usr/include/c++/4.9.1)
include_directories(/usr/lib/clang/3.5.0/include)
include_directories(src)
list(APPEND CMAKE_CXX_FLAGS "-pthread")
add_executable(${TARGET_NAME} ${ALL_SRC_FILES})
link_directories(${Boost_LIBRARY_DIRS})
target_link_libraries(${TARGET_NAME} ${Boost_LIBRARIES})

回答1:

boost_system library is missing

/usr/lib/libboost_system.so.1.56.0: error adding symbols

Try:

find_package(Boost 1.56 COMPONENTS system filesystem regex REQUIRED)

Even if you don't include it in your program, filesystem or regex lib might still use it as dependency