I have a C library A
with no test and I am trying to add tests for one of its functions funC
:
in funC
is not declared in A/lib.h
and only declared in A/lib.c
:
static int funC();
static int funC(){
// do something
}
and I created a test file in test/A.t.cpp
and want to access funC to test it. funC is only declared in .c file so i decide to use extern C
. in test/A.t.cpp
I have:
extern "C"{
static int funC();
}
TEST(A,test){
funC();
.....
}
I thought with the declaration in the .t.cpp file, it would be able to link against the actual implementation in the .c file so I should be able to call the function and test it, but I got:
Error: The function funC() has not had a body defined
how should I fix it? Then I also tried to add the implementation within the test file and it worked but that's not what I want. I want the .t.cpp file to link against the actual implementation in .c file. Thanks!
CodePudding user response:
Your function funC()
has internal linkage (this is the meaning of static
for functions and file-scope variables in C). It cannot be called by name from other translation units than the one it is defined in, whether C or C .
In your test source, the same name refers to a different function, for which you have not provided a definition.
If you want funC()
to be callable from your separate test file then you should change it to have external linkage by removing its static
qualifier or changing it to extern
. You will need to make the same change to the declaration in the test file.
CodePudding user response:
To unit test static functions, this is one of the rare cases where you would need to include a .c file:
extern "C"{
#include "A/lib.c"
}
TEST(A,test){
funC();
.....
}
Then the static
functions and variables will be visible in the test code.