简体   繁体   中英

how to catch symbol lookup error

How can i catch an symbol lookup error in my code so currently my program crashes?

void main()
{
  try {
    dlopen("shared.so", RTLD_LAZY);
    /** 
      now running a function in this shared object and 
      this function calls a undefined reference
      and then it crashes but i want to go in the catch block
    */
  } catch(...) {
  }
}

dlopen is C function. It doesn't throw any exception .

void *dlopen(const char *filename, int flag);

From man dlopen

If dlopen() fails for any reason, it returns NULL.

So, check return value for NULL .

So, for check, that symbol exists you should use

void *dlsym(void *handle, const char *symbol);

If the symbol is not found, in the specified library or any of the libraries that were automatically loaded by dlopen() when that library was loaded, dlsym() returns NULL . (The search performed by dlsym() is breadth first through the dependency tree of these libraries.) Since the value of the symbol could actually be NULL (so that a NULL return from dlsym() need not indicate an error), the correct way to test for an error is to call dlerror() to clear any old error conditions, then call dlsym(), and then call dlerror() again, saving its return value into a variable, and check whether this saved value is not NULL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM