How to Check if the function exists in C/C++

前端 未结 8 2065
失恋的感觉
失恋的感觉 2020-12-01 06:24

Certain situations in my code, i end up invoking the function only if that function is defined, or else i should not. How can i achieve this ?

like:
if (func         


        
8条回答
  •  天命终不由人
    2020-12-01 06:59

    You can use #pragma weak for the compilers that support it (see the weak symbol wikipedia entry).

    This example and comment is from The Inside Story on Shared Libraries and Dynamic Loading:

    #pragma weak debug
    extern void debug(void);
    void (*debugfunc)(void) = debug;
    int main() {
        printf(“Hello World\n”);
        if (debugfunc) (*debugfunc)();
    }
    

    you can use the weak pragma to force the linker to ignore unresolved symbols [..] the program compiles and links whether or not debug() is actually defined in any object file. When the symbol remains undefined, the linker usually replaces its value with 0. So, this technique can be a useful way for a program to invoke optional code that does not require recompiling the entire application.

提交回复
热议问题