title: Obtaining filename at runtime for a shared library c++
body: <p>I have some code that is compiled as a shared library and used with a universal driver, which can be used with other shared libraries that are specific to a particular application.</p>
  
  <p>My question pertains to obtaining some sort of indicator of the name of the binary containing a code that lives in that shared library.</p>
  
  <p>For example, let's say I have 3 files, the first is driver.cpp, the universal driver:</p>
  
  <pre><code>#include "interface.h"
  #include &lt;stdio.h&gt;
  int main(int argc, char *argv[]) {
      //perform a function from the shared library
      std::cout &lt;&lt; foobar() &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>The second is sharedlibrary.cpp, the specific implementation for one case of many:</p>
  
  <pre><code>#include "interface.h"
  char* foobar() {
      return x;
  }
  </code></pre>
  
  <p>Where <code>x</code> is some indicator that this function is defined in sharedlibrary.cpp, or that this function is linked from sharedlibrary.so, or the current stack frame is using the specific binary rather than just being included in driver.cpp.</p>
  
  <p>The last file is interface.h, which provides the interface to the library via <code>extern "C"</code></p>
  
  <pre><code>extern "C" {
  char foobar();
  }
  </code></pre>
  
  <p>I would like to reiterate, for clarity, that I am looking for some indication that this function is being linked from sharedlibrary.so. Many solutions looking for runtime filenames give the <em>executable name</em> using either argv[0] or readlink(), but I have no control over the actual naming of driver.cpp or its executable name. Rather, I can distribute sharedlibrary.so, and would like to be able to use its name from within itself, if possible.</p>
  
  <p>If it helps, I know that a microsoft-specific solution could be to use <code>AfxGetApp()-&gt;m_pszAppName</code> to obtain the DLL name. However, I am looking for a linux solution that does not necessarily need to be portable.</p>
  
  <p>EDIT: I do not know or control the names of driver.cpp, sharedlibrary.cpp, or sharedlibrary.h at compile time. I wish to discover the name of sharedlibrary.cpp at run time.</p>
  
  <p>The updated sharedlibrary.cpp with <code>x</code> replaced with the solution looks like this</p>
  
  <pre><code>#include "interface.h"
  #include &lt;dlfcn.h&gt;
  void func() {
      //Some function that is defined in sharedlibrary.cpp
  }
  
  char* foobar() {
      Dl_info DlInfo;
      if(!dladdr((void*)func, &amp;DlInfo)) {
          return "default_name";
      }
      return DlInfo.dli_fname;
  }
  </code></pre>