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

Hàm thực thi trước và sau main() trong C

Ở đây ta viết code có 2 hàm: 1 hàm chạy trước main(), 1 hàm chạy sau main(). Dùng cho tác vụ khởi tạo (startup) trước main, và dọn dẹp (cleanup) sau main.

Dùng attribute: constructor chạy trước main, destructor chạy sau main.

Ví dụ

#include <stdio.h>

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

void before_main() {
    printf("This is executed before main.\n");
}

void after_main() {
    printf("This is executed after main.");
}

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

Kết quả

This is executed before main.
Inside main
This is executed after main.