システム:ubuntu 18.04
このブログで使用されているサンプルプログラムprotobuf.tar.xzをダウンロードするにはクリックしてください
protobuf.tar.xzファイルの解凍後のディレクトリツリーは次のとおりです。必要に応じてダウンロードしてください。
1つ、protobufのインストール
sudo apt-get install autoconf automake libtool curl make g++ unzip git
git clone https://github.com/protocolbuffers/protobuf.git
cd protobuf
git submodule update --init --recursive
./autogen.sh
./configure
make
sudo make install
sudo ldconfig
protoc --version
最後に次のようなメッセージが出力されれば、protobufのインストールは成功です。
次に、コマンドラインでprotobufを使用します
2.1プロトファイルを作成する
mkdir -p CSDN_ws/protobuf/teminal/
cd CSDN_ws/protobuf/teminal/
gedit AddressBook.proto
次のテキストをAddressBook.protoにコピーして保存します。
package tutorial;
message Person {
required string name=1;
required int32 id=2;
optional string email=3;
enum PhoneType {
MOBILE=0;
HOME=1;
WORK=2;
}
message PhoneNumber {
required string number=1;
optional PhoneType type=2 [default=HOME];
}
repeated PhoneNumber phone=4;
}
message AddressBook {
repeated Person person=1;
}
2.2 c ++ヘッダーファイルを生成する
protoc --cpp_out=./ AddressBook.proto
ls
このとき、ディレクトリにはさらに2つのファイルがあります:AddressBook.pb.cc
とAddressBook.pb.h
。
2.3protobufヘッダーファイルを使用する
gedit main.cpp
次のテキストをmain.cppにコピーして保存します。
#include <iostream>
#include <fstream>
#include <vector>
#include "AddressBook.pb.h"
using namespace std;
// This function fills in a Person message based on user input.
void PromptForAddress(tutorial::Person* person)
{
cout << "Enter person ID number: ";
int id;
cin >> id;
person->set_id(id);
cin.ignore(256, '\n');
cout << "Enter name: ";
getline(cin, *person->mutable_name());
cout << "Enter email address (blank for none): ";
string email;
getline(cin, email);
if (!email.empty())
{
person->set_email(email);
}
while (true)
{
cout << "Enter a phone number (or leave blank to finish): ";
string number;
getline(cin, number);
if (number.empty())
{
break;
}
tutorial::Person::PhoneNumber* phone_number = person->add_phone();
phone_number->set_number(number);
cout << "Is this a mobile, home, or work phone? ";
string type;
getline(cin, type);
if (type == "mobile")
{
phone_number->set_type(tutorial::Person::MOBILE);
}
else if (type == "home")
{
phone_number->set_type(tutorial::Person::HOME);
}
else if (type == "work")
{
phone_number->set_type(tutorial::Person::WORK);
}
else
{
cout << "Unknown phone type. Using default." << endl;
}
}
}
int main(int argc, char *argv[])
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
if (argc != 2)
{
cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
return -1;
}
tutorial::AddressBook address_book;
{
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!input) {
cout << argv[1] << ": File not found. Creating a new file." << endl;
} else if (!address_book.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
}
// Add an address.
PromptForAddress(address_book.add_person());
{
// Write the new address book back to disk.
fstream output(argv[1], ios::out | ios::trunc | ios::binary);
if (!address_book.SerializeToOstream(&output)) {
cerr << "Failed to write address book." << endl;
return -1;
}
}
// Optional: Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
次に、次のコマンドを実行して、コマンドラインでコンパイルします。
g++ AddressBook.pb.cc main.cpp -o main `pkg-config --cflags --libs protobuf`
ls
コンパイルが成功すると、mainという名前の追加ファイルが作成されます。mainを
実行すると、次の情報を入力できます。
./main name.txt
上記は、teminalでprotobufを使用するすべてのプロセスです。終了後、ワークスペースは次のようになります。
3、cmakeの下でprotobufを使用します
3.1cmakeをインストールする
sudo apt-get install cmake cmake-qt-qui
3.2CMakeListsファイルの書き込み
mkdir -p CSDN_ws/protobuf/cmake/
cp CSDN_ws/protobuf/teminal/AddressBook.proto CSDN_ws/protobuf/cmake/AddressBook.proto
cp CSDN_ws/protobuf/teminal/main.cpp CSDN_ws/protobuf/cmake/main.cpp
cd CSDN_ws/protobuf/cmake/
gedit CMakeLists.txt
次のコンテンツをCMakeLists.txtファイルにコピーします。
cmake_minimum_required(VERSION 3.10)
PROJECT (cppTest)
SET(SRC_LIST main.cpp)
# Find required protobuf package
find_package(Protobuf REQUIRED)
if(PROTOBUF_FOUND)
message(STATUS "protobuf library found")
else()
message(FATAL_ERROR "protobuf library is needed but cant be found")
endif()
include_directories(${PROTOBUF_INCLUDE_DIRS})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})
PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS AddressBook.proto)
ADD_EXECUTABLE(cppTest ${SRC_LIST} ${PROTO_SRCS} ${PROTO_HDRS})
target_link_libraries(cppTest ${PROTOBUF_LIBRARIES})
3.3cmakeのコンパイルと実行
cd CSDN_ws/protobuf/cmake/
cmake .
make
./cppTest name.txt
操作の結果は端末の結果と同じです。最終的なファイルディレクトリは次のとおりです。
4、VSコードでprotobufを使用する
4.1VSコードをインストールする
ubuntu 18.04 ubuntuソフトウェアを入力し、ビジュアルスタジオコードを入力し、インストールします。
VS Codeの独自のストアにアクセスして、プラグインのショートカットキー:Ctrl + Shift + xをダウンロードし、c / c ++、c / c ++ clangコマンドアダプター、c ++インテリセンス、CMake、CMakeツールなどのさまざまな依存関係パッケージをダウンロードします。下の図:
4.2コンパイルして実行する
vscodeフォルダーを作成し、vsコードを開きます。
mkdir CSDN_ws/protobuf/vscode/
cp CSDN_ws/protobuf/cmake/AddressBook.proto CSDN_ws/protobuf/vscode/AddressBook.proto
cp CSDN_ws/protobuf/cmake/main.cpp CSDN_ws/protobuf/vscode/main.cpp
cp CSDN_ws/protobuf/cmake/CMakeLists.txt CSDN_ws/protobuf/vscode/CMakeLists.txt
cd CSDN_ws/protobuf/vscode/
code .
左側の[デバッグ]ボタンをクリックし、[構成の追加]を選択してから、[C ++(GDB / LLDB)]を選択すると、launch.jsonファイルが次のように自動的に生成されます。
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "g++ - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/cppTest",
"args": ["name.txt"],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++ build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
vs codeインターフェースでF5をクリックすると、task.jsonファイルを構成するように求められます。次のテキストをデフォルトのtask.jsonファイルにコピーします。
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "protobuf build",
"command": "cmake . && make",
"group": "build"
}
]
}
main.cppインターフェイスに戻り、F5をクリックすると、コンパイルメッセージが表示され、最終結果は実行結果になります。
最終的なファイルディレクトリは次のとおりです。
この滑らかさを見逃すと、次の不調和な波線が見つかる可能性があります。
写真の小さな黄色い電球をクリックすると、いくつかの小さなヒントがあります(この電球はコンパイルに影響しませんが、ヘッダーファイルはVSコードによって認識されず、自動的に完了できません)、クリックAdd to "includePath":${workspaceFolder}
すると、その1つが見つかりますもっと生まれるc_cpp_properties.json
:
{
"configurations": [
{
"name": "Linux",
"includePath": [
"${workspaceFolder}/**",
"${workspaceFolder}"
],
"defines": [],
"compilerPath": "/usr/bin/clang",
"cStandard": "c11",
"cppStandard": "c++14",
"intelliSenseMode": "clang-x64"
}
],
"version": 4
}
最後に、VScodeファイルディレクトリは次のとおりです。
五、bazel
5.1ベーゼルを取り付ける
sudo apt install curl gnupg
curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add -
echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list
sudo apt update && sudo apt install bazel
Bazelを使用して開始できます。C++プロジェクトをコンパイルして、それに慣れてください。
5.2プロジェクトをビルドする
この部分では、Bazelの使用について説明します:コンパイルprotobuf。
mkdir -p CSDN_ws/protobuf/bazel/
cp CSDN_ws/protobuf/teminal/AddressBook.proto CSDN_ws/protobuf/bazel/AddressBook.proto
cp CSDN_ws/protobuf/teminal/main.cpp CSDN_ws/protobuf/bazel/main.cpp
cd CSDN_ws/protobuf/bazel/
gedit WORKSPACE
WORKSPACEファイルに次のように入力します。
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# rules_cc defines rules for generating C++ code from Protocol Buffers.
http_archive(
name = "rules_cc",
sha256 = "35f2fb4ea0b3e61ad64a369de284e4fbbdcdba71836a5555abb5e194cf119509",
strip_prefix = "rules_cc-624b5d59dfb45672d4239422fa1e3de1822ee110",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_cc/archive/624b5d59dfb45672d4239422fa1e3de1822ee110.tar.gz",
"https://github.com/bazelbuild/rules_cc/archive/624b5d59dfb45672d4239422fa1e3de1822ee110.tar.gz",
],
)
# rules_proto defines abstract rules for building Protocol Buffers.
http_archive(
name = "rules_proto",
sha256 = "2490dca4f249b8a9a3ab07bd1ba6eca085aaf8e45a734af92aad0c42d9dc7aaf",
strip_prefix = "rules_proto-218ffa7dfa5408492dc86c01ee637614f8695c45",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_proto/archive/218ffa7dfa5408492dc86c01ee637614f8695c45.tar.gz",
"https://github.com/bazelbuild/rules_proto/archive/218ffa7dfa5408492dc86c01ee637614f8695c45.tar.gz",
],
)
load("@rules_cc//cc:repositories.bzl", "rules_cc_dependencies")
rules_cc_dependencies()
load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains")
rules_proto_dependencies()
rules_proto_toolchains()
5.3ビルドの作成
gedit BUILD
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")
cc_proto_library(
name = "AddressBook_proto",
deps = [":AddressBook_proto_lib"],
)
proto_library(
name = "AddressBook_proto_lib",
srcs = ["AddressBook.proto"],
)
cc_binary(
name = "main",
srcs = ["main.cpp"],
deps = ["AddressBook_proto"],
)
5.4プロジェクトをコンパイルして実行する
次のコマンドを実行して、プロジェクトをコンパイルします
sudo bazel build :main
次の出力情報を取得します。
次のコマンドを実行してプロジェクトを実行します
./bazel-bin/main name.txt
次の結果を取得します。
END
windSeSによって
2020年8月12日