Search code examples
c++linuxdynamic-library

List shared library in the program executed using C/C++ on Linux


I want to know which dynamic libraries are loaded when executing a C/C++ program on Linux.

For example,

int main()
{
    ...
    list = GetAllSharedLibraryFilePaths();
}

list should contain: libm.so.6, librt.so.1, ... or paths: /lib/x86_64-linux-gnu/libm.so.6, /lib/x86_64-linux-gnu/librt.so.1 ...

Are there any APIs that return all shared library file paths? I know ldd, readelf can do that but I need to do that with C/C++ programming in the executable that loads shared libraries.

Thank you.


Solution

  • You can use non-standard dl_iterate_phdr(3) function to walk through the list of loaded shared objects.

    #define _GNU_SOURCE
    #include <link.h>
    #include <stdio.h>
    
    int print(struct dl_phdr_info *info, size_t size, void *data) {
      printf("%s\n", info->dlpi_name);
      return 0;
    }
    
    int main() {
      dl_iterate_phdr(print, NULL);
      return 0;
    }
    
    $ gcc test.c -o test
    $ ./test
    
    linux-vdso.so.1
    /lib/x86_64-linux-gnu/libc.so.6
    /lib64/ld-linux-x86-64.so.2