← 返回主页

args 使用指南

args 是一个功能强大且易于使用的 C++ 命令行参数解析库,帮助开发者轻松处理 CLI 输入。它支持位置参数、标志选项、可选参数等多种形式。

📦 安装

从 GitHub 获取

git clone https://github.com/Taywee/args.git

头文件方式使用

#include <args.hxx>

🚀 基础使用

简单的 Hello World

#include <args.hxx>
#include <iostream>

int main(int argc, char** argv) {
    args::ArgumentParser parser("This is a test program.", "This goes after the options.");
    args::HelpFlag help(parser, "HELP", "Display this help menu", {'h', "help"});
    
    try {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help) {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }

    std::cout << "Hello, World!" << std::endl;
    return 0;
}

位置参数

#include <args.hxx>
#include <iostream>
#include <string>

int main(int argc, char** argv) {
    args::ArgumentParser parser("My program");
    args::HelpFlag help(parser, "HELP", "Display this help menu", {'h', "help"});
    
    // 位置参数
    args::ValueFlag<std::string> input(
        parser, "INPUT", "Input file", {"input"}
    );
    
    args::ValueFlag<std::string> output(
        parser, "OUTPUT", "Output file", {"output"}
    );

    try {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help) {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }

    if (input) {
        std::cout << "Input file: " << args::get(input) << std::endl;
    }
    
    if (output) {
        std::cout << "Output file: " << args::get(output) << std::endl;
    }

    return 0;
}

布尔标志

#include <args.hxx>
#include <iostream>

int main(int argc, char** argv) {
    args::ArgumentParser parser("My program");
    args::HelpFlag help(parser, "HELP", "Display this help menu", {'h', "help"});
    
    // 布尔标志
    args::Flag verbose(
        parser, "VERBOSE", "Enable verbose output", {'v', "verbose"}
    );
    
    args::Flag debug(
        parser, "DEBUG", "Enable debug mode", {'d', "debug"}
    );
    
    args::Flag force(
        parser, "FORCE", "Force overwrite", {'f', "force"}
    );

    try {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help) {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }

    std::cout << "Verbose: " << (verbose ? "true" : "false") << std::endl;
    std::cout << "Debug: " << (debug ? "true" : "false") << std::endl;
    std::cout << "Force: " << (force ? "true" : "false") << std::endl;

    return 0;
}

带值的参数

#include <args.hxx>
#include <iostream>

int main(int argc, char** argv) {
    args::ArgumentParser parser("My program");
    args::HelpFlag help(parser, "HELP", "Display this help menu", {'h', "help"});
    
    // 整数参数
    args::ValueFlag<int> port(
        parser, "PORT", "Port number", {'p', "port"}
    );
    
    // 浮点数参数
    args::ValueFlag<double> rate(
        parser, "RATE", "Processing rate", {'r', "rate"}
    );
    
    // 字符串参数
    args::ValueFlag<std::string> host(
        parser, "HOST", "Host address", {'H', "host"}
    );

    try {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help) {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }

    if (port) {
        std::cout << "Port: " << args::get(port) << std::endl;
    }
    
    if (rate) {
        std::cout << "Rate: " << args::get(rate) << std::endl;
    }
    
    if (host) {
        std::cout << "Host: " << args::get(host) << std::endl;
    }

    return 0;
}

多值参数

#include <args.hxx>
#include <iostream>
#include <string>
#include <vector>

