Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dynamic library directory in c++ (linux)

Tags:

c++

linux

Is there any programmatic way to get the location of a dynamic library loaded by a program?

I know that it is possible to get the 'executable' running path. But it is not enough for me.

I'm developing an external library that has some dependencies and I need to point accordingly to its location.

For example, the program is running at:

/local/deepLearning/bin

And this program uses a dynamic library located at:

/local/external/libs/faciesAnalysis

What I need is, at runtime, the string

"/local/external/libs/facesAnalysis"

I am working on linux, any suggestion?

like image 427
João Paulo Navarro Avatar asked Oct 15 '15 14:10

João Paulo Navarro


1 Answers

Since this is specifically Linux, dladdr() is a glibc extension to the dl family of functions that will lookup the filename of any symbol. Pass it the address of any function that you know exists in the library you are looking for, and you're basically done.

Presented without appropriate error checking:

#define _GNU_SOURCE
#include <dlfcn.h>

const char *my_fname(void) {
    Dl_info dl_info;
    dladdr((void*)my_fname, &dl_info);
    return(dl_info.dli_fname);
}
like image 162
Peter Avatar answered Sep 26 '22 16:09

Peter