我正在尝试找到将我的项目源代码与我的 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")
}
虽然这可行,但我想避免以下情况:
- 使用我需要编译的所有文件的列表定义 TEST_REQUIRED_SOURCES。
- 避免重复编译代码。
我的结构看起来适合这类项目吗?将我在 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/