2
Functions which get executed before and after main() in C
Function
C
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.

Apply the constructor attribute to any function so that it can get called before main() and apply destructor attribute to any function so that it can get called after main().

Here in example below I have applied constructor attribute to startupFunction() and destructor on cleanupFunction().

    /* Apply the constructor attribute to startupFunction() so that it is executed before main() */

        void startupFunction(void) __attribute__ ((constructor));

    /* Apply the destructor attribute to cleanupFunction() so that it is executed after main() */

        void cleanupFunction(void) __attribute__ ((destructor));

/* implementation of startupFunction*/
   void startupFunction(void)
    {
        printf ("startup code before main()\n");
    }

/* implementation of cleanupFunction*/
   void cleanupFunction(void)
    {
        printf ("cleanup code after main()\n");
    }

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

Output:

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

Reference:- [http://www.drdobbs.com/]

Author

Notifications

?