从源码 构建 Protocol buffer(一)

参考:https://developers.google.cn/protocol-buffers/docs/cpptutorial

  1. 编译 protobuf 源码
$ cd protobuf-3.20.1/cmake
$ cmake -B build -G "Ninja"
$ cmake --build build
$ ls ~/protobuf-3.20.1/cmake/build/
build.ninja          CTestTestfile.cmake  libprotobuf.a       lite-test         protoc-3.20.1.0
CMakeCache.txt       lib                  libprotobuf-lite.a  protobuf-lite.pc  test_plugin
CMakeFiles           libgmock.a           libprotoc.a         protobuf.pc       tests
cmake_install.cmake  libgmock_main.a      lite-arena-test     protoc
  1. 编译 protobuf_test

protobuf_test 的目录结构

protobuf_test
├── CMakeLists.txt
├── README.md
├── run.sh
└── src
    └── protobuf_test
        ├── addressbook.pb.cc
        ├── addressbook.proto
        ├── CMakeLists.txt
        ├── include
        │   └── addressbook.pb.h
        └── main.cpp
# 1.configure cmake
# cmake -S . -B build -G "Ninja"
$ cmake -S . -B build

# 2.build
$ cmake --build build
  1. 运行
$ sh run.sh
Test protocol buffer.

根目录 CMakeLists.txt

cmake_minimum_required(VERSION 3.12...3.23 FATAL_ERROR)

project(protobuf_test
  VERSION 1.0.1
  LANGUAGES CXX
  )

add_subdirectory(src/protobuf_test)

run.sh

./build/src/protobuf_test/main

src/propobuf/main.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;


int main() {
  GOOGLE_PROTOBUF_VERIFY_VERSION;
  tutorial::AddressBook address_book;
  std::cout << "Test protocol buffer." << std::endl;
  google::protobuf::ShutdownProtobufLibrary();
  return 0;
}

src/protobuf/CMakeLists.txt

cmake_minimum_required(VERSION 3.12...3.23 FATAL_ERROR)

set(LINK_DIR "~/protobuf-3.20.1/cmake/build/")
set(INCLUDE_DIR "~/protobuf-3.20.1/src" "include")
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} "~/protobuf-3.20.1/cmake/build")
find_package(protobuf 3.20.1 CONFIG REQUIRED)
if (protobuf_FOUND)
  message(STATUS "FOUND ${protobuf_DIR}")
endif()

add_executable(main)
target_sources(main PRIVATE main.cpp addressbook.pb.cc)
set_target_properties(main PROPERTIES CXX_STANDARD_REQUIRED ON)
set_target_properties(main PROPERTIES CXX_EXTENSIONS OFF)
target_compile_features(main PUBLIC cxx_std_11)

target_link_directories(main PUBLIC ${LINK_DIR})
target_include_directories(main PUBLIC ${INCLUDE_DIR})
target_link_libraries(main PUBLIC protobuf)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值