我正在以共享库的形式构建调试内存工具,我在运行时链接可执行文件(包括malloc系列的重写方法).为了处理我的数据结构的初始化,我简单地使用了一个条件变量.每次调用malloc时,我都会检查变量是否未设置,然后调用一个负责初始化结构的函数.现在,这适用于运行单个执行线程的程序,但如果程序包含多个线程,则会出现问题.
确保在用户生成任何线程之前进行初始化的唯一方法(我能想到)是覆盖_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 __((构造函数))和__attribute __((析构函数)).
从gcc
manual开始:
constructor (priority)
destructor (priority)
The
constructor attribute causes the
function to be called automatically
before execution entersmain()
.
Similarly,the destructor attribute
causes the function to be called
automatically aftermain()
has
completed orexit()
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.