2017-01-02 198 views
0

我在做一个使用protobuf的项目。我已安装版本3.1.0。即使看起来连接了protobuf库(C++)后仍然获得protobuf链接错误

我写了一个程序在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

该命令成功退出。

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

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.

+0

作为一个更新:我重新安装protobuf的许多错误都消失了,现在的错误读取 AO:在函数'主。 MIST.cpp :(文字+ 0×20):未定义的引用'ProtobufMIST: :Task :: Task()' MIST.cpp :(。text + 0xd0):未定义对'ProtobufMIST :: Task ::〜Task'的引用' MIST.cpp :(。text + 0xf2):未定义的引用'ProtobufMIST :: Task ::〜Task()' collect2:error:ld返回1退出状态 – CyberDork34

+0

好,所以问题最终是我像一个白痴一样,在编译时实际上并没有链接任何东西。我不得不将生成的protobuf文件编译成.o文件,并使用a.o编译它。 – CyberDork34

回答

0

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