CMake 在链接之前指定源

CMake specify sources before linking

本文关键字:链接 CMake      更新时间:2023-10-16

我有以下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.htmlhttps://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 中的包含,它仅用于编译器选项。

你必须找到 MPI 与 find_package .然后,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()