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

前端 未结 8 1994
失恋的感觉
失恋的感觉 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 07:06

    If you know what library the function you'd like to call is in, then you can use dlsym() and dlerror() to find out whether or not it's there, and what the pointer to the function is.

    Edit: I probably wouldn't actually use this approach - instead I would recommend Matiu's solution, as I think it's much better practice. However, dlsym() isn't very well known, so I thought I'd point it out.

    0 讨论(0)
  • 2020-12-01 07:14

    Using GCC you can:

    void func(int argc, char *argv[]) __attribute__((weak)); // weak declaration must always be present
    
    // optional definition:
    /*void func(int argc, char *argv[]) { 
        printf("ENCONTRE LA FUNC\n");
        for(int aa = 0; aa < argc; aa++){
            printf("arg %d = %s \n", aa, argv[aa]);
        }
    }*/
    
    int main(int argc, char *argv[]) {
        if (func){ 
            func(argc, argv); 
        } else {
            printf("no encontre la func\n");
        }
    }
    

    If you uncomment func it will run it otherwise it will print "no encontre la func\n".

    0 讨论(0)
提交回复
热议问题