LoginSignup
2
0

More than 1 year has passed since last update.

C言語でプログラムの開始時と終了時に何かを実行する方法

Posted at

ctorsはconstructors、dtorsはdestructorsの略称です.
exitを呼ぶと、

  1. _fini -> do_dtors
  2. _exit
    • プロセスが消滅するので、printf("never\n")は実行されません.

等が実行されます.

_finicrt1.c:_startatexit(_fini)している.
atexitで登録された関数はプログラムの終了時に呼ばれます.

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

int count = 0;

void init1()
{
    count++;
    printf("ctors test. (init1)\n");
}

void init2()
{
    count++;
    count++;
    printf("ctors test. (init2)\n");
}

void fini1()
{
    printf("dtors test. (fini1)\n");
}

void fini2()
{
    printf("dtors test. (fini2)\n");
}

void fini3()
{
    printf("atexit test. (fini3)\n");
}

void (*fp1) (void) __attribute__((section(".ctors"))) = init1;
void (*fp2) (void) __attribute__((section(".ctors"))) = init2;
void (*fp3) (void) __attribute__((section(".dtors"))) = fini1;
void (*fp4) (void) __attribute__((section(".dtors"))) = fini2;

int main()
{
    atexit(fini3);
    printf("%d\n", count);
    exit (0);
    printf("never\n");
}
$ clang ctors.c
$ ./a.out
ctors test. (init2)
ctors test. (init1)
3
atexit test. (fini3)
dtors test. (fini1)
dtors test. (fini2)
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0