int main(int argc, char** argv) {
    args::ArgumentParser parser("My program");
    args::HelpFlag help(parser, "HELP", "Display this help menu", {'h', "help"});
    
    // 多值参数
    args::PositionalList<std::string> files(
        parser, "FILES", "Input files"
    );
    
    // 多值标志参数
    args::ValueFlagList<std::string> include(
        parser, "INCLUDE", "Include paths", {'I', "include"}
    );
    
    args::ValueFlagList<std::string> define(
        parser, "DEFINE", "Macro definitions", {'D', "define"}
    );

    try {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help) {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }

    if (files) {
        std::cout << "Files:" << std::endl;
        for (const auto& file : args::get(files)) {
            std::cout << "  " << file << std::endl;
        }
    }
    
    if (include) {
        std::cout << "Include paths:" << std::endl;
        for (const auto& path : args::get(include)) {
            std::cout << "  " << path << std::endl;
        }
    }
    
    if (define) {
        std::cout << "Definitions:" << std::endl;
        for (const auto& def : args::get(define)) {
            std::cout << "  " << def << std::endl;
        }
    }

    return 0;
}

💼 实际应用示例

完整的命令行工具

#include <args.hxx>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

int main(int argc, char** argv) {
    args::ArgumentParser parser(
        "File Processor - A simple tool for processing files",
        "Example: ./processor -i input.txt -o output.txt -v"
    );
    
    args::HelpFlag help(parser, "HELP", "Display this help menu", {'h', "help"});
    
    args::Group required(parser, "Required arguments:", args::Group::Validators::All);
    
    args::ValueFlag<std::string> input(
        required, "INPUT", "Input file path", {'i', "input"}
    );
    
    args::ValueFlag<std::string> output(
        required, "OUTPUT", "Output file path", {'o', "output"}
    );
    
    args::Group optional(parser, "Optional arguments:");
    
    args::Flag verbose(
        optional, "VERBOSE", "Enable verbose output", {'v', "verbose"}
    );
    
    args::Flag force(
        optional, "FORCE", "Force overwrite output file", {'f', "force"}
    );
    
    args::ValueFlag<int> threads(
        optional, "THREADS", "Number of threads (default: 1)", {'t', "threads"}
    );
    
    args::ValueFlagList<std::string> filters(
        optional, "FILTER", "Filter patterns", {'F', "filter"}
    );

    try {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help) {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }
    catch (args::ValidationError e) {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }

    // 获取参数值
    std::string inputFile = args::get(input);
    std::string outputFile = args::get(output);
    bool verboseMode = verbose;
    bool forceMode = force;
    int threadCount = threads ? args::get(threads) : 1;
    auto filterList = filters ? args::get(filters) : std::vector<std::string>();

    // 显示配置
    std::cout << "=== Configuration ===" << std::endl;
    std::cout << "Input: " << inputFile << std::endl;
    std::cout << "Output: " << outputFile << std::endl;
    std::cout << "Verbose: " << (verboseMode ? "Yes" : "No") << std::endl;
    std::cout << "Force: " << (forceMode ? "Yes" : "No") << std::endl;
    std::cout << "Threads: " << threadCount << std::endl;
    
    if (!filterList.empty()) {
        std::cout << "Filters:" << std::endl;
        for (const auto& filter : filterList) {
            std::cout << "  - " << filter << std::endl;
        }
    }

    // 执行处理逻辑(示例)
    std::ifstream inFile(inputFile);
    std::ofstream outFile(outputFile);
    
    if (inFile.good() && outFile.good()) {
        std::cout << "\nProcessing file..." << std::endl;
        std::string line;
        while (std::getline(inFile, line)) {
            if (verboseMode) {
                std::cout << "Processing: " << line << std::endl;
            }
            outFile << line << std::endl;
        }
        std::cout << "Done!" << std::endl;
    } else {
        std::cerr << "Error opening files!" << std::endl;
        return 1;
    }

    return 0;
}

📋 参数类型速查

类型 说明 示例
args::Flag 布尔标志 -v, --verbose
args::ValueFlag<T> 单值参数 -p 8080
args::ValueFlagList<T> 多值参数 -I path1 -I path2
args::Positional<T> 位置参数(单值) input.txt
args::PositionalList<T> 位置参数(多值) file1 file2 file3
💡 提示: args 使用头文件方式,无需编译库,只需包含 args.hxx 即可使用。支持自动生成帮助信息。
⚠️ 注意:

🔗 参考资料