'Get the name of a function in C
I'm implementing a test library and I want to be able to print the test functions, which fail. Therefore I need a way to get the name of the failing function. I know there are predefined identifiers like __func__ and __FUNCTION__, but they only give me the name of the last executed function. I also don't want to use those identifiers inside the unit test functions, but in the procedure, which runs all the tests.
I posted an example, which uses an imaginary function called function_name. Is there any macro or something else available for this purpose?
/** Description
* This function calls a number of unit tests and print the results.
* Please note the imaginary function 'function_name'.
*
* Parameters:
* tests: Function pointers to unit tests
* number_tests: The number of tests to run
*/
void run_tests(unit_test* tests, unsigned int number_tests) {
int number_passed = 0;
for (unsigned int i = 0; i < number_tests; i++) {
// Execute the unit test and get the result
test_result result = (*tests[i])();
if (result == TEST_PASSED)
number_passed++;
else
printf("Test %s failed!\n", function_name(*tests[i]));
}
printf("%d/%d passed tests, %d failed tests\n", number_passed,
number_tests, number_tests - number_passed);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
