C++在main函数之前或之后执行的函数

 
Category: C++

写在前面

总结一波面试题

测试环境 Ubuntu+clang

之前执行

#include <iostream>
using namespace std;

__attribute((constructor)) void before() { // C
    cout << "before main 1\n";
}

int a = []() { // C++ 11
    cout << "before main 2\n";
    return 0;
}();

int t1() {
    cout << "before main 3\n";
    return 1;
}

static int p1 = t1();

struct P {
    P() { cout << "before main 4\n"; }
};
P p; // global object

int main(int argc, char *argv[]) {
    cout << "main\n";
    return 0;
}
// before main 1
// before main 2
// before main 3
// before main 4
// main

之后

#include <iostream>
// #include <cstdlib> //atexit
using namespace std;


auto f1 = []() { cout << "after main 1\n"; };

void f2(int, void *) { //
    cout << "after main 2\n";
}

struct P {
    ~P() { cout << "after main 3\n"; }
};
P p; // global object

__attribute((destructor)) void after() { //
    cout << "after main 4\n";
}

int main(int argc, char *argv[]) {
    on_exit(f2, NULL); // just for linux
    atexit(f1);        // 调用顺序与注册顺序相反
    cout << "main\n";
    return 0;
}

// main
// after main 1
// after main 2
// after main 3
// after main 4