How do you execute a function in C before the main function starts

  • 2020-04-02 01:46:51
  • OfStack

In GCC, you can declare constructor and destructor using the attribute keyword as follows:


#include <stdio.h>
__attribute((constructor)) void before_main()
{
 printf("%s/n",__FUNCTION__);
}
__attribute((destructor)) void after_main()
{
 printf("%s/n",__FUNCTION__);
}
int main( int argc, char ** argv )
{
 printf("%s/n",__FUNCTION__);
 return 0;
}

  Vc does not support attribute keyword. In vc, the following method can be used:

#include <stdio.h>
int
main( int argc, char ** argv )
{
        printf("%s/n",__FUNCTION__);
        return 0;
}

int before_main()
{
        printf("%s/n",__FUNCTION__);
        return 0;
}
int after_main()
{
        printf("%s/n",__FUNCTION__);
        return 0;
}
typedef int func();
#pragma data_seg(".CRT$XIU")
static func * before[] = { before_main };
#pragma data_seg(".CRT$XPU")
static func * after[] = { after_main };
#pragma data_seg()

Compile and execute, the results of the above two pieces of code are:

before_main

The main

after_main

You can call multiple functions before and after main, declare multiple constructors, destructor under GCC using attributes, and add multiple function Pointers in before and after arrays under vc.


Related articles: