如何在 linux 中的标准共享库 (C) 中添加自己的自定义函数?

How to add own custom function in standard shared library (C) in linux?

我已经下载了 libgcrypt 库源代码,我想通过在一个特定的库中添加我的函数来自定义这个标准共享库 源代码文件。

虽然compilation/build定制共享库过程成功,但在链接时显示错误。

这是我所做的。

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

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

我还在 /src/gcrypt.h

中包含函数原型
void MyFunction(void);


#build process

./configure --prefix=/usr
sudo make install

nm command find this custom function.

nm /usr/lib/libgcrypt.so | grep MyFunction
000000000000dd70 t MyFunction

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

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

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


gcc aes_gcrypt_example.c -o aes -lgcrypt

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

我也尝试在 gcrypt.h 中将 MyFunction 设置为 extern,但在那种情况下我也遇到了同样的错误。

为什么会这样?

是否不允许自定义标准库?

如果是,那么是否有任何 FLAG 可以禁用以允许自定义?

如果不是,我犯了什么错误?

如果有人能提供一些有用的link/solution解决上述问题,那将是很大的帮助。我正在使用 Ubuntu16.04,gcc 4.9。

小写 t 符号类型?

nm /usr/lib/libgcrypt.so | grep MyFunction
000000000000dd70 t MyFunction

你确定这是可见函数吗?在我的 Ubuntu 16.04 VM 上,目标文件中定义的可链接函数将 T(不是 t)作为符号类型。是否有流浪者 static 踢来踢去造成混乱?检查 libgcrypt.so 中定义的几个其他函数(并记录在 gcrypt.h 中)并查看它们是否具有 tT。他们将有 T 而不是 t。您需要弄清楚为什么您的函数获得 t — 从您显示的代码中不清楚。

nm 的 (Ubuntu) 手册页包括:

The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external).

您显示的行表明 MyFunction 在其源文件之外不可见,链接器同意,因为它没有找到它。

您现在的问题是检查包含 MyFunction 的目标文件是否具有符号类型 T — 如果不是,则问题出在源代码中。

假设目标文件显示符号类型T,但共享对象显示符号类型t,你必须找到在共享对象创建阶段发生了什么,使符号在外部不可见共享对象。这可能是因为 'linker script' 控制哪些符号在库外可见(或者可能只是编译选项)。您可以在 Google 上搜索 'linker script' 和各种额外的词('tutorial'、'provide'、'example' 等),并找到相关文档的链接。

您可能需要研究 LibTool, or for the linker BinUtils. LibTool provides ways of manipulating shared libraries. In a compilation command line that you show in a , there is the option -fvisibility=hidden. I found (mostly by serendipitous accident) a GCC Wiki on visibility. See also visibility attribute and code generation options 的文档。