依赖本人写的多平台编译器宏判断:
C/C++ MACOS、Windows、Linux、HarmonyOS 平台宏判断-CSDN博客
MACOS头文件依赖:
#if defined(_MACOS)
#include <libproc.h>
#endif
#include <mach-o/dyld.h>
只需要链接 libSystem.dylib 就行了,不需要在编译器上面声明链接它,编译器会隐式自动链接。
源代码:
cpp
std::string GetFullExecutionFilePath() noexcept {
#if defined(_WIN32)
char exe[8096]; /* MAX_PATH */
GetModuleFileNameA(NULL, exe, sizeof(exe));
return exe;
#elif defined(_MACOS)
char path[PATH_MAX];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0) {
return path;
}
#if defined(PROC_PIDPATHINFO_MAXSIZE)
char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
proc_pidpath(getpid(), pathbuf, sizeof(pathbuf));
return pathbuf;
#else
return "";
#endif
#else
char sz[PATH_MAX + 1];
int dw = readlink("/proc/self/exe", sz, PATH_MAX);
sz[dw] = '\x0';
return dw < 1 ? "" : sz;
#endif
}