目录

mini-args

一个极简的 C++17 命令行参数解析头文件库(single-header,无依赖)。

特性

  • 仅一个头文件 args.hpp,直接 #include 即可
  • 支持 --key=value、--key value、-k value、-k=value、裸标志 --flag
  • 模板接口支持 int、double、std::string 等类型的自动转换(基于 std::from_chars)
  • 可选值返回 std::optional,支持设置默认值
  • 自动收集位置参数,-- 之后全部视为位置参数
  • 注意:选项后紧跟的不以 - 开头的参数会被当作该选项的值,建议布尔标志放最后、使用 = 形式,或用 -- 分隔位置参数

使用

#include "args.hpp"

int main(int argc, char* argv[]) {
    minargs::Args args(argc, argv);

    int port = args.get<int>("port", 8080);          // --port 9090
    std::string host = args.get<std::string>("host", "127.0.0.1");
    bool debug = args.has("debug");                  // --debug
    auto input = args.get<std::string>("input");     // std::optional
    auto files = args.positional();                  // 位置参数列表

    return 0;
}

完整示例见 example.cpp:

g++ -std=c++17 -Wall example.cpp -o example
./example input.dat --port 9090 --debug

License

Copyright 2026 程哲熙 24377148

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

关于

一个极简的 C++17 命令行参数解析头文件库(single-header,无第三方依赖)。支持 --key=value、--key value、裸标志、位置参数和 -- 分隔符,模板接口提供类型安全的取值与默认值。采用 Apache License 2.0 开源。

37.0 KB
邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9 京公网安备 11010802047560号