Finding current executable's path without /proc/self/exe

前端 未结 13 827
有刺的猬
有刺的猬 2020-11-22 01:06

It seems to me that Linux has it easy with /proc/self/exe. But I\'d like to know if there is a convenient way to find the current application\'s directory in C/C++ with cros

13条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 01:30

    Some OS-specific interfaces:

    • Mac OS X: _NSGetExecutablePath() (man 3 dyld)
    • Linux: readlink /proc/self/exe
    • Solaris: getexecname()
    • FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
    • FreeBSD if it has procfs: readlink /proc/curproc/file (FreeBSD doesn't have procfs by default)
    • NetBSD: readlink /proc/curproc/exe
    • DragonFly BSD: readlink /proc/curproc/file
    • Windows: GetModuleFileName() with hModule = NULL

    There are also third party libraries that can be used to get this information, such as whereami as mentioned in prideout's answer, or if you are using Qt, QCoreApplication::applicationFilePath() as mentioned in the comments.

    The portable (but less reliable) method is to use argv[0]. Although it could be set to anything by the calling program, by convention it is set to either a path name of the executable or a name that was found using $PATH.

    Some shells, including bash and ksh, set the environment variable "_" to the full path of the executable before it is executed. In that case you can use getenv("_") to get it. However this is unreliable because not all shells do this, and it could be set to anything or be left over from a parent process which did not change it before executing your program.

提交回复
热议问题