Get Executable File Path on Linux using C++

Get Executable File Path on Linux using C++

In a Linux environment, retrieving the path to the executable file being run is a common requirement for various applications and systems. Knowing the executable file path can be crucial for operations such as dynamically loading libraries, configuring settings, or managing resources specific to the application. This tutorial explains how to get executable file path on Linux using C++.

The provided code retrieves and prints the absolute path of the executable file being run on a Linux system:

#include <iostream>
#include <climits>
#include <unistd.h>

int main()
{
    char path[PATH_MAX + 1];
    ssize_t length = readlink("/proc/self/exe", path, PATH_MAX);
    path[length] = '\0';

    std::cout << path << std::endl;

    return 0;
}

Inside the main function, a character array is declared to hold the path of the executable. PATH_MAX is a system-defined constant representing the maximum length of a file path. To ensure sufficient space for the complete path with the null terminator, PATH_MAX + 1 is used as the size for the character array.

The readlink function is used to read the symbolic link /proc/self/exe. On Linux, this symbolic link points to the executable file associated with the current process. After the readlink call, the character array is not null-terminated, so we explicitly place a null character at the end of the string.

The absolute path of the executable file is printed to the standard output. Example:

/home/john/projects/cpp/myapp

Leave a Comment

Cancel reply

Your email address will not be published.