📜  C语言中的__attribute __((构造函数))和__attribute __((析构函数))语法

📅  最后修改于: 2021-05-26 03:37:03             🧑  作者: Mango

用C两个功能使用GCC编译器,主要函数后的主要函数和其他执行之前其执行的一个。

GCC特定语法

1. __attribute __((构造器))的语法:这个特殊的GCC语法,具有函数一起使用时,在该程序的前main()函数的启动,即,执行相同的函数。

2. __attribute __((析构函数))的语法:这个特殊的GCC语法,具有函数一起使用时,只需通过后main()函数_exit,即该程序终止之前执行相同的函数。

说明
构造函数和析构函数的工作方式是,共享库文件包含特殊节(ELF上的.ctors和.dtors),这些节分别包含对标记有构造函数和析构函数属性的函数的引用。在加载/卸载库时,动态加载程序会检查是否存在此类部分,如果存在,则调用其中引用的函数。

关于这些的几点值得注意:
1. __attribute __((constructor))在加载共享库时运行,通常在程序启动期间运行。
2. __attribute __((destructor))在共享库卸载时运行,通常在程序退出时运行。
3.这两个括号可能是为了将它们与函数调用区分开。
4. __attribute__是GCC特定的语法;不是函数或宏。

驱动程序代码

// C program to demonstrate working of
// __attribute__((constructor)) and
// __attribute__((destructor))
#include
  
// Assigning functions to be executed before and
// after main()
void __attribute__((constructor)) calledFirst();
void __attribute__((destructor)) calledLast();
  
void main()
{
    printf("\nI am in main");
}
  
// This function is assigned to execute before
// main using __attribute__((constructor))
void calledFirst()
{
    printf("\nI am called first");
}
  
// This function is assigned to execute after
// main using __attribute__((destructor))
void calledLast()
{
    printf("\nI am called last");
}

输出:

I am called first
I am in main
I am called last
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。