I have a program that has binaries for many different OS’s
I have need to get the location of the binary (think auto-updater)
How to do so in ‘your’ OS?
(Think of it as a challenge, of sorts 🙂 )
EDIT Note: The program can be portable (run off flash drive, etc) or installed (e.g. initially in .deb format)
EDIT2: Here’s what i have already:
/**
* Get the location of the executable
* @return the location of the executable, as a string.
*/
const char *GetExecutableLocation()
{
const char *path;
char buf[1024];
#if defined (WIN32) || defined (WIN64)
GetModuleFileName(path, &size);
#elif defined (__APPLE__)
_NSGetExecutablePath(path, &size);
#elif defined(UNIX)
if (readlink("/proc/self/exe", buf, sizeof(buf)) == -1) path = buf;
#elif defined(__FreeBSD__)
int mib[4];
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
sysctl(mib, 4, buf, sizeof(buf), NULL, 0);
path = buf;
#elif defined(SUNOS)
path = getexecname();
#endif
return path;
}
(note that i have only tested the unix section, i don’t know about anything else)
There is no portable way.
The rough ideas for the main operating systems (I’m leaving out the details here):
Note: argv[0] is generally useless; it gives the name that was used to invoke the program in a console environment, but doesn’t resolve shell search paths, and may not be available in some environments. It doesn’t exist on Windows GUI programs, and I’m not even sure what MacOS passes as argv[0] when you run the program via the GUI.