Shared objects may export functions using the
__attribute__((constructor)) and __attribute__((destructor))
function attributes. Constructor functions are executed before
dlopen() returns, and destructor functions are executed before
dlclose() returns. A shared object may export multiple
constructors and destructors, and priorities can be associated
with each function to determine the order in which they are
executed. See the gcc info pages (under "Function attributes")
for further information.
函数设置__attribute__((constructor))属性,在dlopen时,会先调用该方法。
设置__attribute__((destructor))属性,在dlclose时会调用该方法。
demo
下面举例
// test.c
#include <stdio.h>
__attribute__((constructor)) void test_init() {
printf("hello world\n");
}
__attribute__((destructor)) void test_fini() {
printf("bye world\n");
}
void test() {
printf("test\n");
}
gcc -fPIC -shared test.c -o libtest.so
#include <stdio.h>
#include <dlfcn.h>
typedef void(*testFunc)();
int main() {
void *handle = dlopen("./libtest.so", RTLD_LAZY);
if (handle == NULL) {
printf("handle is null, %s\n", dlerror());
}
printf("----------\n");
testFunc f = (testFunc)dlsym(handle, "test");
if (f == NULL) {
printf("f is null\n");
}
f();
dlclose(handle);
return 0;
}
gcc main.c -ldl -O0 -g
执行可执行文件,在dlopen时执行test_init方法,最后在dlclose执行test_fini方法。
// a.out
hello world
----------
test
bye world