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.