gflags是google的一个开源的处理命令行参数的库,使用c++开发

#include <iostream>
#include <string>

#include <gflags/gflags.h>

DEFINE_bool(a_bool_flag, true, "A Bool Flag");
DEFINE_string(ipaddr, "127.0.0.1", "IPAddress String");
DEFINE_int32(portno, 4000, "Port NO.");

static bool ipaddr_validator(
        const char* flagname,
        const std::string& ipaddr) {
    if (ipaddr.size() >= 7 && ipaddr.size() <= 15) {
        return true;
    }

    std::cerr << flagname << std::endl;
    std::cerr << "Invalid IP address: " << ipaddr << std::endl;

    return false;
}

static bool port_validator(
        const char* flagname,
        google::int32 portno) {
    if (portno > 0 && portno < 65536) {
        return true;
    }

    std::cerr << flagname << std::endl;
    std::cerr << "Invalid port: " << portno << std::endl;

    return false;
}

void func_use_flags() {
    std::cout << FLAGS_a_bool_flag << std::endl;
    std::cout << FLAGS_ipaddr << std::endl;
    std::cout << FLAGS_portno << std::endl;
}

int main(int argc, char* argv[]) {
    std::cout << google::RegisterFlagValidator(&FLAGS_ipaddr, &ipaddr_validator) << std::endl;;
    std::cout << google::RegisterFlagValidator(&FLAGS_portno, &port_validator) << std::endl;
    std::cout << "before ParseCommandLineFlags. argc : " << argc << std::endl;
    for (int i = 0; i < argc; ++i) {
        std::cout << "argv[" << i << "] : " << argv[i] << std::endl;
    }
    int r = google::ParseCommandLineFlags(&argc, &argv, false);
    std::cout << r << std::endl;
    std::cout << "after ParseCommandLineFlags. argc : " << argc << std::endl;
    for (int i = 0; i < argc; ++i) {
        std::cout << "argv[" << i << "] : " << argv[i] << std::endl;
    }

    func_use_flags();

    return 0;
}
本文链接地址:https://const.net.cn/557.html

标签: gflags

添加新评论