Get List of Shared Libraries in the Program on Linux using C++

Get List of Shared Libraries in the Program on Linux using C++

In the realm of Linux programming, understanding the shared libraries associated with a program is important for efficient troubleshooting. Shared libraries are crucial components that house reusable code and functions, allowing multiple programs to utilize the same resources. This tutorial shows how to get list of shared libraries in the program on Linux using C++.

The following code can be used to obtain a list of shared libraries used by a program on a Linux system:

#include <iostream>
#include <link.h>

int main()
{
    dl_iterate_phdr([](struct dl_phdr_info *info, size_t size, void *data) {
        if (info->dlpi_name[0] != '\0') {
            std::cout << info->dlpi_name << std::endl;
        }

        return 0;
    }, nullptr);

    return 0;
}

The dl_iterate_phdr is a function for iterating over the shared libraries which used by the program. The first argument is a lambda function (also known as an anonymous function) that will be called for each shared library. Within the lambda function, we check if the name of the shared library is not an empty string. If the name is not empty, we print the name of the shared library to the standard output.

Here's an example of the output:

linux-vdso.so.1
/lib/x86_64-linux-gnu/libstdc++.so.6
/lib/x86_64-linux-gnu/libc.so.6
/lib/x86_64-linux-gnu/libm.so.6
/lib64/ld-linux-x86-64.so.2
/lib/x86_64-linux-gnu/libgcc_s.so.1

Leave a Comment

Cancel reply

Your email address will not be published.