在 Linux 下用 C++ 写配置脚本,通常有两种理解,我先分开说明,再给示例。
通常是 Shell 脚本(bash)来完成:
#!/bin/bash
set -e
echo "开始配置 C++ 项目..."
# 创建构建目录
mkdir -p build
cd build
# 使用 CMake 配置
cmake ..
# 编译
make -j$(nproc)
echo "构建完成"
使用方式:
chmod +x build.sh
./build.sh
配置一般写成:
.ini.json.yamlconfig.ini
ip=127.0.0.1
port=8080
debug=true
C++ 读取示例(简化版):
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
std::map<std::string, std::string> loadConfig(const std::string& file) {
std::map<std::string, std::string> cfg;
std::ifstream in(file);
std::string line;
while (std::getline(in, line)) {
if (line.empty() || line[0] == '#') continue;
size_t pos = line.find('=');
if (pos != std::string::npos) {
cfg[line.substr(0, pos)] = line.substr(pos + 1);
}
}
return cfg;
}
int main() {
auto cfg = loadConfig("config.ini");
std::cout << "ip=" << cfg["ip"] << std::endl;
}
config.json
{
"ip": "127.0.0.1",
"port": 8080
}
使用 nlohmann/json:
#include <iostream>
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
int main() {
std::ifstream f("config.json");
json cfg = json::parse(f);
std::cout << cfg["ip"] << std::endl;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(demo)
set(CMAKE_CXX_STANDARD 17)
add_executable(demo main.cpp)
你可以告诉我:
我可以直接给你完整可运行示例。