繁体   English   中英

如何使用 .c 文件在 google test 中编写测试类而不是 .cpp 文件?

[英]how to use a .c file to write a test class in google test instead of .cpp file?

我已将 googletest 用于包含 .c 文件的 Android NDK 项目。 我使用了一个 .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++。

当您想在 C++ 单元测试代码中#include "some_header.h"时,您必须处理一个小问题,而some_header.h是 C 语言头文件之一:

C++ 编译器将处理some_header.h只要知道some_header.h是 C 语言头文件,它就可以正确处理它。 要通知 C++ 编译器some_header.h是 C 头文件,您可以这样写:

extern "C" {
#include "some_header.h"
}

如果您没有将extern "C" { ... }放在 C 语言标头的#include周围,​​那么您将在链接时收到未定义符号错误。

我建议您尝试一个包含以下三个文件的项目:

返回_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

返回_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 编译、链接和运行。

您可能会发现此问题的答案很有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM