【发布时间】:2017-05-08 14:34:39
【问题描述】:
我有一个简单的 C++ 类,其中包含我想从 Google 测试 Fixture 调用的方法。
当我在 cpp 文件中声明该方法时,编译器会抛出 undefined symbol 错误:
Class.h
class Class {
public:
double test() {
return 1.;
}
}
Class.cpp
double Class::test() {
return 1.;
}
GoogleTest.cpp
#include "Class.h"
class GoogleTest : public ::testing:Test {
protected:
Class c;
}
TEST_F(GoogleTest, TestIt) {
EXPECT_EQ(c.test(), 1.);
}
同时在头文件中定义方法,我可以像魅力一样编译:
Class.h
class Class {
public:
double test() {
return 1.;
}
}
GoogleTest.cpp
#include "Class.h"
class GoogleTest : public ::testing:Test {
protected:
Class c;
}
TEST_F(GoogleTest, TestIt) {
EXPECT_EQ(c.test(), 1.);
}
这种行为的原因是什么?我不想在 header 中定义我所有的方法。
整个错误:
Undefined symbols for architecture x86_64:
"Numeric::test()", referenced from:
ConstantsTest_Gamma_Test::TestBody() in Test.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [runUnitTests] Error 1
【问题讨论】:
-
首先,我认为Class.h中第一种情况下
test()的定义实际上应该是一个声明。其次,错误应该是编译测试时没有编译Class.cpp。检查你的制作文件。我没有使用过 Google Test,所以我无法给出问题的解决方案。 -
为什么要定义同一个函数两次?
-
发布确切的错误信息
-
在创建测试二进制文件时是否忘记链接
Class.o(或Class.cpp编译到的任何目标文件或库)?
标签: c++ testing compiler-errors