C 中的 attribute((constructor)) 和 attribute((destructor)) 语法在 tutorials point 中是如何使用的?
我们将了解如何编写一个代码,其中有两个函数,一个函数将在主函数之前执行,另一个函数将在主函数之后执行。这些特性用于在执行主函数之前执行一些启动任务,并在执行主函数之后执行一些清理任务。
为此,我们必须为这两个函数赋予属性。属性为构造函数属性时,它将在 main() 之前执行,属性为析构函数类型时,它将 main() 之后执行。
我们使用 GCC 函数。该函数为 __attribute__(). 在本例中,我们使用两个不同的选项。使用 __attribute__() 函数的构造函数和析构函数。语法 __attribute__((constructor)) 用于在程序启动时执行函数。而语法 __attribute__((destructor)) 用于在 main() 函数执行完成后执行函数。请仔细阅读此示例以获得更好的想法。
示例
#include <stdio.h>
void before_main() __attribute__((constructor));
void after_main() __attribute__((destructor));
void before_main() {
printf("This is executed before main.
");
}
void after_main() {
printf("This is executed after main.");
}
main() {
printf("Inside main
");
}输出
This is executed before main. Inside main This is executed after main.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP