【问题标题】:Linking project source code with boost tests under CMake在 CMake 下将项目源代码与 boost 测试链接
【发布时间】:2014-09-26 06:15:53
【问题描述】:

我正在尝试找到将我的项目源代码与我的 boost 单元测试链接的最佳方法。我现在有一个使用 CMake 的相当基本的项目设置,但是我遇到的所有 boost UTF 示例都显示了非常基本的测试,这些测试不会触及与测试一起的项目中的源代码。

作为一个最小的例子,我有以下内容:

CMakeLists.txt

cmake_minimum_required(version 2.8) 
project(test-project) 
find_package(Boost 1.55 REQUIRED COMPONENTS unit_test_framework )
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})

add_subdirectory(src) 
enable_testing()
add_subdirectory(test) 

src/CMakeLists.txt

add_executable(example main.cpp foo.cpp)  

src/foo.h

#include <string>
std::string hello(std::string name);

src/foo.cpp

#include "foo.h"
std::string hello(std::string name) { return "Hello " + name; }

src/main.cpp - 以简单的方式使用 foo

测试/CMakeLists.txt

include_directories (../src) 
set(TEST_REQUIRED_SOURCES ../src/foo.cpp)

add_executable (test test.cpp ${TEST_REQUIRED_SOURCES}) 
target_link_libraries(test ${Boost_UNIT_TEST_FRAMEWORK_LIBRARY})

add_test(SimpleTest test)

test/test.cpp

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE SimpleTest
#include <boost/test/unit_test.hpp>

#include "foo.h"

BOOST_AUTO_TEST_CASE(ShouldPass) {
    BOOST_CHECK_EQUAL(hello("fred"), "Hello fred")
}

虽然这可行,但我想避免以下情况:

  1. 使用编译所需的所有文件的列表定义 TEST_REQUIRED_SOURCES。
  2. 避免重复编译代码。

对于此类项目,我的结构看起来是否正确?将 src 下的代码编译到库中是否有意义?我的大部分测试经验来自 C#,这要简单得多。

【问题讨论】:

    标签: c++ boost cmake


    【解决方案1】:

    你可以看看我是怎么做到的:https://github.com/NewbiZ/mengine/blob/master/CMakeLists.txt

    基本上,我用我的库构建一个目标文件,并在主可执行文件和测试中重用它。这样你只构建一次。

    CMake 的有趣之处在于:

    # Just build the object files, so that we could reuse them
    # apart from the main executable (e.g. in test)
    ADD_LIBRARY(mengine_objects OBJECT ${MENGINE_SOURCES})
    

    然后构建主可执行文件:

    ADD_EXECUTABLE(mengine $<TARGET_OBJECTS:mengine_objects>
                           src/main.cpp)
    

    还有测试:

    ADD_EXECUTABLE(test_tga $<TARGET_OBJECTS:mengine_objects>
                            test_tga.cpp)
    

    希望有帮助!

    【讨论】:

    • 这看起来很完美,感谢您让我注意到 OBJECT 库类型。我在这里找到了更多关于它的信息cmake.org/Wiki/CMake/Tutorials/Object_Library
    • 太棒了!最后,我明白了为什么我在做的事情不起作用。天哪,这是 3 岁的东西,可以说它救了我的命。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多