__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。__attribute__前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数

    __attribute__语法格式为:attribute ( ( attribute-list ) )

    如果函数被设定为constructor属性,则该函数会在main()函数执行之前被自动的执行;若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。

    例如:

    1. #include <iostream>
    2. using namespace std;
    3. __attribute__((constructor)) void load_file()
    4. {
    5. printf("Constructor is called.\n");
    6. }
    7. __attribute__((destructor)) void unload_file()
    8. {
    9. printf("Destructor is called.\n");
    10. }
    11. int main()
    12. {
    13. printf("this is main function.\n");
    14. return 0;
    15. }

    输出:

    1. Constructor is called.
    2. this is main function.
    3. Destructor is called.

    注:在attribute(( )) 修饰的函数中使用 std::cout 程序会崩溃