GoogleTest仅在定义在.h文件中时才有效

GoogleTest only work when definition is in .h file

本文关键字:有效 定义 GoogleTest 文件      更新时间:2023-10-16

我花了一整天的时间试图让GoogleTest在Visual Studio 2013中工作。最后,使其"工作",但仅当函数的定义放置在 .h 文件中时才有效。使用单独的编译,例如 =:

// simplemath.h
#include <cmath>
double cubic(double d);
// simple.cpp
#include "simplemath.h"
double cubic(double d)
{
    return pow(d, 3);
}
// unittest_SimpleMath.cpp
#include "gtest/gtest.h"
#include "simplemath.h"    
TEST(testMath, myCubeTest)
{
    EXPECT_EQ(1000, cubic(10));
}  

产生以下错误:

1>------ Build started: Project: unittest_SimpleMath, Configuration: Release Win32 ------
1>  unittest_SimpleMath.cpp
1>unittest_SimpleMath.obj : error LNK2001: unresolved external symbol "double __cdecl cubic(double)" (?cubic@@YANN@Z)
1>C:UsersalexDocumentsVisual Studio 2013ProjectsSimpleMathReleaseunittest_SimpleMath.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 2 up-to-date, 0 skipped ==========

编辑:忘了提到一件重要的事情。我按照教程 http://www.bogotobogo.com/cplusplus/google_unit_test_gtest.php 弄清楚如何配对Gtest和VS2013。我的解决方案结构与 desc 相同。在教程中 - 3 个项目。

您似乎正在使用不同的项目进行测试。您应该在具有cubic函数的同一项目中使用测试。或者从您的cubic代码制作库并将其链接到测试项目中。您遇到的错误与 gtest 没有任何关系。您只是没有将 cpp 文件编译为可以在测试项目中使用的对象文件。

另外,请确保您在测试项目中链接了gtest_main*.lib(星号,因为它有几个名称,您应该选择您需要的任何名称),因为您没有main(或者您没有显示它)。