Search code examples
cgcctypesfunction-pointers

Function pointer to __attribute__((const)) function?


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.


Solution

  • 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;