Search code examples
ccross-compilingglibcglib

How do I get the executing program's directory in C using a plataform independent method?


I develop my app in Linux for both unix and win32(cross compile at each build) platforms, so a ready to use function would be nice :). I'm using glib that has the gchar* g_get_current_dir(void) function and it returns the current directory, but what I really need is the executable's directory. I'm inexperienced in C programming so any suggestions are welcome.


Solution

  • Under Unix like operating systems that have the /proc directory you can readlink /proc/self/exe to get the actual executable files full path even when argv[0] does not have this.

    This may not work, however, if the executable was started with fexecv (not available on many systems) and if that is implemented as a system call on your system. fexecv is just like execve except that it is passed an open file descriptor rather than a filename to run. Under Linux it is implemented by calling execve on the string generated by `"/proc/self/%i", fd", so the file would have to live in the file system at the time the program was started.

    I think that GNU/Hurd supports fexecve natively.

    It is possible for an executable file to be renamed or unlinked from the filesystem after it has been executed which makes it become an unnamed file which will go away as soon as it ceases to be open (in this context running a file usually requires it to be open by the kernel).