ที่นี่เราจะดูวิธีเขียนโค้ดที่มีฟังก์ชัน 2 ฟังก์ชัน ฟังก์ชันหนึ่งจะทำงานก่อน main() และอีกฟังก์ชันทำงานหลัง main() คุณสมบัตินี้ใช้สำหรับงานเริ่มต้นก่อนรัน main และงานทำความสะอาดหลังรัน main
เพื่อทำอย่างนี้ ต้องกำหนด attribute ให้ฟังก์ชันทั้งสอง ถ้า attribute เป็น constructor จะรันก่อน main() ถ้าเป็น destructor จะรันหลัง main()
เราใช้ฟังก์ชัน GCC คือ __attribute__() กรณีนี้ใช้ 2 ตัวเลือกคือ Constructor และ Destructor ไวยากรณ์ __attribute__((constructor)) ใช้สำหรับรันฟังก์ชันตอนเริ่มโปรแกรม และ __attribute__((destructor)) ใช้สำหรับรันฟังก์ชันตอนจบ main() ดูตัวอย่างเพื่อเข้าใจดีขึ้น
ตัวอย่างโค้ด
#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."); } main() { printf("Inside main\n"); }ผลลัพธ์
This is executed before main. Inside main This is executed after main.