I have this requirement where I need to find the full path for the C++ program from within. For Windows, I have the following solution. The argv[0] may or may not contain the full path. But I need to be certain.
TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR], base[_MAX_FNAME], ext[_MAX_EXT];
TCHAR fullPath[255+1];
_splitpath(argv[0],drive,dir,base,ext);
SearchPath(NULL,base,ext,255,fullPath,NULL);
What is the Linux (gcc) equivalent for the above code? Would love to see a portable code.
If you came here when Googling for
GetModuleFileName Linux
... you're probably looking for the ability to do this for dynamically-loaded libraries. This is how you do it:For Linux:
Function to execute system command
Then we get app name
Then we extract application path
Do not forget to trim the line after
On Linux (Posix?) you have a symbolic link
/proc/self/exe
which links to the full path of the executable.On Windows, use
GetModuleFileName
.Never rely on
argv[0]
, which is not guaranteed to be anything useful.Note that paths and file systems are not part of the language and thus necessarily a platform-dependent feature.
The top answer to this question lists techniques for a whole bunch of OSes:
Finding current executable's path without /proc/self/exe