c++ - 如何在 C 代码上从终端运行 Google 测试?

标签 c++ c unit-testing testing googletest

我正在使用 googleTest 测试 C 代码。 我的 test.cpp 文件看起来像这样

#include <gtest/gtest.h>
 

extern "C" {
#include "list.h"
#include "list.c"
}

TEST(ListTest, singleInsertion) {
// some tests
}

int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

但是尝试使用以下命令从终端运行测试 g++ test.cpp -lgtest 给出错误和警告,就好像正在测试的代码是 C++ 而不是 C 一样。

错误和警告示例: 错误:malloc 的转换无效 警告:ISO C++ 禁止将字符串常量转换为“char*”

如何声明我的测试文件是 C 而不是 C++?

最佳答案

However trying to run the test from the terminal using g++ test.cpp -lgtest gives Errors and warning as if the code being tested is C++ not C.

那是因为您使用 g++ 编译器将其编译为 C++。使用gcc编译为C。

不幸的是,这段代码不会编译为 C - 它会在 google::InitGoogleTest() 调用上卡住,因为 C 无法识别 ::范围界定运算符。我对这个测试框架并不熟悉,但乍一看它似乎是用于 C++,而不是 C。

解决此问题的方法是删除 #include "list.c" 指令

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

并将其单独编译为C:

gcc -c list.c

然后编译你的测试器:

g++ -c test.cpp

然后将目标文件与库链接:

g++ -o test test.o list.o -lgtest

关于c++ - 如何在 C 代码上从终端运行 Google 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64544392/

相关文章:

python - 多个枚举值的开关/大小写

c++ - g++ 和 clang++ 推导可变参数模板 `auto` 值的不同行为

c - 将变量声明放在 C 中的单独函数中

javascript - 测试复杂的异步 Redux 操作

python - 在 Python 中模拟模拟对象的方法?

c++ - 为什么 SFINAE 不起作用?

c++ - C++ 中的最小浮点正值

c++ - 传递元组嵌入Python

c++ - pthread线程状态

c# - 使用 Selenium 2 的 IWebDriver 与页面上的元素进行交互