Skip to content

Instantly share code, notes, and snippets.

@hoozh
Last active April 12, 2025 02:50
Show Gist options
  • Save hoozh/5cbc9e16f1833e06b231d79d58659d11 to your computer and use it in GitHub Desktop.
Save hoozh/5cbc9e16f1833e06b231d79d58659d11 to your computer and use it in GitHub Desktop.
get Executable directory cross platform
QString getExecutableDir() {
#if defined(Q_OS_MAC)
unsigned int bufferSize = 512;
std::vector<char> buffer(bufferSize + 1);
if(_NSGetExecutablePath(&buffer[0], &bufferSize))
{
buffer.resize(bufferSize);
_NSGetExecutablePath(&buffer[0], &bufferSize);
}
char* lastForwardSlash = strrchr(&buffer[0], '/');
if (lastForwardSlash == NULL) return NULL;
*lastForwardSlash = 0;
return &buffer[0];
#elif defined(Q_OS_WINDOWS)
HMODULE hModule = GetModuleHandleW(NULL);
WCHAR path[MAX_PATH];
DWORD retVal = GetModuleFileNameW(hModule, path, MAX_PATH);
if (retVal == 0) return NULL;
wchar_t *lastBackslash = wcsrchr(path, '\\');
if (lastBackslash == NULL) return NULL;
*lastBackslash = 0;
return QString::fromWCharArray(path);
#elif defined(Q_OS_LINUX)
char pBuf[FILENAME_MAX];
int len = sizeof(pBuf);
int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);
if (bytes >= 0) {
pBuf[bytes] = '\0';
}
char* lastForwardSlash = strrchr(&pBuf[0], '/');
if (lastForwardSlash == NULL) return NULL;
*lastForwardSlash = '\0';
return QString::fromStdString(pBuf);
#else
#error getExecutableDir not implemented on this platform
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment