Search code examples
cgoogleteststatic-functions

how to test static functions of C using google test


I have a C file contains some static functions, how to use google test to test those static function?

header file:

test.h
int accessData();

source file:

test.c
static int value;
static int getData()
{
   return value;
}

int accessData()
{
    if(value != 0)
    {
       return getData();
    }
    return 0;
}

static function is called by global function, but how to test those static function using google test?


Solution

  • One way to achieve this is to #include the C source file into your test source (if it's using only the subset of C that's valid C++). Then, the static function is part of the same translation unit as the test code, and can be called from it:

    #include "test.c"
    
    /* here follow the tests of getData() */
    

    The downside to this is that everything in test.c gets compiled again, with obvious impact on build times. If that gets to be a problem, you might consider extracting the static functions to be tested into their own source file (e.g. test_p.c, with the _p meaning private/internal). Then #include "test_p.c" from both test.c and your unit test.