Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

link pthread statically with cmake

Tags:

cmake

msys2

How can I get CMake to link pthread statically on Windows? I use MSYS2 MinGW 32 bit and cmake v3.7.

What I would like to achieve is a compiler invocation like

g++ -static-libgcc -static-libstdc++ -std=c++11 -o test test.cpp -Wl,-Bstatic -lpthread

Setting

target_link_libraries(test PUBLIC "-Wl,-Bstatic -lpthread")

results in -Wl,-Bdynamic -Wl,-Bstatic -lpthread being called. If I change CMAKE_EXE_LINKER_FLAGS, pthreads is included before my object files and thus symbols are not resolved.

like image 373
zeeMonkeez Avatar asked Sep 02 '25 09:09

zeeMonkeez


2 Answers

find the Threads module:

find_package(Threads REQUIRED)
add_executable(myApp main.cpp)
target_link_libraries(myApp Threads::Threads)

Note from the documentation:

For systems with multiple thread libraries, caller can set CMAKE_THREAD_PREFER_PTHREAD

like image 187
Nicolas Holthaus Avatar answered Sep 04 '25 12:09

Nicolas Holthaus


As the FindThreads.cmake mention in its source code:

# For systems with multiple thread libraries, caller can set
#
# ::
#
#   CMAKE_THREAD_PREFER_PTHREAD
#
# If the use of the -pthread compiler and linker flag is preferred then the
# caller can set
#
# ::
#
#   THREADS_PREFER_PTHREAD_FLAG
#
# Please note that the compiler flag can only be used with the imported
# target. Use of both the imported target as well as this switch is highly
# recommended for new code.

So in addition to what already said, you might need to set the additional flag THREADS_PREFER_PTHREAD_FLAG. In some systems (OSX, etc.) this flag is needed at compilation time because it defines some macros that would be missing if you would only link -lpthread.

set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
add_library(test test.cpp)
set_property(TARGET test PROPERTY CXX_STANDARD 11)
set_target_properties(test PROPERTIES LINK_SEARCH_START_STATIC 1)
set_target_properties(test PROPERTIES LINK_SEARCH_END_STATIC 1)
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++")
find_package(Threads REQUIRED)  

target_link_libraries(test Threads::Threads)  

Does it help?

like image 32
fedepad Avatar answered Sep 04 '25 12:09

fedepad