__attribute__ ((constructor)) decorated functions perform __ functions before the main function

Source: Internet
Author: User


Recent research on QEMU has similar code when initializing:


#define MODULE_INIT (function, type)                                         \
static void __attribute__ ((constructor)) Do_qemu_init_ # # function (void ) {  \
    register_module_init (function, type);                                   \
}

do_qemu_init_** must be the initialization of the module, but did not call the Do_qemu_init place, odd strange, why.


Take a closer look at this function and the modifier contains __attribute__ (constructor), which is probably what this guy did.


Write code test:


#include <stdio.h>
#include <stdlib.h>


void static __attribute__ ((constructor)) Before_main ()
{
    printf ("before main\n");
}

void Static __attribute__ ((destructor)) After_main ()
{
    printf ("after main\n");
}

int main (int argc, char** argv)
{
    printf ("Hello world!\n");
}


Compile execution:

root@mothership:/home/source/test# gcc a.c-o a
root@mothership:/home/source/test#./A
before main
Hello world!
After main
root@mothership:/home/source/test#

Sure enough,

__attribute__ ((constructor))-decorated functions are executed before the main function

__attribute__ ((destructor))-decorated functions are executed after the main function








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.