본문 바로가기
IT/programming

[C/C++] C언어 main 함수 전/후에 함수를 실행 하는 방법

by 어느해겨울 2021. 12. 21.

C언어 main 함수 전/후에 함수를 실행 하는 방법

 

10년 전쯤에 이런 질문을 받은 적이 있다. C언어에서 main 함수 전/후에 뭔가 print를 찍는다거나 함수 등을 실행하는 행위를 할 수 있냐고. 

나는 안될거다고 얘기했다. C의 entry function 이 main이라 stack의 시작과 끝은 main 함수이기 때문이라 생각하기 때문이다.

근데 물어보신 분은 맞는지 틀리는지 대답을 해주지 않으셨고 어느날 불현듯 그 질문이 생각나서 찾다 보니 가능하다는 글을 보아 갈무리를 하였다. 갈무리 역시 6년 전이지만 정리하는 습관을 기르기 위해 남겨본다.

 

출처와 내용은 다음과 같다.

http://www.geeksforgeeks.org/functions-that-are-executed-before-and-after-main-in-c/

Functions that are executed before and after main() in C

With GCC family of C compilers, we can mark some functions to execute before and after main(). So some startup code can be executed before main() starts, and some cleanup code can be executed after main() ends. For example, in the following program, myStartupFun() is called before main() and myCleanupFun() is called after main().

 

#include<stdio.h>
 
/* Apply the constructor attribute to myStartupFun() so that it
    is executed before main() */
void myStartupFun (void) __attribute__ ((constructor));
 
 
/* Apply the destructor attribute to myCleanupFun() so that it
   is executed after main() */
void myCleanupFun (void) __attribute__ ((destructor));
 
 
/* implementation of myStartupFun */
void myStartupFun (void)
{
    printf ("startup code before main()\n");
}
 
/* implementation of myCleanupFun */
void myCleanupFun (void)
{
    printf ("cleanup code after main()\n");
}
 
int main (void)
{
    printf ("hello\n");
    return 0;
}

결과는 다음과 같다.

startup code before main()
hello
cleanup code after main()

 

C언어에서 __attribute__ 키워드를 사용하여 as 생성자와 소멸자를 구현한듯하다. 

pre-compile 시에 동작을 정의할 수 있다고도 들은거 같은데 직접 해보지 않아 그것 역시 모르겠다.

 

 

__attribute__ 키워드 정보

https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html

 

Variable Attributes (Using the GNU Compiler Collection (GCC))

6.34 Specifying Attributes of Variables The keyword __attribute__ allows you to specify special properties of variables, function parameters, or structure, union, and, in C++, class members. This __attribute__ keyword is followed by an attribute specificat

gcc.gnu.org

 

 

댓글