【问题标题】:Getting protobuf linking errors even after seemingly linking protobuf libraries (C++)即使在看似链接了 protobuf 库 (C++) 之后也会出现 protobuf 链接错误
【发布时间】:2017-05-16 20:57:30
【问题描述】:

我正在做一个使用 protobuf 的项目。我已经安装了 3.1.0 版本。

我写了一个程序来测试protobuf中的序列化,看起来像这样

// This file exists to facilitate testing

//MIST.cpp

//#include <asio.hpp>
#include <Task.hpp> //user defined, not relevant
#include <MIST.hpp> //user defined, not relevant
#include <ReceiveData.hpp> //user defined, not relevant
#include <MIST.pb.h> //protobuf file made from protoc

int main() {
    /*MIST::ReceiveData receiveObj;
    std::string s = receiveObj.receive<64>();
    std::cout << "Message received: '" << s << "'" << std::endl;*/

    ProtobufMIST::Task taskObj;
    taskObj.set_task_name("The Best Task");
    taskObj.set_task_id("7");

    std::string* message;
    if(!taskObj.SerializeToString(message))
        std::cout << "Task '" << taskObj.task_name() << "'" << " not serialized successfully\n";
    else
        std::cout << message << std::endl;

    return 0;
}

我用构建脚本编译了它。底层命令是g++ std=c++1y [link include files] -lpthread MIST.cpp -lprotobuf -o a.o

此命令成功退出。

然后我尝试将a.o 与命令g++ a.o -std=c++1y -L/usr/local/lib/ -lprotobuf -o a 链接,我收到以下错误

a.o: In function `main':
MIST.cpp:(.text+0x20): undefined reference to `ProtobufMIST::Task::Task()'
MIST.cpp:(.text+0x55): undefined reference to `google::protobuf::MessageLite::SerializeToString(std::string*) const'
MIST.cpp:(.text+0xd0): undefined reference to `ProtobufMIST::Task::~Task()'
MIST.cpp:(.text+0xf2): undefined reference to `ProtobufMIST::Task::~Task()'
a.o: In function `google::protobuf::internal::GetEmptyStringAlreadyInited()':

MIST.cpp:(.text._ZN6google8protobuf8internal27GetEmptyStringAlreadyInitedEv[_ZN6google8protobuf8internal27GetEmptyStringAlreadyInitedEv]+0x5): undefined reference to `google::protobuf::internal::fixed_address_empty_string'
collect2: error: ld returned 1 exit status

我不确定当我同时包含 -L/usr/local/lib 和 -lprotobuf 时,怎么会有未定义的引用来包含我已经编译过的文件,或者怎么会有对 protobuf 的未定义引用。我不知道怎么可能是问题。

供参考,我已经尝试实施这些解决方案收效甚微

problems with linking protobuf library

Linking protobuf library with code (Google protocol buffers)

Can't compile example from google protocol buffers

在虚拟机上运行 Kubuntu 16.10。主机是 Windows 10。

【问题讨论】:

  • 作为更新:我重新安装了 protobuf,许多错误都消失了,现在错误显示为 ao: In function main': MIST.cpp:(.text+0x20): undefined reference to ProtobufMIST::Task::Task()' MIST.cpp:(. text+0xd0): 未定义对ProtobufMIST::Task::~Task()' MIST.cpp:(.text+0xf2): undefined reference to ProtobufMIST::Task::~Task()' 的引用 collect2: error: ld returned 1 exit status
  • 好的,所以问题最终是我,像个白痴,在编译时实际上并没有链接任何东西。我必须将生成的 protobuf 文件编译成 .o 并用 a.o 编译。

标签: c++ linker g++ c++14 protocol-buffers


【解决方案1】:

将.pb.cc文件编译成.o文件并与主程序链接,这样应该可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多