我有一个可执行文件shared_main、一个共享库libbar.so和一个动态加载共享库libfoo.so(通过dlopen加载shared_main).

shared_main不使用libbar.so中的任何符号,但libfoo.so使用.

所以gcc -g -Wall -o shared_main shared_main.c libbar.so -ldl不能把libbar.soshared_main联系起来.

如何让gcc强制shared_main链接libbar.so

P、 我知道我可以把libfoo.solibbar.so联系起来.但我想try 一下,如果我能强迫shared_main连接libbar.so.


shared_main.c

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

int main(){    
    void* libHandle = dlopen("./libfoo.so", RTLD_LAZY);
    if(libHandle == NULL){
        printf("dlopen:%s", dlerror());
        exit(1);
    }
    int(*xyz)(int);
    xyz = (int(*)(int)) dlsym(libHandle, "xyz");
    if(xyz == NULL){
        printf("dlsym:%s", dlerror());
        exit(1);
    }
    int b = xyz(3);
    printf("xyz(3): %d\n", b);

}

傅.c(libfoo.so)

void func_in_bar();
int xyz(int b){
    func_in_bar();
    return b + 10;
}

wine 吧c(libbar.so)

//mimic python share library runtime
#include <stdio.h>
void func_in_bar(){
    printf("I am a Function in bar\n");
}

void another_func_in_bar(){
    printf("I am another function in bar\n");
}

生成文件

shared_main:
    gcc -g -Wall -o shared_main shared_main.c libbar.so -ldl
shared:
    gcc -g -Wall -fPIC -shared -o libfoo.so foo.c
    gcc -g -Wall -fPIC -shared -o libbar.so bar.c

推荐答案

你有一个XY问题,其中X是:libfoo has unresolved symbols, but the linker doesn't warn about it

因此,使用-z defs选项链接时间,当您得到关于未解析符号的链接器错误时,将-lfoo添加到链接命令.

这还不够,你还必须使用-L-Wl,-rpath选项.这是一个完整的生成文件:

# Makefile

# LIBDIR should be the final place of the shared libraries
# such as /usr/local/lib or ~/libexec/myproject

LIBDIR  := ${PWD}
TARGETS := shared_main libbar.so libfoo.so

all: ${TARGETS}

clean:
    rm -f ${TARGETS} 2>/dev/null || true

shared_main: shared_main.c
    gcc -g -Wall -o shared_main shared_main.c -ldl

libbar.so: bar.c
    gcc -g -Wall -fPIC -shared -o libbar.so bar.c

libfoo.so: foo.c libbar.so
    gcc -g -Wall -fPIC -shared -z defs -o libfoo.so foo.c \
    -L${LIBDIR} -Wl,-rpath,${LIBDIR} -lbar

编辑:尽管如此,对于最初的问题,这里有一个黑客解决方案:使用选项-Wl,--no-as-needed

shared_main:
    gcc -g -Wall -o shared_main shared_main.c \
    -Wl,--no-as-needed -Wl,-rpath,${PWD} libbar.so -ldl

C++相关问答推荐

想了解 struct 指针和空指针转换

GCC不警告隐式指针到整数转换'

使用NameSurname扫描到两个单独的字符串

为什么GCC可以调用未定义的函数?

正在try 将文件/文件夹名从目录 struct 存储到链接列表

创建一个fork导致fget无限地重新读取文件

从TCP连接启动UDP(C套接字)

cairo 剪辑区域是否存在多个矩形?

如何在GDB中查看MUSL的源代码

MacOS下C++的无阻塞键盘阅读

在进程之间重定向输出和输入流的问题

链接到底是如何工作的,我在这里到底做错了什么

Zlib:解压缩大文件导致";无效代码长度设置";错误

如何对现有的双向循环链表进行排序?

从文件到链表读取日期

STM32:代码的执行似乎取决于它在闪存中的位置

将char*铸造为空**

C循环条件内的函数

使用替代日历打印日期

在 C/C++ 中原子按位与字节的最佳方法?