protobuf_generate_cpp not found

I don’t see a whole lot in the docs about the preqequisites of the above function (?). Using it on 3.24.2 I have no problem but on some build agents I’m using which are on 3.16 it fails with Unknown CMake command "protobuf_generate_cpp". Can anyone tell me what the requirements for this really are please - or perhaps even better update the docs to clarify under which conditions it won’t be found?

On SO I also found this old post which perhaps could use some authoritative advice. The hackish answers there did not really help me.

Edit: I guess this is because of the different modes of find_package but I think it could be better documented that this appears to be only available if using the cmake provided find module.

@eriols - I think I know the the problem you encountered. This problem is related to:

In short, protobuf_generated_cpp() is a legacy command”. Instead, you should use protobuf_generate() command for the modern usage”.

There will be a cache variable defined when calling find_package(Protobuf) with Config Mode, protobuf_MODULE_COMPATIBLE.

  • You can use protobuf_generate_cpp() if it is set to ON.
  • You cannot do so if it is set to OFF or EMPTY.

The following code is my template CMakeLists.txt using Protobuf, which works successfully. You can take a look for reference.

get_filename_component(target_name "${CMAKE_CURRENT_SOURCE_DIR}" NAME)
message("==== TARGET: ${target_name}")
add_executable("${target_name}")

file(GLOB src_files   "*.cpp")
file(GLOB hdr_files   "*.hpp" "*.h")
file(GLOB proto_files "*.proto")

set(CMAKE_INCLUDE_CURRENT_DIR ON)
if(protobuf_MODULE_COMPATIBLE)
    # Legacy Support
    protobuf_generate_cpp(proto_srcs proto_hdrs "${proto_files}")
    list(APPEND src_files "${proto_srcs}")
    list(APPEND hdr_files "${proto_hdrs}")
endif()

target_sources("${target_name}"
    PRIVATE 
        "${src_files}"
        "${hdr_files}"
        "${proto_files}")

target_link_libraries("${target_name}"
    PRIVATE
        protobuf::libprotobuf
        protobuf::libprotoc)

if(NOT protobuf_MODULE_COMPATIBLE)
    # Modern Usage
    protobuf_generate(TARGET "${target_name}")
endif()