[cpp]
#include
__attribute__((constructor)) void before_main() {
printf("%s\n", __FUNCTION__);
}
__attribute__((destructor)) void after_main() {
printf("%s\n", __FUNCTION__);
}
int main(int argc, char **argv) {
printf("%s\n", __FUNCTION__);
return 0;
}
輸出:before_main → main → after_main。可定義多個 constructor/destructor,按優先級順序執行。
[cpp]
#include
int before_main() { printf("%s\n", __FUNCTION__); return 0; }
int after_main() { printf("%s\n", __FUNCTION__); return 0; }
typedef int (*func)();
#pragma data_seg(".CRT$XIU")
static func *before[] = { before_main };
#pragma data_seg(".CRT$XPU")
static func *after[] = { after_main };
#pragma data_seg()
int main(int argc, char **argv) {
printf("%s\n", __FUNCTION__);
return 0;
}
利用 CRT 初始化節區 .CRT$XIU (初始化) 和 .CRT$XPU (終止) 注冊函數指針。