Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ linker flags in CMake

Tags:

c++

cmake

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.

like image 482
Amani Avatar asked Mar 08 '23 13:03

Amani


2 Answers

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})
like image 141
utopia Avatar answered Mar 17 '23 08:03

utopia


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")
like image 31
Akira Avatar answered Mar 17 '23 07:03

Akira