【问题标题】:How to not compile parts of CMakeLists.txt using cmd line parameters?如何不使用命令行参数编译 CMakeLists.txt 的一部分?
【发布时间】:2019-04-30 15:08:08
【问题描述】:

我正在使用 CMake 3.10.2 并将其放在我的目标 CMakeLists.txt 文件之一中......

target_compile_definitions(mytarget PUBLIC USE_MY=${USE_MY})

然后我可以在命令行上使用参数,例如 -DUSE_MY=0,这样我就可以将这样的内容放入我的 c++ 文件中:

#ifdef USE_MY
   // code left out
#endif

但是,我还希望能够从编译中省略 CMakeLists.txt 中的文件。

set(my_sources
    filea.cpp
    fileb.cpp
    filec.cpp (how would I leave out filec.cpp?)
)

在我的顶级 CMakeLists.txt 中,省去整个库。

add_subdirectory(my_stuff/liba)
add_subdirectory(my_stuff/libb) (how to leave out this lib?)
add_subdirectory(my_stuff/libc

所以我也想省略某些文件和目标的编译。感谢您对此的任何帮助。

【问题讨论】:

  • 您可以附加到 my_sources 以根据您的 CMake 变量添加其他源。
  • if (USE_MY) add_subdirectory(my_stuff/libb) endif() 语法在这里:cmake.org/cmake/help/latest/command/if.html
  • @drescherjm - 这样做,我得到... CMake Error at src/targetA/CMakeLists.txt:95 (add_executable): 找不到源文件:if target_link_libraries(targetA ${my_liba} if ( USE_MY) ${my_libb} endif() ${my_liibc}} )
  • @drescherjm - 所以,我只是在 if、elseif 中使用单独的 target_link_libraries()。如果你做出是一个答案,我会检查它。
  • @Ender 根据您的 cmets 更新了我的回复

标签: c++ cmake


【解决方案1】:

正如@drescherjm 建议的那样,这样的事情可能对你有用:

set(my_sources
    filea.cpp
    fileb.cpp
)
if(USE_MY)
    # Append filec if USE_MY is defined.
    set(my_sources ${my_sources} filec.cpp)
endif()

同样,

add_subdirectory(my_stuff/liba)
if(USE_MY)
    add_subdirectory(my_stuff/libb)
endif()
add_subdirectory(my_stuff/libc

# ... other code here ...

# Link the libraries.
target_link_libraries(targetA ${my_liba} ${my_libc})
if(USE_MY)
    target_link_libraries(targetA ${my_libb})
endif()

【讨论】:

    【解决方案2】:

    在现代 CMake 中,你会做这样的事情:

    add_subdirectory(my_stuff/liba)
    
    if (USE_MY)
        add_subdirectory(my_stuff/libb)
    endif()
    
    add_subdirectory(my_stuff/libc
    

    那么对于来源:

    add_library(libB source1.cpp source2.cpp source3.cpp)
    
    if (USE_MY)
        target_sources(libB source4.cpp source5.cpp)
    endif()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-14
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      相关资源
      最近更新 更多