Search code examples
cdynamic-function

C - dynamic function call


I have a testing file with tests defined as

static int test1(){
    /*some tests here*/
    return 0;
}
static int test2(){
    /*some tests here*/
    return 0;
}
/*...etc*/`

and I was wondering if there's a way to call all of the tests in a loop, instead of writing the call for each one. (There are some functions I need to call before and after each test, and with >20 tests, this might get really annoying. I've also just been curious about doing things like this for a while.)

I was thinking something similar to:

int main(){
    int (*test)() = NULL;
    for(i = 1; i <= numtests; i++){
      /*stuff before test*/
      (*test)();
      /*stuff after test*/
    }
    return 0;
}

but I'm not sure how to proceed with using the value of "i" to set the test pointer.


Solution

  • You can use a self inclusion trick to get a list of function pointers:

    #ifndef LIST_TESTS
    #define TEST(name, ...) static int name() __VA_ARGS__
    
    /* all includes go here */
    #endif // ifndef LIST_TESTS
    
    TEST(test1, {
      /* some tests here */
      return 0;
    })
    
    TEST(test2, {
      /* some tests here */
      return 0;
    })
    
    #undef TEST
    
    #ifndef LIST_TESTS
    int main(void) {
      int (*tests[])() = {
        #define LIST_TESTS
        #define TEST(name, ...) name,
        #include __FILE__
      };
      int num_tests = sizeof(tests) / sizeof(tests[0]);
      int i;
    
      for (i = 0; i < num_tests; ++i) {
        /* stuff before test */
        (tests[i])();
        /* stuff after test */
      }
    
      return 0;
    }
    #endif // ifndef LIST_TESTS