003-CLI11-命令行接口库

CLI:Command Line Interface

一、基础

目的:为程序添加命令行支持

要求:main函数的参数必须是齐全的,即:

int main(int argc, char** argv)
{
//...
}

基础使用

    //一、定义一个CLI::App变量,字符串为描述
    CLI::App app { "File watcher" };
    //二、定义需要从命令行参数读入的变量
    std::vector<std::string> paths;
    //三、添加参数项,第一个字符串为参数描述,第二个字符串为描述性文字
    app.add_option("paths", paths, "Paths to watch");
    //四、开始解析命令行
    app.parse(argc, argv);

二、用法详解

1.案例与异常

1.1 CLI::ConstructionError

时机:app.parse()之前的操作(add_option()之类)抛出异常

原因:构建错误——不合理的参数设计(通常是代码写得有问题)

示例:重复添加

#include <iostream>

#include <CLI/CLI.hpp>

int main(int argc, char** argv)
{
    std::system("chcp 65001 > nul");

    CLI::App app { "This is a CLI app" };
    std::vector<std::string> paths;

    try {
        // 重复添加
        app.add_option("paths", paths, "Paths to files");
        app.add_option("paths", paths, "Paths to files");
    } catch (CLI::ConstructionError const& e) {
        // CLI自带的异常处理
        return app.exit(e);
    }
    app.parse(argc, argv);
    for (auto const& path : paths) {
        std::cout << "Path: " << path << std::endl;
    }

    std::system("pause");
}

运行结果:

 WDJ@NicoLula build .\cli11.exe d:\\temp c: e:\\watch
added option matched existing option name: paths is already added
Run with --help for more information.

可以看到,app.exit(e)不仅打印了异常原因,还提示使用 --help命令获取帮助。

1.2 CLI::ParseError

时机:app.parse()抛出的异常

原因:解析错误——不合理的参数供应

try {
    app.parse(argc, argv);
} catch (CLI::ParseError const& e) {
    // CLI自带的异常处理
    return app.exit(e);
}

上述代码常用,因此有一个宏可以替代:

CLI11_PARSE(app, argc, argv);

2.匿名参数、具名参数

1748850723207

添加方式:

    int maxCount = 0;
    app.add_option("--max-count", maxCount, "Max count of paths"); // 长名
    // app.add_option("-m", maxCount, "Max count of paths"); //短名
    // app.add_option("-m,--max-count", maxCount, "Max count of paths"); //长短都要

3.选项(option)与标志(flag)

1748851155506

添加方式:

bool createdOnly = false;
app.add_flag("-c,--created-only", createdOnly, "Only show created files");

4.必须(required)与非必选

1748851516171

1748851542774