获取C中函数的名称

Get the name of a function in C

我正在实现一个测试库,我希望能够打印失败的测试函数。因此我需要一种方法来获取失败函数的名称。我知道有像 __func____FUNCTION__ 这样的预定义标识符,但它们只给我最后执行的函数的名称。我也不想在单元测试函数中使用这些标识符,而是在运行所有测试的过程中。

我发布了一个示例,它使用了一个名为 function_name 的虚构函数。是否有任何宏或其他东西可用于此目的?

/** 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);
}

由于您使用的是 C,一个好的解决方案似乎在于使用预处理器,以及为 unit_test 类型使用更丰富的结构。也就是说:它不仅包含函数指针,还包含函数名称,例如:

struct _unit_test {
   int (*func)();
   char* func_name;
};
typedef struct _unit_test unit_test;

像这样的宏将有助于填充它

#define ptr_name(x) {x, #x}

tests 数组的初始化可以是

unit_tests tests[] = {ptr_name(func1), ptr_name(func2)};

您必须更改代码的以下行

test_result result = (*tests[i])();

test_result result = tests[i].func();

失败的结果行

printf("Test %s failed!\n", tests[i].func_name);