protobuf插件
在使用protobuf这个序列化库的时候,我们通常需要手动调用protoc.exe
这个可执行程序对我们定义的.proto
文件进行编译,从而生成对应的.cc
和.h
文件,但是这有点麻烦,所以CMake提供了一个API便于我们编译.proto
文件
1.编译原生proto文件
1 2 3 4 5 6 7 8 9 10 11 12
| find_package(Protobuf REQUIRED)
include_directories(${Protobuf_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})
set(PROTO_FILE helloworld.proto) protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS ${PROTO_FILE} LANGUAGE cpp)
add_executable(greeter_server greeter_server.cpp ${PROTO_FILE})
target_link_libraries(greeter_server protobuf::libprotobuf)
|
2.编译包含gPRC的proto文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| find_package(gRPC REQUIRED) find_package(Protobuf REQUIRED)
include_directories(${Protobuf_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR})
set(PROTO_FILE helloworld.proto)
protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS ${PROTO_FILE} LANGUAGE cpp) get_target_property(grpc_cpp_plugin_location gRPC::grpc_cpp_plugin LOCATION) protobuf_generate_cpp(GRPC_SRCS GRPC_HDRS ${PROTO_FILE} LANGUAGE grpc GENERATE_EXTENSIONS .grpc.pb.h .grpc.pb.cc PLUGIN "protoc-gen-grpc=${grpc_cpp_plugin_location}")
add_executable(greeter_server greeter_server.cpp ${PROTO_SRCS} ${GRPC_SRCS}) target_link_libraries(greeter_server gRPC::grpc++ protobuf::libprotobuf)
|
关键API:protobuf_generate_cpp
,如果使用正确,在编译的时候就会在./build
目录下生成对应的文件了