CMake在链接之前指定源

时间:2016-02-22 17:18:36

标签: c++ cmake g++

我有以下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})

但是构建似乎失败了,因为CMake在“-l”选项之后自动指定源(main.cpp),这似乎是问题,因为使用命令行,以下命令有效:

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

但是这个没有并产生与CMake构建相同的错误:

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

如何告诉CMake在链接发生之​​前指定源文件?

2 个答案:

答案 0 :(得分:1)

您想要调查以下CMake命令:

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

这样的事情应该完成工作:

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)

答案 1 :(得分:1)

您不能将CMAKE_CXX_FLAGS用于CMake中的包含,它仅适用于编译器选项。

您必须找到find_package的MPI。然后CMake找到包含路径和库。

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()