Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

__attribute__((constructor)) và __attribute__((destructor)) trong C

Cách viết code có hàm thực thi trước main() và sau main() bằng thuộc tính GCC. Dùng cho tác vụ khởi tạo (startup) và dọn dẹp (cleanup).

Cú pháp:

  • __attribute__((constructor)): chạy trước main()
  • __attribute__((destructor)): chạy sau main()

Ví dụ

#include <stdio.h>

void before_main() __attribute__((constructor));
void after_main() __attribute__((destructor));

void before_main() {
    printf("Day la ham chay truoc main.\n");
}

void after_main() {
    printf("Day la ham chay sau main.");
}

int main() {
    printf("Ben trong main\n");
    return 0;
}

Kết quả

Day la ham chay truoc main.
Ben trong main
Day la ham chay sau main.