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

标签 c linux shared-libraries

我已经下载了 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/

相关文章:

c - 指针不兼容类型错误

linux - 为什么使用共享库时 Linux 上的应用程序启动速度较慢?

c - sqlite3 sqlite3_prepare_v2 段错误

c++ - CMake SWIG 生成的文件安装和创建 jar

c - 斐波那契数生成器在 N>47 时中断

linux - 如何安装git lfs

python - tcpkill : write: Operation not permitted with subprocess. 弹出

linux - 从 Linux 设置一个 Windows exe 图标(没有 Wine?)

c++ - 在库中使用模板

c++ - 共享库中的外国库