关于GCC的__attribute__(constructor)

本文介绍如何在Linux动态库中实现类似Windows DLLMain的功能。利用GCC的__attribute__((constructor))和__attribute__((destructor))属性,在main函数前后分别调用before_main和after_main函数。

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

今天写一个动态库,需要让动态库有一个类似于windows的DLLMain函数一样功能的函数,可惜发现Linux没有这样的功能,于是查阅了大量的资料,最后发现GCC的__attribute__属性设置可以将函数设置成类似于这样功能的函数:
  1. __attribute__((constructor)) // 在main函数被调用之前调用
  2. __attribute__((destructor)) // 在main函数被调用之后调
一个简单的例子如下:

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. __attribute__((constructor)) void before_main() {
  3.    printf("before main\n");
  4. }

  5. __attribute__((destructor)) void after_main() {
  6.    printf("after main\n");
  7. }
  8.   
  9. int main(int argc, char **argv) {
  10.    printf("in main\n");
  11.    return 0;
  12. }
这个例子的输出结果将会是:
  1. before main
  2. in main
  3. after main



阅读(70) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值