【问题标题】:How To Run Google test from terminal on C code?如何在 C 代码上从终端运行 Google 测试?
【发布时间】:2021-02-09 03:20:07
【问题描述】:

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

错误和警告示例: error: invalid conversion for mallocs warning: ISO C++ forbids converting a string constant to ‘char*'

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

【问题讨论】:

  • 强烈建议:不要这样做:#include "list.c",而是为list.c创建一个头文件,然后更正你的编译和链接语句

标签: c++ c unit-testing testing googletest


【解决方案1】:

但是,尝试使用 g++ test.cpp -lgtest 从终端运行测试会出现错误和警告,就好像正在测试的代码是 C++ 而不是 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2012-09-04
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    相关资源
    最近更新 更多