Search code examples
boostcmakeboost-thread

CMake and Boost


I've searched and found out that a lot of people have the same problem, but no solution exists.

I'm using CMake to generate Makefiles for MinGW and when compiling I'm getting an error:

CMakeFiles\boosttest.dir/objects.a(main.cpp.obj):main.cpp:(.text+0x5e): undefined reference to `_imp___ZN5boost6thread4joinEv'
CMakeFiles\boosttest.dir/objects.a(main.cpp.obj):main.cpp:(.text+0x71): undefined reference to `_imp___ZN5boost6threadD1Ev'
CMakeFiles\boosttest.dir/objects.a(main.cpp.obj):main.cpp:(.text+0x88): undefined reference to `_imp___ZN5boost6threadD1Ev'

This seems to be a linking problem, I get it. My CMake configuration is:

project(boosttest)
cmake_minimum_required(VERSION 2.6)

include_directories(${boosttest_SOURCE_DIR}/include c:/boost_1_48_0/)
link_directories(c:/boost_1_48_0/lib)

file(GLOB_RECURSE cppFiles src/*.cpp)

add_executable(boosttest ${cppFiles})

target_link_libraries(boosttest libboost_thread-mgw46-mt-1_48.a)

First I tried using find_package(Boost COMPONENTS thread) and it was working the same way, so I thought to try to do this manually and I still get the same error.

Any insights on this?

I've compiled it for mingw using bjam and as a static link. Also tried doing:

add_library(imp_libboost_thread STATIC IMPORTED)
set_property(TARGET imp_libboost_thread PROPERTY IMPORTED_LOCATION c:/boost_1_48_0/lib/libboost_thread-mgw46-mt-1_48.a)
target_link_libraries(boosttest imp_libboost_thread)

And I still get the same error messages.


Solution

  • For mingw32 you may add definition BOOST_THREAD_USE_LIB. And linking with boost::thread will work. Also you may need Threads package (but i'm not sure, may be it needs only for *nix platforms).

    Here is part of my CMakeLists. I copied it from project, which uses boost::thread, and compiles under mingw-gcc (and other compilers):

        set(Boost_USE_STATIC_LIBS   ON)
        set(Boost_USE_MULTITHREADED ON)
        set(Boost_ADDITIONAL_VERSIONS "1.44" "1.44.0")
        find_package(Boost COMPONENTS thread date_time program_options filesystem system REQUIRED)
        include_directories(${Boost_INCLUDE_DIRS})
    
        find_package(Threads REQUIRED)
    
        #...
    
        if (WIN32 AND __COMPILER_GNU)
            # mingw-gcc fails to link boost::thread
            add_definitions(-DBOOST_THREAD_USE_LIB)
        endif (WIN32 AND __COMPILER_GNU)
    
        #...
    
        target_link_libraries(my_exe
                ${CMAKE_THREAD_LIBS_INIT}
                #...
            ${Boost_LIBRARIES}
        )