如何在C ++中正确链接.so库?

问题描述 投票:0回答:1

我有这样的项目结构,

a.pb.h          --- includes -->    protobuf.h
b.grpc.pb.h     --- includes -->    a.pb.h & grpcpp.h

还有a.pb.ccb.grpc.cc文件。

一个带有extern C的C ++包装器,它是wrapper.ccwrapper.h,包括b.grpc.pb.hgrpcpp.h。 extern C中的函数是char* helloWorld(const char*, const char*, const char*);

创建.oa.pb.hb.grpc.pb.h

g++ -fpic -std=c++11 `pkg-config --cflags protobuf grpc`  -c -o a.pb.o a.pb.cc
g++ -fpic -std=c++11 `pkg-config --cflags protobuf grpc`  -c -o b.grpc.pb.o b.grpc.pb.cc

创建libcombined.so的步骤:

grpcprotobuf已经在/usr/local/lib下提供了。首先创建了.soa.pb.ob.grpc.pb.o来编译包装文件:

g++ -shared -o libcombined.so *.o

编译包装为:

g++ -fpic wrapper.cc -l:./libcombined.so -c -o wrapper.o -std=c++11

.soa.pb.ob.grpc.pb.owrapper.olibcombined.so

g++ -shared -o libcombinedwrapper.so *.o

编译main.c为:

gcc main.c -l:./libcombinedwrapper.so -o main -ldl

我从我的helloWorld文件中调用main.c,它是:

#include <stdio.h>
#include <dlfcn.h>

int main(){
    char* (*fn)(const char*,const char*,const char*);
    void *handle  = dlopen("path_to/libcombined.so",RTLD_NOW);
    if(handle==NULL){
        fprintf(stderr, "Error: %s\n", dlerror());
    }
    fn = (char* (*)(const char*,const char*,const char*))dlsym(handle, "helloWorld");
    if (!fn) {
        /* no such symbol */
        fprintf(stderr, "Error: %s\n", dlerror());
        dlclose(handle);
        return 0;
    }
    char* msg = fn("asd","asdas","asdasd");
    printf("%s",msg);
    return 0;
}

执行后出错:./main

Error: path_to/libcombinedwrapper.so: undefined symbol: _ZN6google8protobuf2io20ZeroCopyOutputStream15WriteAliasedRawEPKvi
Error: ./main: undefined symbol: helloWorld
Segmentation fault (core dumped)

上面的第一个错误来自protobuf.h文件中的符号。

有人可以在链接时建议我做错了什么,或者我在main.c文件中做错了什么?

linux c++11 grpc dynamic-linking dlopen
1个回答
0
投票

g++ -shared -o libcombined.so *.o

您还需要链接对象的所有依赖项(此处为libgrpc)。

您可以添加-Wl,--no-allow-shlib-undefined来验证libcombined.so是否链接了所需的一切。

附:为了避免核心转储,一旦exit失败,你应该returndlopen

P.P.S.链接*.o通常是一个非常糟糕的想法(TM)。使用适当的Makefile来避免不必要的编译,并明确列出您打算放入libcombined.so的对象。

© www.soinside.com 2019 - 2024. All rights reserved.