创建一个静态库包装器并链接到它

问题描述

我的问题如下:
我想围绕 libprotobuf.a 创建一个包装器,但我不希望用户明确链接到这个库。我希望这个库的所有代码都包含在我的静态库中。

我已经按照官方教程构建了 libprotobuf.a 静态库。以下是使用的命令:

git clone https://github.com/protocolbuffers/protobuf.git
cd protobuf
git submodule update --init --recursive
./autogen.sh
./configure
make

然后,我通过 protobuf 方案(test.cpp;使用 sensor.proto 编译)使用 protobuf 导出函数创建了一个简单文件protoc --cpp_out=. sensor.proto):

#include <fstream>
#include "sensor.pb.h"

#include "test.h"

void test_library() {
    Sensor sensor;
    sensor.set_name("Laboratory");
    sensor.set_temperature(23.4);
    sensor.set_humidity(68);
    sensor.set_door(Sensor_SwitchLevel_OPEN);

    std::string s;
    sensor.SerializetoString(&s);

    std::cout << s.length() << std::endl;
}
Syntax = 'proto3';

message Sensor {
  string name = 1;
  double temperature = 2;
  int32 humidity = 3;
 
  enum SwitchLevel {
    CLOSED = 0;
    OPEN = 1;
  }
  
  SwitchLevel door = 5;
}

这个导出的函数是通过一个非常简单的 main.cpp 调用的:

#include "test.h"

int main() {
    test_library();
}

我使用以下命令创建我的静态库,其中包含我的代码和 protobuf 导出的代码

rm *.o ./libprotobuf.a
g++ -c test.cpp -o test.o `pkg-config --cflags --libs protobuf`
g++ -c sensor.pb.cc -o sensor.pb.o `pkg-config --cflags --libs protobuf`
cp ../protobuf/src/.libs/libprotobuf.a .
ar x ./libprotobuf.a
ar rvcs libtest.a *.o
# Library is Now created...

# Compiling and linking against a custom main()...
g++ -c main.cpp -o main.o
g++ -o main libtest.a main.o

最后,我收到一条错误消息,提示 main.cpp:(.text+0x9): undefined reference to `test_library()',但此函数似乎包含在我的静态库 nm libtest.a | grep test_library (saying 'T')...

000000000000017a t _GLOBAL__sub_I__Z12test_libraryv
0000000000000000 T _Z12test_libraryv

我确切地说,在不使用我的包装器的情况下直接链接 libprotobuf.a 效果很好......
有什么我遗漏的吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)