1

I tries to use FOREACH to generated several pb files. And make two list names PROTO_SRCS & PROTO_HDRS like below. I can use it in the main CMakeLists. Like add_executable(a SHARED ${PROTO_SRCS} main.cpp). But I can not use this param in subdirectories to make a library. when I type "cmake .." in main CMakelists build dir. It shown that "Cannot find source file: a.pb.cc".

main CMakeLists.txt

add_library(xxx SHARED ${PROTO_SRCS}) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/back back)

in src/back CMakeLists.txt

add_executable(yyy ${PROTO_SRCS})

and I can use message to show ${PROTO_SRCS} in subdir so it pass into successfully.

Please help me to point out the problem. Thx a lot

1
  • 2
    Welcome to stackoverflow, advise you to read stackoverflow.com/help/how-to-ask first, and edit your description to clarify the question. Commented Feb 25, 2021 at 11:58

1 Answer 1

1

The issue is that in CMake versions older than 3.20 the GENERATED property of source files is only visible in the directory where it is set. Thus, when you add the protobuf-generated source files to a target defined in a different directory, CMake will no longer know that these are files generated during the build. Consequently, CMake will try to locate these files at configuration time, when they obviously do not exist yet.

Unfortunately, at the time of writing there is only a release candidate for CMake 3.20 and no official release yet. So depending on whether you need to coordinate with other coworkers or whether you're working on this project on your own it might not be feasible to use the release candidate.

If you can't use it, the alternative is to create an object library via add_library(protobuf_objs OBJECT ${PROTO_SRCS}) in the directory where you generate the files and to use target_sources(xxx PRIVATE $<TARGET_OBJECTS:protobuf_objs>) and target_sources(yyy PRIVATE $<TARGET_OBJECTS:protobuf_objs>) instead of adding the ${PROTO_SRCS} as source files to these targets directly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank u so much. I use your method to add an OBJECT library, and it works. Smart way!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.