如何使用 cmd 行参数不编译 CMakeList 的部分.txt

How to not compile parts of CMakeLists.txt using cmd line parameters?

本文关键字:CMakeList txt 编译 何使用 cmd 参数      更新时间:2023-10-16

我正在使用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

但是,我也希望能够省略 CMakeList 中的文件.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

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

正如@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()

在现代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()