여기서 우리는 두 개의 함수가 존재하는 코드를 작성하는 방법을 볼 것이며, 하나의 함수는 메인 함수보다 먼저 실행되고 다른 함수는 메인 함수 다음에 실행될 것입니다. 이러한 기능은 메인을 실행하기 전에 일부 시작 작업을 수행하고 메인을 실행한 후에 일부 정리 작업을 수행하는 데 사용됩니다.
이 작업을 수행하려면 이 두 함수에 대한 속성을 넣어야 합니다. 속성이 생성자 속성이면 main()보다 먼저 실행되고 속성이 소멸자 유형이면 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.