温馨提示×

linux c++配置怎样写脚本

小樊
38
2026-10-07 23:59:20
栏目: 编程语言

在 Linux 下用 C++ 写配置脚本,通常有两种理解,我先分开说明,再给示例。


一、用脚本自动配置 / 编译 C++ 项目(最常见)

通常是 Shell 脚本(bash)来完成:

  • 安装依赖
  • 编译
  • 生成配置

示例:build.sh

#!/bin/bash

set -e

echo "开始配置 C++ 项目..."

# 创建构建目录
mkdir -p build
cd build

# 使用 CMake 配置
cmake ..

# 编译
make -j$(nproc)

echo "构建完成"

使用方式:

chmod +x build.sh
./build.sh

二、在 C++ 程序中读取配置文件(配置脚本)

配置一般写成:

  • .ini
  • .json
  • .yaml
  • 或自定义格式

示例 1:简单 ini 风格配置

config.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;
}

示例 2:用 JSON 配置(推荐)

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;
}

三、用 CMake 作为“配置脚本”(工程级)

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(demo)

set(CMAKE_CXX_STANDARD 17)

add_executable(demo main.cpp)

四、你更关心哪一种?

你可以告诉我:

  1. 是想 写 shell 脚本配置环境?
  2. 还是 C++ 程序读取配置
  3. 还是 CMake / Makefile 配置

我可以直接给你完整可运行示例。

0 踩