Protobuf安装|编译|使用

1.linux安装Protobuf

Linux编译安装protocal-3.6.1
https://github.com/protocolbuffers/protobuf/releases/tag/v3.6.1

tar zvxf protobuf-all-3.6.1.tar.gz
cd protobuf-3.6.1
 
./configure --prefix=/usr/local/
 
sudo make  #要编译很久
sudo make check
sudo make install

2.linux使用Protobuf

(1)编写test.proto

syntax = "proto2";
package test;

message something
  {
    optional int32 num = 1;
    repeated string strs = 2;
  }

(2)编写main函数使用.proto中定义的message

test.cc

#include "test.pb.h"

int main()
  {
    test::something msg;
    msg.set_num(42);
    msg.add_strs("hello");
    msg.add_strs("world");

    msg.PrintDebugString();
  }

(3)使用protoc编译.proto

protoc test.proto --cpp_out=.
此时当前目录将生成两个文件test.pb.cc test.pb.h

(4)编译

g++ -O0 -g3 -pthread test.cc test.pb.cc -I /usr/local/include/google/protobuf/ -L /usr/local/lib/libprotobuf.so.17 -lprotobuf -std=c++11

-I:指定protobuf的头文件
-L: 指定protobuf的库文件
*可能会遇到以下报错
/usr/bin/ld: cannot find -lprotobuff
collect2: error: ld returned 1 exit status
这是因为gcc 编译器找不到protobuf.so库文件,因为在usr/local/lib下的protobuf.so不能被gcc找到。解决方法有两种:
a. export LD_LIBRARY_PATH=/usr/local/lib (这种方法临时生效,重启就不生效了)
b. 在/etc/ld.so.conf 文件里面添加路径 /usr/local/lib ,因为linux系统运行库会读取这里的目录寻找so,之后ldconfig
这一步结束编译出可执行文件a.out

[root@node2 demo01]# ./a.out
num: 42
strs: "hello"
strs: "world"

3.linux通过CMAKE使用Protobuf

(1)编写CMakeLists.txt文件

# 1.指定cmake最小版本
cmake_minimum_required(VERSION 3.5)

# 2.定义project名称为demo02
project(demo02)

# 3.指定支持c++11,相当于gcc编译时加的参数-std=c++11
set(CMAKE_CXX_FLAGS "-std=c++11")

# 4. 找到Protobuf的编译器protoc和库,REQUIRED表示找不到的话就停止编译
# find the protobuf compiler and libraries
find_package(Protobuf REQUIRED)

# 5. 根据.proto文件生成对应的头文件.pb.h和源文件.pb.cc
# Generate the .h and .cxx files
# SRCS = Variable to define with autogenerated source files
# HDRS = Variable to define with autogenerated header files
PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS test.proto)

message ("PROTO_SRCS = ${PROTO_SRCS}")
message ("PROTO_HDRS = ${PROTO_HDRS}")

# 6. 根据test.cpp和上一步生成的.pb.h和.pb.cc文件生成可执行文件,名为demo02
# Add an executable
add_executable(demo02 test.cpp ${PROTO_SRCS} ${PROTO_HDRS})

# 7. 指定目标demo02包含的头文件路径 (-I xxxx)
# PROTOBUF_INCLUDE_DIRS - Include directories for Google Protocol Buffers
# CMAKE_CURRENT_BINARY_DIR - The path to the binary directory currently being processed.
target_include_directories(demo02 PUBLIC ${PROTOBUF_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})

# 8. 指定目标链接的库 (-lprotobuf)
# link the exe against the libraries
# PROTOBUF_LIBRARIES - The protobuf libraries
target_link_libraries(demo02 PUBLIC ${PROTOBUF_LIBRARIES})

(2)编写test.proto(见2.(1))

(3)编写main函数使用.proto中定义的message-test.cc(见2.(2))

(4)创建build目录并编译

mkdir build
cd build
cmake ..
make
./demo02

参考

https://github.com/ttroy50/cmake-examples

你可能感兴趣的:(Protobuf安装|编译|使用)