教程中C中的attribute((constructor))和attribute((destructor))语法指向吗?
在这里,我们将看到如何编写存在两个功能的代码,其中一个功能将在主功能之前执行,另一个功能将在主功能之后执行。这些功能用于在执行main之前执行一些启动任务,并在执行main之后执行一些清理任务。
为此,我们必须为这两个函数放置属性。当属性是构造函数属性时,它将在执行之前main()
,而当属性是析构函数类型时,它将在之后执行main()
。
我们正在使用GCC函数。该函数是__attribute__()。在这种情况下,我们使用两个不同的选项。具有__attribute__()函数的构造函数和析构函数。程序启动时,语法__attribute__((constructor))用于执行功能。main()
函数完成后,将使用语法__attribute__((destructor))来执行该函数。请仔细阅读示例以获得更好的主意。
示例
#include <stdio.h> void before_main() __attribute__((constructor)); void after_main() __attribute__((destructor)); void before_main() { printf("This is executed before main.\n"); } void after_main() { printf("这是在main之后执行的。"); } main() { printf("Inside main\n"); }
输出结果
This is executed before main. Inside main 这是在main之后执行的。