CMake如何配置这个C++项目?

Elo*_*off 1 c++ cmake

我想要一个具有两个配置构建和测试的 cmake 项目。

BUILD 将不在 test 子目录中的所有源代码编译到共享库中。TEST 将所有源代码(包括 test 子目录(包括 main.cpp)中的源代码)编译为运行测试的可执行文件。我不希望 TEST 构建共享库。我不希望 BUILD 构建测试可执行文件。

我目前在磁盘上有它:

project/
  test/
    test_foo.cpp
    main.cpp

  bar.hpp
  widget.hpp
  bar.cpp
  widget.cpp
  ...
Run Code Online (Sandbox Code Playgroud)

如果它更容易,我可以移动东西。我在 CMakeLists.txt 文件中放了什么?

use*_*829 5

在我看来,您想使用 cmake 的OPTION命令。默认情况下选择一种配置(或者如果您想强制编译代码的人选择,则两者都不启用)

OPTION( BUILD_SHARED_LIBRARY "Compile sources into shared library" ON )
OPTION( RUN_TESTS "Compile test executable and run it" OFF )
Run Code Online (Sandbox Code Playgroud)

您需要确保选项是互斥的,否则会出错

if ( BUILD_SHARED_LIBRARY AND RUN_TESTS )
  message(FATAL_ERROR "Can't build shared library and run tests at same time")
endif()
Run Code Online (Sandbox Code Playgroud)

然后,您可以将其余命令放在基于这些变量的 if 块中

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()
Run Code Online (Sandbox Code Playgroud)