Function pointer to __attribute__((const)) function?

ⅰ亾dé卋堺 提交于 2019-12-13 12:25:44

问题


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.



来源:https://stackoverflow.com/questions/9441262/function-pointer-to-attribute-const-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!