4

I'm compiling a C++ program and have been getting the following error message:

undefined reference to 'pthread_mutexattr_init' undefined reference to 'dlopen' undefined reference to 'dlerror' undefined reference to 'dlsym' undefined reference to 'dlclose' 

To resolve the error for pthread I added the following linker flag to my CMakeLists.txt.

if (UNIX) set(CMAKE_CXX_FLAGS "-pthread") endif (UNIX) 

This resolved the pthread error. To resolve the libdl error I went ahead and modified it to the following.

if (UNIX) set(CMAKE_CXX_FLAGS "-pthread -dl") endif (UNIX) 

This gave me a warning

unrecognized gcc debugging option: l 

I modified it to the following

if (UNIX) set(CMAKE_CXX_FLAGS "-pthread") set(CMAKE_CXX_FLAGS "-dl") endif (UNIX) 

And got back all the error messages together with

unrecognized gcc debugging option: l. 

Do I miss how to set linker flags in CMake? What exactly am I doing wrong? I'm on Ubuntu 17.04 x64.

1
  • tried target_link_libraries(yourtarget pthread dl)? Commented Jul 21, 2017 at 15:05

2 Answers 2

5

This is the modern canonical CMake method for pthread and dl:

cmake_minimum_required(VERSION 3.9) project(my_pthread_dl_project) set(THREADS_PREFER_PTHREAD_FLAG ON) find_package(Threads) add_executable(myexe source.c) target_link_libraries(myexe Threads::Threads ${CMAKE_DL_LIBS}) 
Sign up to request clarification or add additional context in comments.

3 Comments

Why should this be preferred than @Akira's approach?
It is not as platform specific and has no bad habits.
Tested on Windows 10 and Ubuntu 17.04, it works. Thanks.
3

Try the following way instead of overwriting CMAKE_CXX_FLAGS:

project(FooProject) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include_dir) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/source_dir FOO_SOURCES) add_executable(foo ${FOO_SOURCES}) target_link_libraries(foo pthread dl) 

The set command overwrites the variable. If you use it like:

set(CMAKE_CXX_FLAGS "-pthread") 

the old concent of CMAKE_CXX_FLAGS will be replaced. To append something to a variable, you should use the set command as follows:

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

4 Comments

Why are you using aux_source_directory here?
@SirDarius, just for the sake of completeness. I use aux_source_directory for all projects to collect source files.
I'm mentioning this because the documentation says explicitely that it is not good practice and this command should only be used for explicit template instanciation. Explicitely listing source files is the preferred way in CMake.
@SirDarius, thanks for the clarification. This is my bad habit then which may originating from Qt Creator's CMake project template.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.