広告

main()関数(その4) C/C言語上級講座

予告したように、GCCでのmain()関数のテクです。
#include <stdio.h> 

__attribute__((constructor)) void
before ()
{
    (void)printf ("Before !\n");
}

int
main (void)
{
    (void)printf ("Main !\n");

    return EX_OK;
}
実行してみませう。
% gcc main.c
% ./a.out
Before !
Main !
驚きましたか?
before()関数が呼ばれもしないのに実行されちやつてゐます。
しかもmain()関数よりも前に。 実はGCCはmain()関数の前に呼ばれる関数を
__attribute__((constructor))
で指定できるのです。
もう少し、遊んでみませう。
#include <stdio.h> 

__attribute__((constructor)) void
before0 ()
{
    (void)printf ("Before0 !\n");
}

__attribute__((constructor)) void
before1 ()
{
    (void)printf ("Before1 !\n");
}

int
main (void)
{
    (void)printf ("Main !\n");

    return EX_OK;
}
実行してみれば分りますが、 before0()関数もbefore1()関数も共に実行されます。
Copyright © 皇紀2670 Ezo Labo. All Rights Reserved.
皇紀2670年05月20日更新
TOPへ