在 Linux 下用 C++ 进行程序配置,常见做法有几种,从简单到复杂,按使用场景选择即可。下面按推荐程度 + 实际项目经验给你一个完整说明。
| 方式 | 适合场景 | 推荐指数 |
|---|---|---|
| 命令行参数 | 简单参数、调试 | ⭐⭐⭐ |
| INI 文件 | 简单配置 | ⭐⭐⭐⭐ |
| JSON 文件 | 现代项目、复杂配置 | ⭐⭐⭐⭐⭐ |
| YAML 文件 | 可读性强、复杂结构 | ⭐⭐⭐⭐ |
| 环境变量 | 系统级配置 | ⭐⭐⭐ |
| 数据库 / 远程配置 | 服务端 | ⭐⭐ |
适合少量参数。
#include <unistd.h>
#include <iostream>
int main(int argc, char* argv[]) {
int opt;
std::string configFile;
while ((opt = getopt(argc, argv, "c:")) != -1) {
if (opt == 'c') {
configFile = optarg;
}
}
std::cout << "config file: " << configFile << std::endl;
}
运行:
./app -c config.json
✅ 优点:简单
❌ 缺点:不适合大量配置
config.ini[server]
host = 127.0.0.1
port = 8080
[log]
level = info
Linux 下没有标准 INI 库,可:
#include "ini.h"
#include <iostream>
int handler(void* user, const char* section,
const char* name, const char* value) {
std::cout << section << "." << name << " = " << value << "\n";
return 1;
}
int main() {
ini_parse("config.ini", handler, nullptr);
}
✅ 适合:小型服务、工具
❌ 不适合:复杂嵌套结构
config.json{
"server": {
"host": "127.0.0.1",
"port": 8080
},
"log": {
"level": "debug"
}
}
| 库 | 特点 |
|---|---|
| nlohmann/json | 最流行、易用 |
| rapidjson | 高性能 |
| jsoncpp | 老牌 |
sudo apt install nlohmann-json3-dev
#include <iostream>
#include <fstream>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
int main() {
std::ifstream in("config.json");
json j;
in >> j;
std::string host = j["server"]["host"];
int port = j["server"]["port"];
std::cout << host << ":" << port << std::endl;
}
✅ 优点:
config.yamlserver:
host: 127.0.0.1
port: 8080
log:
level: info
sudo apt install libyaml-cpp-dev
#include <yaml-cpp/yaml.h>
#include <iostream>
int main() {
YAML::Node config = YAML::LoadFile("config.yaml");
std::string host = config["server"]["host"].as<std::string>();
int port = config["server"]["port"].as<int>();
std::cout << host << ":" << port << std::endl;
}
✅ 适合:大型项目、运维友好
❌ 依赖稍重
常用于 Docker / 云环境。
#include <cstdlib>
#include <iostream>
int main() {
const char* port = std::getenv("APP_PORT");
if (port) {
std::cout << "port=" << port << std::endl;
}
}
export APP_PORT=8080
./app
✅ 常配合 JSON / YAML 使用
project/
├── bin/
│ └── app
├── conf/
│ ├── config.json
│ └── config.yaml
├── src/
└── CMakeLists.txt
读取时:
std::ifstream in("../conf/config.json");
✅ 新项目推荐顺序
如果你愿意,可以告诉我:
我可以直接给你一个 完整可编译的 C++ 配置模板。