添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

C++ – 跨平台在Windows、Linux系统上获取当前可执行程序路径

2023-09-07 本文共1663个字,阅读需要5分钟。

1 C++ 跨平台 Windows Linux 系统上 获取当前可执行程序路径

跨平台获取当前可执行程序路径是C++跨平台项目中会经常使用的功能,我将这个功能简单的封装成了一个 PathUtils 工具类,在该类中通过 GetCurrentProgramDirectory 静态函数获取当前可执行程序路径,下面贴出了功能实现代码。

path_utils.h

#ifndef _PATH_UTILS_H_
#define _PATH_UTILS_H_
#include <string>
class PathUtils
public:
    // 得到当前程序执行路径
    static std::string GetCurrentProgramDirectory();
#endif // !_PATH_UTILS_H_

path_utils.cpp

#include "path_utils.h"
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#include<Windows.h>
#elif defined(linux) || defined(__linux)
#include <string.h>
#include <unistd.h>
#include <dlfcn.h>
#endif // WINDOWS
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
static HMODULE GetSelfModuleHandle()
    MEMORY_BASIC_INFORMATION mbi;
    return (
        (::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0)
        ? (HMODULE)mbi.AllocationBase : NULL
std::string PathUtils::GetCurrentProgramDirectory()
    std::string strCurrentPath = "";
    char curDirector[260] = { 0 };
    GetModuleFileName(GetSelfModuleHandle(), curDirector, 260);
    strCurrentPath = curDirector;
    size_t nameStart = strCurrentPath.rfind("\\");
    strCurrentPath = strCurrentPath.substr(0, nameStart + 1);
    return strCurrentPath;
#elif defined(linux) || defined(__linux)
std::string PathUtils::GetCurrentProgramDirectory()
    std::string strCurrentPath = "";
    char szCurWorkPath[256];
    memset(szCurWorkPath, '\0', 256);
    int nRet = readlink("/proc/self/exe", szCurWorkPath, 256);
    if (nRet > 256 || nRet < 0)
        return strCurrentPath;
    for (int i = nRet; i > 0; i--)
        if (szCurWorkPath[i] == '/' || szCurWorkPath[i] == '\\')
            szCurWorkPath[i] = '\0';
            break;
    strCurrentPath = szCurWorkPath;
    return strCurrentPath;
#endif
#include <iostream>
#include "path_utils.h"
int main()
    std::cout << "Path : " << PathUtils::GetCurrentProgramDirectory() << std::endl;
    return 0;
				

本文作者:StubbornHuang

版权声明:本文为站长原创文章,如果转载请注明原文链接!

原文标题:C++ – 跨平台在Windows、Linux系统上获取当前可执行程序路径

原文链接:https://www.stubbornhuang.com/2790/

发布于:2023年09月07日 11:45:54

修改于:2023年09月07日 11:45:54

如果您觉得对您有帮助,可以请站长喝一杯咖啡哦!

记得在赞赏备注里写上您的昵称

金额随意,礼轻义重

您可在本站资助名单中查看你的打赏记录哦!

alipay code image

支付宝扫一扫

wechatpay code image

微信扫一扫

当前分类随机文章推荐

全站随机文章推荐