[英]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.