我想要一个具有两个配置 BUILD 和 TEST 的 cmake 项目。
BUILD 将所有不在 test 子目录中的源代码编译到一个共享库中。 TEST 将所有源代码(包括测试子目录(包括 main.cpp)中的源代码)编译成运行测试的可执行文件。我不希望 TEST 构建共享库。我不希望 BUILD 构建测试可执行文件。
我目前将其保存在磁盘上:
project/
test/
test_foo.cpp
main.cpp
bar.hpp
widget.hpp
bar.cpp
widget.cpp
...
如果它更容易的话,我可以移动东西。我在 CMakeLists.txt 文件中放了什么?
最佳答案
在我看来,您想使用 cmake 的 OPTION命令。选择一种默认情况下启用的配置(如果你想强制编译代码的人选择,则两者都不启用)
OPTION( BUILD_SHARED_LIBRARY "Compile sources into shared library" ON )
OPTION( RUN_TESTS "Compile test executable and run it" OFF )
你需要确保选项是互斥的,否则会出错
if ( BUILD_SHARED_LIBRARY AND RUN_TESTS )
message(FATAL_ERROR "Can't build shared library and run tests at same time")
endif()
然后您可以将其余命令放在基于这些变量的 if block 中
if ( BUILD_SHARED_LIBRARY )
#add subdirectories except for test, add sources to static library, etc
endif()
if ( RUN_TESTS )
#compile an executable and run it, etc.
endif()
关于c++ - CMake如何配置这个C++项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31765970/