Search code examples
c++qtprotocol-buffersqmake

How to add a proto file to a Qt project


I want to add this file, tutorial.proto, to my qmake Qt project, which I copied from a tutorial:

syntax="proto3";

package qtprotobuf.tutorial;

message EchoRequest {
  string message = 1;
}

message EchoResponse {
  string message = 1;
}

service EchoService {
  rpc Echo(EchoRequest) returns (EchoResponse);
}

I tried to connect the ProtoBuff library itself and everything seemed to work, at least the project is coming together.

My pro file:

QT = websockets

TARGET = server
CONFIG   += console
CONFIG   -= app_bundle
CONFIG += c++17 cmdline

TEMPLATE = app

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
        main.cpp \
        server.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

HEADERS += \
    server.h

target.path = $$[QT_INSTALL_EXAMPLES]/websockets/echoserver
INSTALLS += target

LIBS += -lprotobuf

DISTFILES += \
    tutorial.prot

Solution

  • QT += network
    
    TARGET = server
    CONFIG += console
    CONFIG -= app_bundle
    
    TEMPLATE = app
    
    # Path to your .proto file
    PROTO_FILE = tutorial.proto
    
    # Path to generated C++ files
    PROTO_OUT_DIR = $$OUT_PWD/protobuf_generated
    # Create the output directory if it doesn't exist
    !exists($$PROTO_OUT_DIR) {
        system(mkdir $$PROTO_OUT_DIR)
    }
    
    # Command to generate C++ files from .proto file
    PROTOC = protoc
    PROTO_SRC = $$PWD/$$PROTO_FILE
    PROTO_INC = -I$$PWD
    PROTO_FLAGS = --cpp_out=$$PROTO_OUT_DIR $$PROTO_SRC
    
    # Run the protoc command
    system($$PROTOC $$PROTO_INC $$PROTO_FLAGS)
    
    # Add generated files to your project
    PROTO_GEN_FILES = $$files($$PROTO_OUT_DIR/*.pb.cc)
    PROTO_GEN_HEADERS = $$files($$PROTO_OUT_DIR/*.pb.h)
    SOURCES += $$PROTO_GEN_FILES
    HEADERS += $$PROTO_GEN_HEADERS
    
    # Include generated files in the include path
    INCLUDEPATH += $$PROTO_OUT_DIR
    
    # Add protobuf library
    LIBS += -lprotobuf
    

    This .pro file will:

    • Define variables for the .proto file, output directory, protoc command, and include paths.
    • Generate the C++ files from the .proto file using the protoc compiler.
    • Add the generated .pb.cc and .pb.h files to your project's source and header files.
    • Include the output directory in the include path.
    • Link against the ProtoBuf library.