Programmatically retrieving the absolute path of an OS X command-line app

The function _NSGetExecutablePath will return a full path to the executable (GUI or not). The path may contain symbolic links, “..“, etc. but the realpath function can be used to clean those up if needed. See man 3 dyld for more information.

char path[1024];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0)
    printf("executable path is %s\n", path);
else
    printf("buffer too small; need size %u\n", size);

The secret to this function is that the Darwin kernel puts the executable path on the process stack immediately after the envp array when it creates the process. The dynamic link editor dyld grabs this on initialization and keeps a pointer to it. This function uses that pointer.

Leave a Comment