Kernael
Kernael

Reputation: 3280

CMake specify sources before linking

I have the following CMakeLists :

cmake_minimum_required(VERSION 3.3)
project(untitled)

set(SOURCE_FILES main.cpp)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/home/kernael/.openmpi/include -pthread -Wl,-rpath -Wl,/home/kernael/.openmpi/lib -Wl,--enable-new-dtags -L/home/kernael/.openmpi/lib -lmpi_cxx -lmpi")

add_executable(untitled ${SOURCE_FILES})

But the build seems to fail because CMake automatically specifies the sources (main.cpp) after the "-l" options, which seems to be the problem because with command line, the following command works :

g++ -I/home/kernael/.openmpi/include -pthread -L/home/kernael/.openmpi/lib main.cpp -lmpi_cxx -lmpi

But this one doesn't and produces the same errors as the CMake build :

g++ -I/home/kernael/.openmpi/include -pthread -L/home/kernael/.openmpi/lib -lmpi_cxx -lmpi main.cpp

How can I tell CMake to specify the source files before the links happen ?

Upvotes: 2

Views: 282

Answers (2)

Hamdor
Hamdor

Reputation: 381

You cannot use CMAKE_CXX_FLAGS for includes in CMake, it is only for compiler options.

You have to find MPI with find_package. CMake then finds the include path, and the library.

find_package(MPI)
if (MPI_C_FOUND)
  include_directories(${MPI_INCLUDE_PATH})
  add_executable(untitled ${SOURCE_FILES})
  target_link_libraries(untitled ${MPI_LIBRARIES})
  set_target_properties(untitled PROPERTIES
                        COMPILE_FLAGS "${MPI_COMPILE_FLAGS}")
else()
  # MPI not found ...
endif()

Upvotes: 1

Mike Steinert
Mike Steinert

Reputation: 814

You'll want to investigate the following CMake commands:

https://cmake.org/cmake/help/v3.3/command/target_include_directories.html https://cmake.org/cmake/help/v3.3/command/target_link_libraries.html

Something like this should get the job done:

cmake_minimum_required(VERSION 3.3)
add_executable(untitled main.cxx)
target_include_directories(untitled PUBLIC /home/kernael/.openmpi/include)
target_link_libraries(untitled -pthread -L/home/kernael/.openmpi/lib -lmpi_cxx -lmpi)

Upvotes: 1

Related Questions