-1

In Ubuntu with C++, I have been given some code which creates an executable called Alpha. The code requires loading text files at runtime, and so there is a section of the code which finds the path of the executable, such that the relative directory containing these text files can be found. The executable path is determined by /proc/self/exe.

Now, instead of creating the executable Alpha, I want to create a library called LibAlpha with the same code as Alpha, and then create another executable called Beta which calls LibAlpha. However, the problem with doing this using Alpha's original code, is that when /proc/self/exe is called, it returns the path of Beta, rather than the path of LibAlpha. How can I get the path of the called library, rather than the executable?

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247
  • Possible duplicate of: [Finding the absolute path of the currently running shared object](http://stackoverflow.com/questions/27816739/finding-the-absolute-path-of-the-currently-running-shared-object#comment44040148_27816739). Have a look at the link from my comment. – πάντα ῥεῖ Jan 07 '15 at 17:00

1 Answers1

1

In your library code:

#ifndef _GNU_SOURCE
#   define _GNU_SOURCE 1
#endif _GNU_SOURCE
#include <dlfcn.h>

#include <string>

std::string my_path() {
    Dl_info info;
    return dladdr(reinterpret_cast<void*>(&my_path), &info) 
        ? info.dli_fname 
        : std::string()
        ;
}
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • You forgot the `#define _GNU_SOURCE` before the `#include ` since `dladdr` is only a GNU extension. See [feature_test_macros(7)](http://man7.org/linux/man-pages/man7/feature_test_macros.7.html) & [dladdr(3)](http://man7.org/linux/man-pages/man3/dladdr.3.html) – Basile Starynkevitch Jan 07 '15 at 16:56