Gflags learning notes

  • 简介

        gflags是谷歌开发的一个命令行标记库,区别于其他命令行标记库,它允许标记定义出现在源文件各处,而不是限定在一个源文件(如main())中。这意味着一个源代码文件定义和使用对该文件有意义的标志,任何链接该文件的应用程序都将获得标志,gflags库将自动处理这些标志。借助于gflags,程序在灵活性和代码重用方面有了显著的提高。

        但是,在程序中使用gflags时存在这样的危险:两个文件定义了相同的标志,在它们链接在一起时编译器会给出错误。

  • 编译(Test with Ubuntu & CMake, same below)

        PS:可以参考官方提供的INSTALL.md

       在选定的目录下,执行以下命令:

git clone https://github.com/gflags/gflags.git
cd gflags && mkdir build && cd build
cmake -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DINSTALL_HEADERS=ON -DINSTALL_SHARED_LIBS=ON -DINSTALL_STATIC_LIBS=ON ..
make -j4
sudo make install

         编译安装后,继续执行以下命令:

ldconfig
ls /usr/local/lib/libgflags* -l

        出现以下输出结果,则证明编译安装完成 

Gflags learning notes_第1张图片

  • 测试

        在选定目录下执行以下命令:

mkdir gflags_test && cd gflags_test && mkdir build
touch gflags_test.cpp CMakeLists.txt

         使用编辑器编辑以下内容到gflags_test.cpp & CMakeLists.txt:

//gflags_test.cpp

#include 
#include 

DEFINE_bool(flag, true, "This is a flag");
DEFINE_string(name, "shaw", "This is a name");

int main(int argc, char **argv)
{
    gflags::ParseCommandLineFlags(&argc, &argv, false);
    if(FLAGS_flag)
    {
        std::cout<< "Hello, " << FLAGS_name << ", nice to meet you!" << std::endl;
    }
    return 0;
}
# CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project(gflags_test VERSION 1.0)

find_package(gflags REQUIRED)

add_executable(gflags_test gflags_test.cpp)
target_link_libraries(gflags_test  gflags)

        在上述选定目录下,执行以下命令:

cd build && cmake .. && make
./gflags_test --flag --name="Jay Zhou"

        得到以下输出:

你可能感兴趣的:(Learning,Notes,c++)