OS/2 codes: How to writes initialization/termination codes with gcc

When programming, one of the most annoying things is to write initialization/termination codes. In case of DLL, OS/2 provides the opportunity for this by _DLL_InitTerm(). However, if it is a static library, OS/2 does not provide any ways for this. Instead, compilers provides its own ways for this.

Of course, gcc has its own ways. They are __attribute__((consturctor)) for intialization and __attribute__((destructor)) for termination. Here are the sample code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>

__attribute__((constructor))
static void before( void )
{
    printf("constructor : before()\n");
}

__attribute__((destructor))
static void after( void )
{
    printf("destructor : after()\n");
}

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

    return 0;
}


If you run this program,  you can see the following.

1
2
3
constructor : before()
main()
destructor : after()


However, be careful when linking DLL with customized _DLL_InitTerm(). The default codes of _DLL_InitTerm() are like this,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
unsigned long _System _DLL_InitTerm( unsigned long hmod, unsigned long flags )
{
    switch( flags )
    {
        case 0 :
            if( _CRT_init() == -1 )
                return 0;

            __ctordtorInit();
            break;

        case 1 :
            __ctordtorTerm();
            _CRT_term();
            break;

        default :
            return 0;
    }

    return 1;
}


By the way, sometimes __ctordotrInit() and __ctordotrTerm() are missed because C++ codes are not used. But without them, functions declared with __attribute__((constructor)) and __attribute__((destructor)) are not called. So if you write DLLs and use cutomized _DLL_InitTerm(), it would be a good habit to call __ctordtorInit() and __ctordtorTerm() regardless of using C++ codes.

댓글

이 블로그의 인기 게시물

토렌트: < 왕좌의 게임 > 시즌 1 ~ 시즌 8 완결편 마그넷

토렌트: < 스타워즈 > Ep.1 ~ Ep.6 마그넷

토렌트: NGC < 코스모스 > 우리말 더빙 전편(1편~13편) 마그넷