c/c++ 在main之前运行函数,在main结束后运行的函数

在gcc编译环境下,使用__attribute__关键字实现

原理:全局对象的构造函数在 main 函数之前

__attribute__((constructor))

__attribute__((destructor))

__attribute__((constructor))
void before() {
    cout << "befor" << endl;
}

__attribute__((destructor))
void after() {
    cout << "after" << endl;
}

int main() {
    cout << "main" << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/LIN-JW/p/12662130.html