My project contains C files. And in some files I have functions defined as static.
I'm using CppUnit in my unit tests and I want to test these static functions. I know that calling a function from outside the file (where it's defined) is not allowed. Is there a solution to avoid this problem in order to call these static functions from my C++ test file?
I have a common header file that I include in all the source files of my projects. I have added these lines and the problem is solved:
#ifdef TEST
#define static
#endif
I can even avoid adding the above code in my origin C code. I could add the flag -Dstatic=
in the gcc command and I find this works as well.
But we have to be careful when using this solution because:
Assuming we are talking about C static functions then the easiest solution to this is to make the functions non-static when you are compiling a debug build. This means the symbols will be available for you to use in your unit tests. This only works if there is no aliasing of symbols though.
If you define the symbol DEBUG
on all debug builds then something like:
#ifdef DEBUG
#define debug_export
#else
#define debug_export static
#endif
and then define your static functions like this
debug_export void foo(void)
{
...
}
and either include the declarations conditionally in the header file or manually import them in your unit test file:
extern void foo(void);
Other ways around it are to either include the unit tests in the source file itself (a bit of a mess if it gets out of hand), not bother unit testing the function (a bit of a cop-out) or to mark the function as dll-local rather than static and ensure that your unit tests are part of that dynamic object.
Is there any way to refactor the code to remove the need for static methods? From an OO design point of view, statics are globals in sheep's clothing.
I know it's not necessarily the practical or quickest answer, but you would improve your design by eliminating it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With