__attribute__(constructor))修飾された関数はmain関数の前に実行されます.

1134 ワード

最近qemuを研究して、初期化の時似たようなコードがあります:
#define module_init(function, type)                                         \
static void __attribute__((constructor)) do_qemu_init_ ## function(void) {  \
    register_module_init(function, type);                                   \
}

do_qemu_init_** モジュールの初期化に違いないがdo_は呼び出されなかったqemu_Initのところ、おかしいですね.どうしてですか.
この関数をよく見ると、修飾子には__が含まれています.attribute__((constructor))、こいつがやったと思う!
コードテストを書く:
#include 
#include 


void static __attribute__((constructor)) before_main()
{
    printf("before main
"); } void static __attribute__((destructor)) after_main() { printf("after main
"); } int main(int argc, char** argv) { printf("hello world!
"); }

コンパイル実行:
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#

やはりそうなのか、
__attribute__((constructor))修飾された関数はmain関数の前に実行されます_attribute__(destructor))修飾された関数はmain関数の後に実行されます.