我正在尝试使用cmake链接我的项目。

我需要找到一个软件包mypack,它将给我mypack_definitionsmypack_flagsmypack_include_dirsmypack_libraries。这里mypack_flags包含用于链接mypack的相关标志。我将mypack_flags添加到CMAKE_CXX_FLAGS

请参阅下面的CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)
project(QMCLIB C CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fopenmp")

find_package(mypack REQUIRED)

add_executable(QMC codeA.cpp codeB.cpp )
add_definitions(${mypack_definitions})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${mypack_flags}")
target_link_libraries(QMC ${mypack_libraries})
target_include_directories(QMC PUBLIC ${mypack_include_dirs})

但是取决于系统,mypack_flags可能包含或不包含-fopenmp,当包含-fopenmp时,我的CMAKE_CXX_FLAGS将具有两个-fopenmp。我无法删除-fopenmp
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fopenmp")

如果删除它,则当mypack_flags不包含-fopenmp时,则在CMAKE_CXX_FLAGS中将没有-fopenmp

有没有一种方法可以强制cmake仅使用一个-fopenmp?还是有两个-fopenmp可以吗?谢谢你的建议。

================================================== ====================

感谢RobertPrévost,这是删除重复的子字符串的常规功能:
function(removeDuplicateSubstring stringIn stringOut)
    separate_arguments(stringIn)
    list(REMOVE_DUPLICATES stringIn)
    string(REPLACE ";" " " stringIn "${stringIn}")
    set(${stringOut} "${stringIn}" PARENT_SCOPE)
endfunction()

我们可以通过以下方式调用此函数:
 removeDuplicateSubstring(${CMAKE_CXX_FLAGS} CMAKE_CXX_FLAGS)

最佳答案

除了list(REMOVE_DUPLICATES <list>)解决方案,我建议避免使用CMAKE_CXX_FLAGSadd_*命令,而建议使用target_*命令:

  • target_compile_definitions ;
  • target_compile_options ;
  • target_compile_features

  • 您的cmake文件可能会变成这样:
    cmake_minimum_required(VERSION 2.8)
    project(QMCLIB C CXX)
    
    function(removeDuplicateSubstring stringIn stringOut)
        separate_arguments(stringIn)
        list(REMOVE_DUPLICATES stringIn)
        string(REPLACE ";" " " stringIn "${stringIn}")
        set(${stringOut} "${stringIn}" PARENT_SCOPE)
    endfunction()
    
    find_package(mypack REQUIRED)
    
    set(mycompile_options -fopenmp ${mypack_flags})
    
    removeDuplicateSubstring(${mycompile_options} mycompile_options)
    
    add_executable(QMC codeA.cpp codeB.cpp )
    target_compile_definitions(QMC PUBLIC ${mypack_definitions})
    target_compile_options(QMC PUBLIC ${mycompile_options})
    target_compile_features(QMC PUBLIC cxx_constexpr)
    target_include_directories(QMC PUBLIC ${mypack_include_dirs})
    target_link_libraries(QMC ${mypack_libraries})
    

    10-04 10:21