gpt4 book ai didi

c - 无法从 C 中的其他模块访问 linux 中共享库的自定义全局函数

转载 作者:可可西里 更新时间:2023-11-01 11:45:10 24 4
gpt4 key购买 nike

我已经下载了 libgcrypt 库源代码和在一个特定文件中添加了我自己的自定义功能。

虽然自定义共享库的编译/构建过程是成功的,并且 nm 和 objdump 都显示 自定义函数是全局的它仍然在链接时显示错误( undefined reference )。

这是我所做的:

在/src/visibility.c 文件中,我添加了我的自定义函数,

void __attribute__((visibility("default"))) MyFunction(void)
{
printf("This is added just for testing purpose");
}

构建过程

./configure --prefix=/usr/local --disable-ld-version-script

sudo make install

nmobjdump 命令在共享库中发现这个自定义函数是全局的。

nm /usr/local/lib/libgcrypt.so | grep MyFunction
000000000000fbf0 T MyFunction


objdump -t /usr/local/lib/libgcrypt.so | grep MyFunction
000000000000fbf0 g F .text 0000000000000013 MyFunction

这是我访问自定义函数的示例代码。

//gcrypt_example_test.c
#include <stdio.h>
#include <gcrypt.h>
#include <assert.h>

int main()
{
MyFunction();
return 0;
}


export LD_RUN_PATH=/usr/local/lib
gcc gcrypt_example_test.c -o test -lgcrypt

/tmp/ccA0qgAB.o: In function `main': gcrypt_example_test.c:(.text+0x3a2): undefined reference to `MyFunction' collect2: error: ld returned 1 exit status

编辑 1:

我尝试了所有可能的方法来将函数原型(prototype)声明包含在头文件 (/src/gcrypt.h) 中,如下所示:

   void __attribute__((visibility("default"))) MyFunction(void);   

...或者:

    extern void __attribute__((visibility("default"))) MyFunction(void);  

...或者:

    extern void   MyFunction(void);

...或者:

    void   MyFunction(void);

尽管在上述所有情况下都没有生成错误结果,但我仍然遇到相同的错误(undefined reference)。

为什么会这样,我犯了什么错误?

虽然其他全局函数是标准共享库的一部分并在 visibility.c 中定义(nm 也显示了这些函数的 T)可以访问,为什么我自定义的共享库的全局函数(MyFunction)仍然无法访问?谢谢!

非常感谢解决此错误的任何链接或解释。

最佳答案

来自 the GCC documentation (强调我的):

Some linkers allow you to specify the path to the library by setting LD_RUN_PATH in your environment when linking.

但是,from the GNU ld man page :

   -rpath=dir
Add a directory to the runtime library search path. This is used
when linking an ELF executable with shared objects. All -rpath
arguments are concatenated and passed to the runtime linker,
which uses them to locate shared objects at runtime. The -rpath
option is also used when locating shared objects which are needed
by shared objects explicitly included in the link; see the
description of the -rpath-link option. If -rpath is not used
when linking an ELF executable, the contents of the environment
variable "LD_RUN_PATH" will be used if it is defined.

请注意,根本没有提及链接时间库搜索路径。

您需要在链接时库搜索路径中用/usr/local/lib编译/链接:

gcc gcrypt_example_test.c -o test -L/usr/local/lib -lgcrypt

关于c - 无法从 C 中的其他模块访问 linux 中共享库的自定义全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48752139/

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