gpt4 book ai didi

c - dlsym 返回 NULL,即使该符号存在

转载 作者:IT王子 更新时间:2023-10-29 00:32:54 33 4
gpt4 key购买 nike

我正在使用 dlsym 在我的程序中查找符号,但它总是返回 NULL,这出乎我的意料。根据联机帮助页,如果出现某种错误或者符号确实为 NULL,dlsym 可能会返回 NULL。就我而言,我遇到了一个错误。我将向您展示我今晚制作的 MCVE。

这是instr.c的内容:

#include <stdio.h>

void * testing(int i) {
printf("You called testing(%d)\n", i);
return 0;
}

一个非常简单的东西,只包含一个不起眼的示例函数。

这里是test.c的内容:

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

typedef void * (*dltest)(int);

int main(int argc, char ** argv) {

/* Declare and set a pointer to a function in the executable */
void * handle = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL);
dlerror();
dltest fn = dlsym(handle, "testing");

if(fn == NULL) {
printf("%s\n", dlerror());
dlclose(handle);
return 1;
}
dlclose(handle);
return 0;
}

当我使用调试器逐步执行代码时,我看到 dlopen 正在返回一个句柄。根据联机帮助页,如果文件名是 NULL,则返回的句柄用于主程序。 因此,如果我将名为 testing 的符号链接(symbolic link)到主程序中,dlsym 应该找到对吧?

这是我编译和链接程序的方式:

all: test

instr.o: instr.c
gcc -ggdb -Wall -c instr.c

test.o: test.c
gcc -ggdb -Wall -c test.c

test: test.o instr.o
gcc -ldl -o test test.o instr.o

clean:
rm -f *.o test

当我构建这个程序时,然后执行 objdump -t test | grep testing,我看到符号 testing 确实存在:

08048632 g     F .text  00000020              testing

但是我的程序的输出是错误的:

./test: undefined symbol: testing

我不确定我做错了什么。如果有人能阐明这个问题,我将不胜感激。

最佳答案

我不认为你能做到这一点,dlsym 适用于导出的符号。因为您在 NULL(当前图像)上执行 dlsym,即使符号存在于可执行 ELF 图像中,它们也不会导出(因为它不是共享的图书馆)。

为什么不直接调用它,让链接器来处理呢?使用 dlsym 从与 dlsym 调用相同的图像中获取符号是没有意义的。如果您的 testing 符号位于您使用 dlopen 链接或加载的共享库中,那么您将能够检索它。

我相信在构建可执行文件时还有一种导出符号的方法(-Wl,--export-dynamic,如 Brandon 的评论中所述),但我不确定您为什么要要做到这一点。

关于c - dlsym 返回 NULL,即使该符号存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37104928/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com