Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

arvind_dev

macrumors newbie
Original poster
May 9, 2019
1
0
Bangalore
Hi

How can I get the path to currently running executable in C/C++?
I Googled about it but could find code only for Linux/Windows.

Thanks,
Arvind.
 
When I google this:
mac c code path to current executable

the following StackOverflow thread comes up at the top of the search results:
https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe

The top answer in that thread shows how to accomplish the goal for several platforms, including Mac OS, Windows, BSD, and Linux. Other replies discuss other approaches, which may also work.


The Mac-specific answer is _NSGetExecutablePath(). Its man page is:
https://developer.apple.com/library...Conceptual/ManPages_iPhoneOS/man3/dyld.3.html

The URL shows _iPhoneOS, but the man page and the function also exist on Mac OS. You can see this using the Terminal command:
Code:
man 3 dyld
 
Remember main has 'argv[0]' containing entire pathname of executable

EDIT: Perhaps useful code

Code:
#include <iostream>


int main(int const argc, const char* const argv[], char* envv[])
{
    using std::cout;
    using std::endl;

    // display this executables pathname
    cout << argv[0] << endl;


    // display launch environment variables
    while ( *envv )
    {
        cout << *envv++ << endl;
    }

    return EXIT_SUCCESS;
}
 
Last edited:
Code:
int main(int argc, const char * argv[])
{
   char *locationString = malloc(strlen(argv[0]));
   strcpy(locationString, argv[0]);
 
Remember main has 'argv[0]' containing entire pathname of executable
Not necessarily. For example, if you put the source you supplied into a file "./test.cpp", then type the command:
Code:
make test
It will make the executable 'test' in the current dir (wherever that is, and assuming it's writable).

Now run the executable just made:
Code:
./test

Fragment of output:
Code:
./test

That is, the executable receives the relative path to itself, without any information about where the current working directory is. Yes, the working dir path can be obtained (man getcwd).

Other relative paths have similar problems, such as ones containing "../".

The whole thing is a bit more of a puzzle than it first seems. Some (or most) of this is mentioned in the answers of the StackExchange thread I linked.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.