c/c++程序中获取当前可执行文件所在的目录路径,使用跨平台的program_location

c/c++程序中获取当前可执行文件所在的目录路径

对于大型工程中,可执行文件中通过c/c++代码获取到当前路径,可以很大方便于工程后续的部署与运维工作。

比如说根据当前的可执行文件路径获取到配置文件的路径,然后加载读取配置文件。

有了这个能力就不用再在操作系统中配置环境变量来指定当前工程的目录了,让事情变得简单了不少。

由于c++在语言层面并没有获取可执行文件相关的定义,所示各个平台操作系统都有自己的不同实现。例如:

linux下可以通过系统调用readlink读取/proc/self/exe数据,如下面代码所示:

#pragma once
#include <string>
#include <unistd.h>

//////////////////////////////////////////////////////////
// for linux platform

namespace vi
{
    class vdirectory
    {
    public:
        //get current executor abslout full path (filename with path)
        static std::string get_current_executor_path()
        {
            const std::size_t MAXBUFSIZE = 2048;
            char buf[MAXBUFSIZE] = {'\0'};
            readlink("/proc/self/exe", buf, MAXBUFSIZE);
            return std::string(buf);    // 0 is for heap memory
        }
    };

}

 

但是这方法并不能在windows和macos平台上使用。它们分别有自己的实现。如windows下使用GetModuleFileName实现,示例代码如下:

#include <stdio.h>
#include <windows.h>
int main()
{
    char ExeFile[256];
    //得到当前文件路径名
    GetModuleFileName(NULL,ExeFile,200);
    printf("当前文件路径为:\n");
    printf("%s\n",ExeFile);
    return 0;
}

 

上面的这些实现,各自都不具备跨平台性。

更好的跨平台解决方案:

浏览boost文档,无意中发现了一个新库:dll,这个库里有个program_location函数可以获得当前可执行文件的全路径。代码如下所示:

#include <boost/dll/runtime_symbol_info.hpp>

 
boost::dll::fs::path path_exec = boost::dll::program_location();
std::cout<<"this executor path is:"<<path_exec.string()<<std::endl;

 

经测试,这一方法可以在多个常用的OS平台上成功使用。

所以写下此文分享给大家。

 

posted @ 2023-04-27 20:03  元几科技  阅读(1463)  评论(0编辑  收藏  举报