C ++ Linker Flags in CMake

I compile a program in C ++ and get 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 fix the error for pthread, I added the following linker flag to mine CMakeLists.txt.

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

This resolved the error pthread. To fix the error libdl, I went ahead and changed it to the following.

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

It gave me a warning

unrecognized gcc debugging option: l

I changed it to the next

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

And returned all error messages along with

unrecognized gcc debugging option: l.

Don't know how to set linker flags in CMake? What am I doing wrong? I'm on Ubuntu 17.04 x64.

+4
source share
2 answers

This is the modern canonical CMake method for pthreadand 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})
+3
source

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)

set . , :

set(CMAKE_CXX_FLAGS "-pthread")

CMAKE_CXX_FLAGS . - , set :

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

Source: https://habr.com/ru/post/1681978/


All Articles