我正在使用 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/