C 语言如何在 main 函数之前或之后执行一段代码

How to execute some scripts before or after main in C language

Code

#include 

void __attribute__ ((constructor)) premain()
{
    printf("premain\n");
}

void __attribute__ ((destructor)) postmain()
{
    printf("postmain\n");
}

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

This code can be compiled on my Windows by

gcc -o main main.c

or (use Clang)

clang --target=x86_64-w64-mingw32 -o main main.c

and surely it would work on Linux.

The result would be

premain
main
postmain

However, when compiled by

clang -o main main.c

in which the target, by default, is x86_64-pc-windows-msvc, there would be an error

premain
main
Segmentation fault

Reference and detailed information on 戴正华《UEFI原理与编程》, including how to make it work with msvc.

你可能感兴趣的:(C 语言如何在 main 函数之前或之后执行一段代码)