BLOGTIMES
2009/09/08

Cでmain()が呼ばれる直前に関数を呼ぶ

  c 
このエントリーをはてなブックマークに追加

研究用のCプログラムでmain()が呼ばれる直前をフックして別の処理を埋め込みたいという相談を後輩からうけたので、検索してみたところGCCであれば、__attribute__((constructor))を使えばすぐ出来るという話を見つけたので試して見たところ意外とすんなり実装できてびっくり。普段はほとんどC言語を使う機会もないので、こういう機能をじっくり調べる機会もあまりないんですよね。

main() の前に関数を呼ぶ - bkブログ

GCC では main() の前に呼ばれる関数を __attribute__((constructor)) という拡張機能を使って定義できます。たとえば、次のプログラムでは main() の前に foo() が呼び出されます。

gccのinfoを検索してみると、ちゃんと解説もありました。

info gcc --index-search="Declaring Attributes of Functions"

5.24 Declaring Attributes of Functions ====================================== (中略) `constructor' `destructor' The `constructor' attribute causes the function to be called automatically before execution enters `main ()'. Similarly, the `destructor' attribute causes the function to be called automatically after `main ()' has completed or `exit ()' has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program. These attributes are not currently implemented for Objective-C.

ほかにもattributeはいろいろあるみたいなので、このあたりは一読しておくといいのかも。


    トラックバックについて
    Trackback URL:
    お気軽にどうぞ。トラックバック前にポリシーをお読みください。[policy]
    このエントリへのTrackbackにはこのURLが必要です→https://blog.cles.jp/item/3193
    Trackbacks
    このエントリにトラックバックはありません
    Comments
    愛のあるツッコミをお気軽にどうぞ。[policy]
    古いエントリについてはコメント制御しているため、即時に反映されないことがあります。
    コメントはありません
    Comments Form

    コメントは承認後の表示となります。
    OpenIDでログインすると、即時に公開されます。

    OpenID を使ってログインすることができます。

    Identity URL: Yahoo! JAPAN IDでログイン