参考:https://developers.google.cn/protocol-buffers/docs/cpptutorial
- 编译 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
- 编译 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
- 运行
$ 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)