CMake: Project structure with unit tests

前端 未结 2 1829
轻奢々
轻奢々 2020-12-02 04:08

I am trying to structure my project to include the production sources (in src subfolder) and tests (in test subfolder). I am using CMake to build t

2条回答
  •  遥遥无期
    2020-12-02 04:16

    I like the example of @Fraser but would use the add_test command in the test/CMakeLists.txt and use enable_testing before add_subdirectory(test).

    This way you can run your tests from the top-level build directory while specifying your tests in the test/CMakeLists.txt.

    The result would look like this (I reused the example of @Fraser):

    CMakeLists.txt

    cmake_minimum_required (VERSION 2.8)
    project (TEST)
    add_subdirectory (src)
    
    enable_testing ()
    add_subdirectory (test)
    

    src/CMakeLists.txt

    add_library (Sqr sqr.cpp sqr.h)
    add_executable (demo main.cpp)
    target_link_libraries (demo Sqr)
    

    test/CMakeLists.txt

    find_package (Boost COMPONENTS system filesystem unit_test_framework REQUIRED)
    include_directories (${TEST_SOURCE_DIR}/src
                         ${Boost_INCLUDE_DIRS}
                         )
    add_definitions (-DBOOST_TEST_DYN_LINK)
    add_executable (Test test.cpp)
    target_link_libraries (Test
                           Sqr
                           ${Boost_FILESYSTEM_LIBRARY}
                           ${Boost_SYSTEM_LIBRARY}
                           ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY}
                           )
    add_test (NAME MyTest COMMAND Test)
    

提交回复
热议问题