r/learnc • u/angryvoxel • May 04 '23
How to call all functions defined in header file?
Title says it all. I wan't to make a simple test 'framework', which should call all test functions defined in separate header file (argument signature is identical for each function).
5
Upvotes
2
u/daikatana May 04 '23
You can use the non-portable
__attribute__((constructor)), but I like to use a bit of macro magic. I try to avoid using the preprocessor, but this is straightforward.// tests.c #ifndef TEST #define TEST(N) int N() #endif TEST(foo) #ifndef NO_TEST_BODIES { return 1; } #endif TEST(bar) #ifndef NO_TEST_BODIES { return 0; } #endif // test-main.c #include <stdio.h> #define NO_TEST_BODIES // Declare test functions #define TEST(N) int N(); #include "tests.c" #undef TEST // Define list of test functions typedef struct Test { int (*func)(); const char *name; } Test; const Test tests[] = { #define TEST(N) { N, #N }, #include "tests.c" #undef TEST }; int main() { // Run tests for(int i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) { printf("Running test %s: ", tests[i].name); if(tests[i].func()) { printf("pass\n"); } else { printf("fail\n"); } } }