Question

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.

Was it helpful?

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

OTHER TIPS

On linux

put the functions in a separate shared library (.so). Then use dlopen to open it and dlsym to get a function pointer by its name

On windows

put the functions in a separate dll (basically the same thing). Then use LoadLibrary to open it and GetProcAddress to get a pointer to the function

A lot more typing that you wanted to do , but it will let you do what you want

What you can do is define an array of function pointers with all your functions and then loop in all elements of the array.

int (*array[])(void) = {test1, test2, test3};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top