galinette galinette - 7 days ago 7
Linux Question

Linking with cmake, icc and pthreads (linux)

I am trying to compile a simple test project with the

Intel C++ Compiler
,
CMake
, and
std::threads
support.

If I do :

icpc -std=c++11 -lpthread source/main.cpp


Then the build and the program work fine.

But with
CMake
I get an error:

CMake Error at CMakeLists.txt:21 (TARGET_LINK_LIBRARIES):
Cannot specify link libraries for target "test" which is not built by
this project.


CMakeLists.txt
is:

project(test)
set (CMAKE_CXX_FLAGS "-std=c++11")
set(SOURCE_LIST "source/main.cpp")
TARGET_LINK_LIBRARIES(${PROJECT_NAME} pthread)
add_executable (${PROJECT_NAME} ${SOURCE_LIST})


I am building in an environment set by the script supplied by
icc
(
compilervars.sh
) and
CMake
is called with the
-DCMAKE_C_COMPILER=icc -DCMAKE_CXX_COMPILER=icpc
options. It works if I'm not using threads.

What is wrong with my use of
CMake
?

Thanks!

Answer

Looking back the documentation for target_link_libraries, a target must be declared before being used:

The named <target> must have been created in the current directory by a command such as add_executable() or add_library().

BTW as stated in this answer, you should not set CMAKE_CXX_FLAGS explicitly, and prefer setting CMAKE_CXX_STANDARD and related variables:

project(test)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

set(SOURCE_LIST "source/main.cpp")

add_executable(${PROJECT_NAME} ${SOURCE_LIST})

target_link_libraries(${PROJECT_NAME} pthread)
Comments