c++ - 将项目源代码与 CMake 下的 boost 测试链接起来

标签 c++ boost cmake

我正在尝试找到将我的项目源代码与我的 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) 

源/CMakeLists.txt

add_executable(example main.cpp foo.cpp)  

源/foo.h

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

源/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)

测试/测试.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#,这要简单得多。

最佳答案

你可以看看我是怎么做到的: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)

希望对您有所帮助!

关于c++ - 将项目源代码与 CMake 下的 boost 测试链接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25107401/

相关文章:

c++ - 使用 boost 将 C++ 对象传递给 python

c++ - 如何处理不断发展的 C++ std::namespace?例如:std::tr1::shared_ptr 对比 std::shared_ptr 对比 boost::shared_ptr 对比 boost::tr1::shared_ptr

boost - cmake v3.15.3找不到boost v1.71.0

c++ - Centos 7 带有自定义构建的 GLFW binary/usr/bin/ld :/usr/local/lib/libglfw3. a(init.c.o): `.text' 部分中无法识别的重定位 (0x2a)

cmake - CMake的一个可执行文件有多个源目录

java - 链接库时找不到符号

c++ - Qt:编辑条目时 QtAbstractItemView (QTableView) 的背景

G++ 4.5 中 std::complex 的 C++11 复制赋值 - 与 'operator+' 不匹配

c++ - 将方法静态性传播到派生类

c++ - 为什么 CMake 在 Ubuntu 18.04 上找不到我的 Boost 库?