cmake 3.6.1 on RHEL7 with devtoolset-6 installed (GCC 6.2.1) fails to use -pthread when ASAN is enabled
With RHEL7's native GCC 4.8, the Threads::Threads
imported target works as expected:
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
get_property(X1 TARGET Threads::Threads PROPERTY INTERFACE_COMPILE_OPTIONS)
get_property(X2 TARGET Threads::Threads PROPERTY INTERFACE_LINK_LIBRARIES)
message(STATUS "Threading compile: '${X1}'; threading link: '${X2}'")
...
Looking for C++ include pthread.h
Looking for C++ include pthread.h - found
Looking for pthread_create
Looking for pthread_create - not found
Check if compiler accepts -pthread
Check if compiler accepts -pthread - yes
Found Threads: TRUE
Threading compile: '-pthread'; threading link: '-pthread'
Stuff is different with GCC 6.2.1 with CXXFLAGS=-fsanitize=address
. Here's the relevant output from FindThreads, notice that pthread_create
is suddenly found:
Looking for C++ include pthread.h
Looking for C++ include pthread.h - found
Looking for pthread_create
Looking for pthread_create - found
Found Threads: TRUE
Threading compile: ''; threading link: ''
And just to confirm that this depends on the address sanitizer (ASAN) being active, here's a small example from another machine with GCC 6.3.0:
$ g++-6.3.0 --std=c++14 -Wall foo.cxx ; echo $?
/tmp/cc2eEDjI.o: In function `main':
foo.cxx:(.text+0x46): undefined reference to `pthread_create'
foo.cxx:(.text+0x65): undefined reference to `pthread_create'
foo.cxx:(.text+0x76): undefined reference to `pthread_join'
foo.cxx:(.text+0x87): undefined reference to `pthread_join'
collect2: error: ld returned 1 exit status
1
$ g++-6.3.0 -fsanitize=address --std=c++14 -Wall foo.cxx ; echo $?
0
Looking at my copy of FindThreads.cmake
, my understanding is that it won't even look at my preference to use the -pthread
compiler&linker option if it "guesses" that it is not "required" because a compilation which happens to invoke pthread_create
succeeds. This is wrong; I would expect to try compilation with -pthread
first when my options indicate so, and only resort to other approaches afterwards.