首页 文章

CMake如何配置这个C项目?

提问于
浏览
1

我想要一个带有两个配置BUILD和TEST的cmake项目 .

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

我目前在磁盘上有:

project/
  test/
    test_foo.cpp
    main.cpp

  bar.hpp
  widget.hpp
  bar.cpp
  widget.cpp
  ...

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

1 回答

  • 4

    在我看来,你想要使用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 ( 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()
    

相关问题