在 Linux 下用 C++ 配置路径,常见场景有几种,不同场景配置方式不一样。下面把最常见的几种情况都给你讲清楚,你可以按需对照。
std::ifstream in("./config.json"); // 相对路径
std::ifstream in("/home/user/config.json"); // 绝对路径
⚠️ 注意:
相对路径是相对于程序运行时的工作目录(pwd),不是 .cpp 文件位置。
/proc/self/exe(最常用,Linux 专用)#include <unistd.h>
#include <limits.h>
std::string getExePath() {
char path[PATH_MAX];
readlink("/proc/self/exe", path, PATH_MAX);
return std::string(path);
}
然后可以拼接配置路径:
std::string configPath = getExePath() + "/../config/config.json";
argv[0](不推荐)int main(int argc, char* argv[]) {
std::cout << argv[0] << std::endl;
}
❌ 不可靠(可能被修改)
g++ main.cpp -I/home/user/include
对应代码:
#include "mylib.h"
g++ main.cpp -L/home/user/lib -lmylib
-Wl,-rpathg++ main.cpp -L/home/user/lib -lmylib -Wl,-rpath=/home/user/lib
export LD_LIBRARY_PATH=/home/user/lib:$LD_LIBRARY_PATH
include_directories(${PROJECT_SOURCE_DIR}/include)
link_directories(${PROJECT_SOURCE_DIR}/lib)
target_link_libraries(app mylib)
install(TARGETS app DESTINATION bin)
install(FILES config.json DESTINATION etc)
#include <cstdlib>
const char* path = std::getenv("MY_APP_CONFIG");
运行前:
export MY_APP_CONFIG=/home/user/config.json
| 场景 | 推荐方式 |
|---|---|
| 程序找配置文件 | /proc/self/exe 定位 |
| 编译头文件 | -I 或 CMake |
| 链接库 | -L + -rpath |
| 可配置路径 | 环境变量 |
| 工程化 | CMake |
std::string getConfigPath() {
char buf[PATH_MAX];
readlink("/proc/self/exe", buf, PATH_MAX);
std::string exe(buf);
auto pos = exe.find_last_of("/");
return exe.substr(0, pos) + "/../config/config.json";
}
如果你能具体说一下:
我可以直接给你一套最适合你项目的配置方案。