簡體   English   中英

如何在 C 代碼上從終端運行 Google 測試?

[英]How To Run Google test from terminal on C code?

我正在使用 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從終端運行測試g++ test.cpp -lgtest給出錯誤和警告,就好像被測試的代碼是 C++ 而不是 C。

錯誤和警告示例: error: invalid conversion for mallocswarning: ISO C++ forbids converting a string constant to 'char*'

我如何聲明我的測試文件是 C 而不是 C++?

然而,嘗試使用g++ test.cpp -lgtest從終端運行測試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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM