【问题标题】:Protobufs build but are not being linked to main program using CMakeProtobufs 构建但未使用 CMake 链接到主程序
【发布时间】:2018-10-20 22:48:36
【问题描述】:

我正在尝试构建和执行一个使用 protobufs 的程序。我正在用 CMake3 构建这个项目。问题是当我制作项目时出现此错误

fatal error: 
      'google/protobuf/stubs/common.h' file not found
#include <google/protobuf/stubs/common.h>
         ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

我将发布我的这个项目的目录结构

directory structure image

directory structure expanded

这是我的 CMakeLists.txt 文件

TestCode/下的顶层

cmake_minimum_required(VERSION 3.5)
set (CMAKE_CXX_STANDARD 11)

add_subdirectory(protobufs)
add_subdirectory(main)

main/下的CMakeList.txt

cmake_minimum_required(VERSION 3.5)

set (CMAKE_CXX_STANDARD 11)

add_executable(test_exe 
    main.cc 
)
target_link_libraries(protos ${PROTOBUF_LIBRARIES})

protobufs/下的CMakeLists/

cmake_minimum_required(VERSION 3.5)

set (CMAKE_CXX_STANDARD 11)

find_package(Protobuf REQUIRED)

PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS 
    dog.proto
)
add_library(protos ${PROTO_SRCS})

target_link_libraries(protos 
    PUBLIC
    ${PROTOBUF_LIBRARIES}
)

target_include_directories(protos
    PUBLIC
    ${PROTOBUF_INCLUDE_DIRS}
    ${CMAKE_CURRENT_BINARY_DIR}
)

这就是我构建项目的方式

cd build
cmake ..
make -j8

我不明白为什么没有为主程序找到 protobuf。如果我只是尝试使用 make 来构建 protobuf,它们会成功构建。任何想法将不胜感激。

编辑:我解决了。 在 main/ 的 CMakeLists.txt 中,我需要在 target_link_libraries 中添加 test_exe

cmake_minimum_required(VERSION 3.5)

set(CMAKE_CXX_STANDARD 11)


add_executable(test_exe 
    main.cc 
)
target_link_libraries(test_exe protos)

【问题讨论】:

    标签: c++ cmake protocol-buffers


    【解决方案1】:

    这个错误:

    'google/protobuf/stubs/common.h' 文件未找到

    是因为你没有告诉编译器你的 protobuf 头文件在哪里。您可以在您的计算机上搜索“google/protobuf/stubs/common.h”吗?如果未安装,则需要安装它(使用系统包管理器)。如果已安装,则需要在 CMake 中为父目录(包含“google”的目录)添加包含目录规则。

    【讨论】:

    • 我在那个目录中有那个文件。您能否通过在 CMake 中添加包含路径来解释您的意思。我试过了,但可能做错了
    猜你喜欢
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 2017-05-29
    • 2011-12-10
    • 1970-01-01
    • 2016-03-25
    相关资源
    最近更新 更多