甚至在看似链接protobuf库之后获得protobuf链接错误(C ++)

时间:2017-01-02 19:09:37

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

我正在做一个我正在使用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时,如何对protobuf进行未定义的引用和-lprotobuf。我很难过如何解决问题。

作为参考,我试图实现这些解决方案并不成功

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。

1 个答案:

答案 0 :(得分:-1)

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