CMake 在链接之前指定来源

CMake specify sources before linking

我有以下 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 在链接发生之​​前指定源文件?

您需要研究以下 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)

您不能将 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()