How to execute a function before the main function starts in C?

Source: Internet
Author: User


In gcc, you can use the attribute keyword to declare constructor and destructor. The Code is as follows:


[Cpp]
# 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;
}
# 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 keywords. You can use the following methods in vc:


[Cpp]
# 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 ()
# 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 above two sections of code:

Before_main

Main

After_main

 

You can call multiple functions before and after main, declare multiple constructor and destructor using attribute under gcc, and add multiple function pointers in the before and after arrays under vc.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.