gccの拡張を使った小ネタ。ユースケースはあんまり分からないがcソースでmain関数の前に処理を行いたいケースで以下のgccの拡張を使うとできるよって話。
具体的なサンプルは以下
環境
[root@localhost ~]# gcc --version gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39) Copyright (C) 2015 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
ソース
#include <stdio.h> __attribute__((constructor)) void init_proc() { printf("attr\n"); } int main(void) { printf("start\n"); return; }
init_proc自体はmainからコールしてないので実行されなそうに見えるがattributeを付加しているのでmainより先に実行される。