使用 Boost 单元测试进行 G++ 项目编译

g++ project compilation with boost unit test

本文关键字:G++ 项目 编译 Boost 单元测试 使用      更新时间:2023-10-16

我正在尝试在Linux上编译单元测试(boost),但编译器出现错误。有人可以检查我的命令吗?

g++ -o UTest ../UTest/UT1.cpp ../UTest/UT2.cpp -lboost_system -lboost_thread -lboost_unit_test_framework 

错误

/usr/lib/gcc/i686-linux-gnu/4.6/../../../i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'

我从 g++ comand 中删除了main(),因为在使用 boost unit test 时不应该使用它。

怎么了?

PS没有单元测试的项目(带main())编译得很好。Windows上的单元测试也可以正常工作。

更新

main()的问题已解决。但是一个新的诞生了。

UT1.cppUT2.cpp都包含UTCommon.h,现在我有很多错误,如下所示

错误

tmp2.cpp:(.text+0xd44a): multiple definition of `boost::unit_test::unit_test_log_t::operator<<(boost::unit_test::lazy_ostream const&)'
/tmp/cc0jw8uR.o:tmp.cpp:(.text+0xd44a): first defined here
/tmp/cctLn9QJ.o: In function `boost::test_tools::tt_detail::equal_impl(char const*, char const*)'

UTCommon.h

#ifndef UT_COMMON_H
#define UT_COMMON_H
#ifndef BOOST_TEST_MODULE
#define BOOST_TEST_MODULE UnitTest
#endif
#if defined (__GNUC__) && defined(__unix__)
    #include <boost/test/included/unit_test.hpp>
#elif defined (WIN32)
    #include <boost/test/unit_test.hpp>
#endif
#endif

最好创建一个单独的.cpp文件,其中包含文件boost/test/included/unit_test.hpp。这将在代码中包括一个预生成的main()函数。然后,您可以使用BOOST_AUTO_TEST_CASE宏进行实际测试(根据需要多次):

#define BOOST_TEST_DYN_LINK        // this is optional
#define BOOST_TEST_MODULE MyTest   // specify the name of your test module
#include <boost/test/included/unit_test.hpp>  // include this to get main()

BOOST_AUTO_TEST_CASE(my_test_1)    // specify a test case
{
  /* Test something... */
  const static auto expected = 12;
  auto actual = my_func();
  BOOST_CHECK(actual == expected);
}

编译此.cpp文件(根据需要为您自己的代码中定义的所有函数添加链接器选项),它将成为执行所有测试并生成报告的可执行文件。