gpt4 book ai didi

c - 在 C 中覆盖 _init 函数,它有多安全?

转载 作者:IT王子 更新时间:2023-10-29 01:10:38 25 4
gpt4 key购买 nike

我正在构建一个共享库形式的调试内存工具,我在运行时链接到一个可执行文件(包括 malloc 系列的重写方法)。为了处理我的数据结构的初始化,我简单地使用了一个条件变量。每次调用我的 malloc 时,我都会检查变量是否未设置,然后调用负责初始化结构的函数。现在这对于运行单个执行线程的程序来说效果很好,但如果程序包含超过 1 个线程,就会出现问题。

确保在用户生成任何线程之前进行初始化的唯一方法(我能想到)是覆盖 _init,如图所示 in this link .

现在这个小例子运行正确了,但是当我尝试在我自己的共享库上覆盖 _init 时,我在尝试链接它时遇到了这个错误:

memory2.o: In function `_init':
memory2.c(.text+0x0): multiple definition of `_init'
/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crti.o(.init+0x0):
first defined here
collect2: ld returned 1 exit status

我使用与链接示例中完全相同的步骤,只是我的共享库还包含一组全局变量和 malloc/free 等的覆盖版本。

谁能告诉我哪里出了问题?此外,在覆盖 _init 时是否还有其他需要考虑的因素(我猜这不是一件很正常的事情)。

谢谢

最佳答案

查看以下常见问题页面:

http://www.faqs.org/docs/Linux-HOWTO/Program-Library-HOWTO.html#INIT-AND-CLEANUP

它将 _init/_fini 描述为危险和过时的,并建议使用 __attribute__ ((constructor))__attribute__ ((destructor))而是使用。

来自gcc manual :

constructor (priority) destructor (priority)

The constructor attribute causes the function to be called automatically before execution enters main(). Similarly, the destructor attribute causes the function to be called automatically after main() has completed or exit() has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program. You may provide an optional integer priority to control the order in which constructor and destructor functions are run. A constructor with a smaller priority number runs before a constructor with a larger priority number; the opposite relationship holds for destructors. So, if you have a constructor that allocates a resource and a destructor that deallocates the same resource, both functions typically have the same priority. The priorities for constructor and destructor functions are the same as those specified for namespace-scope C++ objects (see C++ Attributes).

These attributes are not currently implemented for Objective-C.

关于c - 在 C 中覆盖 _init 函数,它有多安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5474969/

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