How can I add a flag at the end of the linking command line using CMake?

14,743

"How can I go about either getting CMake to add -lpthread at the end of this line, or perhaps even modifying the generated Makefiles somehow in some hacky way to get this to work?"

1st be sure that your

set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lpthread")

is the last seen in line by CMake.
Any further library/module references (like e.g. FIND_BOOST) may screw up the order of the flags you want to provide directly.

I would use

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")

and

set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread")

I think with this option, the linker automatically detects the appropriate pthread library, linked appearing at the end of the linker objects chain.

Share:
14,743
Claudiu
Author by

Claudiu

Graduated from Brown University. E-mail: [email protected]

Updated on June 14, 2022

Comments

  • Claudiu
    Claudiu almost 2 years

    I've got an issue where CMake can't detect pthread. As a work-around I tried:

    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lpthread")
    

    However, this inserts -lpthread in the wrong place:

    /usr/bin/c++    -std=c++11 -D_GNU_SOURCE  -Wall [manyflags ...]    -lpthread \
        CMakeFiles/connectivity_tool.dir/connectivity_tool/conn_tool.cpp.o       \
        -o connectivity_tool -rdynamic -lboost_system [many libraries...]
    

    This results in:

    /usr/bin/ld: /tmp/ccNvRifh.ltrans3.ltrans.o: undefined reference to symbol 'pthread_mutexattr_settype@@GLIBC_2.2.5'
    /lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
    

    Of course, the -lpthread should be at the end of the 3rd line, not the end of the 1st.

    How can I go about either getting CMake to add -lpthread at the end of this line, or perhaps even modifying the generated Makefiles somehow in some hacky way to get this to work?

    (If the answer involves actually detecting pthread properly then answer the linked question.)

  • Andry
    Andry about 6 years
    That -lpthread option didn't help in the cmake 3.11.0 in Linux x64 with gcc 5.4. You have to use -pthread instead both for the compiler and the linker to resolve it for the cmake.
  • Carlo Wood
    Carlo Wood about 4 years
    Note that correct way to add -pthread with cmake would be to use set(THREADS_PREFER_PTHREAD_FLAG true), find_package(Threads REQUIRED) and target_link_libraries(myprogram Threads::Threads)
  • jpaugh
    jpaugh over 2 years
    @Andry IIRC, the -pthread vs -lpthread thing is an issue on Linux even if you're calling the compiler by hand.