ProtoBuf练习

环境设置

项目地址

https://github.com/silvermagic/ProtoBufDev.git

操作系统

64位 Fedora 24

安装protobuf

$ git clone https://github.com/google/protobuf.git
$ cd protobuf/
$ ./autogen.sh
$ ./configure
$ make -j8
$ sudo make install
### 设置pkg-config查找路径
$ tail -n 8 .bash_profile

PKG_CONFIG_PATH=/usr/local/lib/pkgconfig

export PKG_CONFIG_PATH

LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH

export LD_LIBRARY_PATH
$ source ~/.bash_profile

工程目录结构(模板)

$ ls
build  CMakeLists.txt  proto  reader.cpp  README.txt  writer.cpp
$ cat CMakeLists.txt
#cmake的最低版本
cmake_minimum_required(VERSION 2.8)

#工程名
project(protobuf)

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

#遍历当前目录及子目录获取所有源文件
file(GLOB SRC "${CMAKE_CURRENT_SOURCE_DIR}/*.cc")
file(GLOB WSRC "${CMAKE_CURRENT_SOURCE_DIR}/writer.cpp")
file(GLOB RSRC "${CMAKE_CURRENT_SOURCE_DIR}/reader.cpp")

#设置源文件列表
add_executable(writer ${WSRC} ${SRC})
add_executable(reader ${RSRC} ${SRC})

#dependencies
INCLUDE(FindPkgConfig)
#使用pkg-config寻找protobuf库的include目录以及库
pkg_check_modules(PROTOBUF REQUIRED protobuf)
include_directories(${PROTOBUF_INCLUDE_DIRS})
link_directories(${PROTOBUF_LIBRARY_DIRS})
#设置链接库
target_link_libraries(writer ${PROTOBUF_LIBRARIES})
target_link_libraries(reader ${PROTOBUF_LIBRARIES})

#新增自定义命令pb和cls
add_custom_target(pb
    COMMAND protoc -I=${CMAKE_CURRENT_SOURCE_DIR}/proto --cpp_out=${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/proto/*.proto
)
add_custom_target(cls
    COMMAND rm -rf ${CMAKE_CURRENT_SOURCE_DIR}/*.pb.*
)

编译运行项目(模板)

$ mkdir build
$ cd build
$ cmake ..
$ make clean
$ make cls
$ make pb
$ make
$ ./writer
$ ./reader

规范

proto文件名使用小写字母加下划线的组合方式

posted @ 2018-05-25 11:20  银魔术师  阅读(762)  评论(0编辑  收藏  举报