用CMake链接几个程序

时间:2016-02-22 12:55:50

标签: c linker cmake

我有三个程序用串行代码计算数量S,并使用MPI和OpenMP并行计算。所有程序都需要相同的头文件utils.h。不知何故,在运行cmake ..之后,我需要运行make两次才能正确编译程序,因为第一次运行会导致链接错误(标准库似乎没有链接)。任何想法为什么会这样?

cmake_minimum_required(VERSION 2.6)
project(compute_S)

find_package(MPI)
enable_language(C)

include_directories(${MPI_INCLUDE_PATH})

set(CMAKE_C_FLAGS "-std=c99")
add_executable(compute_S compute_S.c utils.h)

set(CMAKE_C_FLAGS "-std=c99")
add_executable(compute_S_MPI compute_S_MPI.c utils.h)

set(CMAKE_C_FLAGS "-std=c99 -fopenmp")
add_executable(compute_S_OpenMP compute_S_OpenMP.c utils.h)

target_link_libraries(compute_S ${catkin_LIBRARIES})
target_link_libraries(compute_S_MPI ${MPI_C_LIBRARIES})
target_link_libraries(compute_S_OpenMP ${catkin_LIBRARIES})

您可以通过运行以下

来重现错误
mkdir test 
cd test 
git clone https://github.com/Zetison/exerciseSet4 
cd exerciseSet4 
cmake . 
make

1 个答案:

答案 0 :(得分:2)

我尝试了https://cmake.org/pipermail/cmake/2011-June/045037.html的示例,其中显示了如何链接MPI。模块FindMPI.cmake创建以下变量:

  • MPI_INCLUDE_PATH:包含搜索路径
  • MPI_LIBRARIES:mi库的名称。
  • MPI_COMPILE_FLAGSMPI_LINK_FLAGS:要编译和链接的标志。

同样,FindOpenMP.cmake模块会创建与OpenMP_C_FLAGS对应的变量OpenMP_Fortran_FLAGSOpenMP_CXX_FLAGSMPI_LINK_FLAGS。实际上,它可以恢复到-fopenmp

您可以通过键入CMakeLists.txt然后cmake .来尝试以下make吗?

cmake_minimum_required(VERSION 2.6)
project(compute_S)

find_package(MPI REQUIRED)
find_package(OpenMP REQUIRED)
enable_language(C)

include_directories(${MPI_INCLUDE_PATH})

set(CMAKE_C_FLAGS "-std=c99")
add_executable(compute_S compute_S.c utils.h)

set(CMAKE_C_FLAGS "-std=c99")
add_executable(compute_S_MPI compute_S_MPI.c utils.h)
# https://cmake.org/pipermail/cmake/2011-June/045037.html
target_link_libraries(compute_S_MPI ${MPI_LIBRARIES})

if(MPI_COMPILE_FLAGS)
  set_target_properties(compute_S_MPI PROPERTIES
    COMPILE_FLAGS "${MPI_COMPILE_FLAGS}")
endif()

if(MPI_LINK_FLAGS)
  set_target_properties(compute_S_MPI PROPERTIES
    LINK_FLAGS "${MPI_LINK_FLAGS}")
endif()

set(CMAKE_C_FLAGS "-std=c99")
add_executable(compute_S_OpenMP compute_S_OpenMP.c utils.h)

# https://cmake.org/cmake/help/v3.0/module/FindOpenMP.html
#message(${OpenMP_C_FLAGS})
if(OpenMP_C_FLAGS)
  set_target_properties(compute_S_OpenMP PROPERTIES
    LINK_FLAGS "${OpenMP_C_FLAGS}")
endif()

target_link_libraries(compute_S ${catkin_LIBRARIES})
target_link_libraries(compute_S_MPI ${MPI_C_LIBRARIES})
target_link_libraries(compute_S_OpenMP ${catkin_LIBRARIES})