gcc下__attribute__ ((constructor))和__attribute__ ((destructor))的使用

本文介绍了GCC编译器中利用__attribute__((constructor))和__attribute__((destructor))属性来实现共享库加载和卸载时自动调用特定函数的功能。通过示例代码展示如何编写和编译,并在运行时观察初始化和清理函数的调用顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

__attribute__ ((constructor))指定的函数在共享库loading的时候调用,__attribute__ ((destructor))指定的函数在共享库unloading的时候调用。

 

1. 编写源码文件ktest.c如下.

#include <stdio.h>
__attribute__ ((constructor)) static void ktest_init(void);
__attribute__ ((destructor)) static void ktest_deinit(void);

void ktest_init(void)
{
    printf("call ktest init./n");
}

void ktest_deinit(void)
{
    printf("call ktest deinit./n");
}

void test1()
{
    printf("call test1./n");
}

void test2()
{
    printf("call test2./n");
}

void test3()
{
    printf("call test3./n");
}

2. 编译为共享库libktest.so

gcc -fPIC -c ktest.c   ### produce ktest.o.
gcc -shared -o libktest.so ktest.o ### produce libktes.so


3. 编写库调用文件calllib.c

#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h> /* dlopen, dlsym, dlclose */

int main(int argc, char **argv)
{
    test1();
    test2();
    test3();

    /* below only for testing dynamic linking loader */
    void *handle;
    void (*test)();
    char *error;

    handle = dlopen ("/path_to_lib/libktest.so", RTLD_LAZY);
    if (!handle) {
        fputs (dlerror(), stderr);
        exit(1);
    }

    test = dlsym(handle, "test2");
    if ((error = dlerror()) != NULL)  {
        fputs(error, stderr);
        exit(1);
    }

    (*test)();
    dlclose(handle);

    return 0;
}

 

4. 编译calllib运行, 将可以看到ktest_init() 和ktest_deinit()已被调用.

gcc calllib.c -o calllib -ldl -L./ -lktest  ### produce calllib

export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH && ./calllib

call ktest init.
call test1.
call test2.
call test3.
call test2.
call ktest deinit.

 


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

      http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

      http://unixwiz.net/techtips/gnu-c-attributes.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值