Function pointer to __attribute__((const)) functio

2020-08-17 06:50发布

问题:

How (in GCC/"GNU C") do you declare a function pointer which points to an __attribute__((const)) function? The idea being that I want the compiler to avoid generating multiple calls to the function called through the function pointer when it can cache the return value from a previous call.

回答1:

typedef void (*t_const_function)(void) __attribute__((const));

static __attribute__((const)) void A(void) {
}

static void B(void) {
}

int main(int argc, const char* argv[]) {
    t_const_function a = A;

    // warning: initialization makes qualified
    // function pointer from unqualified:
    t_const_function b = B;

    return 0;
}

Or just:

__attribute__((const)) void(*a)(void) = A;


回答2:

Although this is not quite the answer to your question, you probably want to know this:

You can't in the general case expect the compiler to perform the optimization you expect here. The compiler cannot in the general case do the alias analysis necessary to know that multiple uses of a function pointer correspond to the same function.

A function call in between two invocations of the function through the pointer could, in the general case, alter the pointer contents, thus causing the invoked function to be different in the second call.

Because of the nature of C, doing proper alias analysis is often intractable, and this sort of optimization is thus not likely to happen.