I have used googletest for my Android NDK project contain .c files. I have used a test class of the type .cpp to do the same. I want to use .c file instead. I get the following error when I try to use it :
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.
How can i solve this?
You cannot use a .c
file to write a test class in googletest instead of a .cpp
file.
A .c
file should contain C language source code and a C/C++ compiler will assume that a .c
file
is to be compiled as C.
A .cpp
file should contain C++ language source code and a C/C++ compiler will assume that a .cpp
file
is to be compiled as C++.
C and C++ are related but different programming languages. C is much older and simpler than C++.
There are no classes in the C language. C++ source code containing classes cannot be compiled as C.
Googletest is a unit-testing framework that is written in C++, not C, and it requires you to write
your test code in C++, using the framework classes. Your tests must coded in .cpp
(and .h
) files so that
the compiler will compile them as C++.
However, you can use googletest to unit-test C code. The C code will be in .c
and .h
files, but you
have to code your unit-tests, as usual, in .cpp
and .h
files. The C/C++ compiler knows that
the .c
files are to be compiled as C and the .cpp
files are to be compiled as C++.
There is a small complication that you must deal with when you want to #include "some_header.h"
in your C++ unit-test code, and some_header.h
is one of the C-language header files:
The C++ compiler is going to process some_header.h
, and it can process it correctly as long
as it knows that some_header.h
is a C-language header file. To inform the C++ compiler that some_header.h
is a C header, you write this:
extern "C" {
#include "some_header.h"
}
If you don't put extern "C" { ... }
around the #include
for a C-language header then you will get undefined-symbol
errors at linktime.
I suggest that you experiment with a project containing the following three files:
return_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
return_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();
}
Get this project to compile, link and run with googletest.
You may find the answers to this question helpful.