WebRTC-命令行参数解析

一、 功能介绍

webrtc中命令行参数解析功能由rtc_base/flags.h中的Flag类和FlagList类提供。使用起来比较简单,支持参数中含有空格等。可以看成google开源的gflags的轻量版.
支持的命令行语法为:

The following syntax for flags is accepted (both '-' and '--' are ok):

   --flag        (bool flags only)
   --noflag      (bool flags only)
   --flag=value  (non-bool flags only, no spaces around '=')
   --flag value  (non-bool flags only)

二、使用方法

2.1 引入到工程

引入flags.hflags.cc文件到工程,定义WEBRTC_WIN宏即可。

2.2 定义参数

  • 新建flagsdef.h
#pragma once
#include "rtc_base/flags.h"

DECLARE_bool(help);
DECLARE_string(ip);
DECLARE_int(port);
DECLARE_string(path);
  • 新建flagsdef.cpp
#include "flagsdef.h"

DEFINE_bool(help, false, "Print this message");  // 参数依次是:名称, 默认值, 注释
DEFINE_string(ip, "127.0.0.1", "server ip");
DEFINE_int(port, 1001, "server port");
DEFINE_string(path, "C:\\Program Files (x86)\\ASUS", "Install path");
  • 在程序main函数开始处加入参数解析代码:
rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, false);

然后在需要获取命令行参数的位置引用头文件flagsdef.h,直接使用FLAG_ipFLAG_path获取参数值。

完整的main.cpp代码如下:

#include "flagsdef.h"
#include "Apple.h"

int main(int argc, char**argv)
{
    rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, false);
    if (FLAG_help) {
        rtc::FlagList::Print(NULL, false);
        return 0;
    }

    printf("%s:%d\n", FLAG_ip, FLAG_port);
    printf("%s\n", FLAG_path);

    return 0;
}

命令行参数样例:

test.exe --ip=192.168.1.1 --port=1002 --path="C:\Program Files (x86)\TEST"
test.exe --noip
test.exe --help

另外,针对这样的参数格式:

test.exe --ip=192.168.1.1 www.baidu.com
或者
test.exe www.baidu.com --ip=192.168.1.1

需要解析出www.baidu.com参数,将rtc::FlagList::SetFlagsFromCommandLine第三个参数设为true,然后使用argc, argv来获取。

你可能感兴趣的:(☆,WebRTC,WebRTC从入门到精通)