Search code examples
c++includeprotocol-buffersbazel

What is the correct way to include a proto file in C++?


I'm trying to learn C++ but I'm failing at some basic steps, like this one. I have a .proto file that needs to be included from a .cc file.

I added the line:

#include "path/to/my/protofile.pb.h"

I edited the matching BUILD file, by adding:

proto_library(
    name = "protofile_proto",
    srcs = ["//path/to/my:protofile.proto"],
    visibility = [
        "//visibility:public",
    ],
)

When I try to compile it, I get the following error:

path/to/my/ccfile.cc
fatal error: 'path/to/my/protofile.pb.h' file not found

Any idea on how to get the compiler to find the proto file at build time? Thanks in advance.


Solution

  • When you use double-quotes " in #include, the path is relative from the source file itself. And if it's not found then the compiler will search through its list of standard (and non-standard) directories to find the header file.

    So there are two alternative solutions for you:

    1. Make sure to give the correct relative path from the source file; Or
    2. Add a suitable directory to the compilers list, usually using an -I (upper-case i) option (note that for this you might as well use <> instead of double-quotes)

    Depending on build-system you need to add path/to/my/protofile.pb.h as a dependency for the source file, to make sure it's generated before the source file itself will be passed to the compiler.