我已将 googletest 用于我的 Android NDK 项目,其中包含 .c 文件。我使用 .cpp 类型的测试类来做同样的事情。我想改用 .c 文件。当我尝试使用它时出现以下错误:
Running main() from gtest_main.cc
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (1 ms total)
[ PASSED ] 0 tests.
我该如何解决这个问题?
最佳答案
您不能使用 .c
文件代替 .cpp
文件在 googletest 中编写测试类。
.c
文件应包含 C 语言源代码,C/C++ 编译器将假定 .c
文件
将被编译为 C。
.cpp
文件应包含 C++ 语言源代码,C/C++ 编译器将假定 .cpp
文件
将被编译为 C++。
C 和 C++ 是相关但不同的编程语言。 C 比 C++ 更古老也更简单。 C语言中没有类。包含类的 C++ 源代码无法编译为 C。
Googletest 是一个用 C++ 而不是 C 编写的单元测试框架,它要求您编写
你的 C++ 测试代码,使用框架类。您的测试必须在 .cpp
(和 .h
)文件中编码,以便
编译器会将它们编译为 C++。
但是,您可以使用 googletest 对 C 代码进行单元测试。 C 代码将在 .c
和 .h
文件中,但是您
必须像往常一样在 .cpp
和 .h
文件中编写您的单元测试。 C/C++ 编译器知道
.c
文件将被编译为 C,而 .cpp
文件将被编译为 C++。
当您想要#include "some_header.h"
时,您必须处理一个小问题
在您的 C++ 单元测试代码中,some_header.h
是 C 语言头文件之一:
C++ 编译器将处理 some_header.h
,并且它可以正确地处理它只要
因为它知道 some_header.h
是一个C语言头文件。通知 C++ 编译器 some_header.h
是一个C头文件,你这样写:
extern "C" {
#include "some_header.h"
}
如果你不在 C 语言 header 的 #include
周围放置 extern "C"{ ... }
那么你将得到 undefined-symbol
链接时出错。
我建议您尝试一个包含以下三个文件的项目:
return_one.h
// return_one.h
#ifndef RETURN_ONE_H
#define RETURN_ONE_H
// A C library :)
// A C function that always return 1.
extern int return_one(void);
#endif
return_one.c
// return_one.c
#include "return_one.h"
int return_one(void)
{
return 1;
}
test_return_one.cpp
// test_return_one.cpp
#include "gtest/gtest.h"
extern "C" {
#include "return_one.h"
}
TEST(t_return_one, returns_1)
{
EXPECT_EQ(1,return_one());
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
获取此项目以使用 googletest 进行编译、链接和运行。
您可能会找到 this question 的答案有帮助。
关于c++ - 如何使用 .c 文件而不是 .cpp 文件在 google test 中编写测试类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23646595/