Help us understand the problem. What is going on with this article?

pragma(crt_constructor) を試してみる

More than 1 year has passed since last update.

これはD言語アドベントカレンダー2017の記事です(は????)

DMD 2.078でC runtime construction and destructionが入りました ね。これはGCC拡張の __attribute__((constructor)), __attribute__((destructor)) 相当のもので、実装もそうなっているんですが、実際に同じように振る舞うのかちょっと気になりますよね。GCC拡張でよく使われている(????)テクニックを実践してみました。

1. mainの2回呼び出し

import core.stdc.stdio;

extern(C):

pragma(crt_constructor)
int main()
{
    puts("C main");
    return 0;
}
  • 実行結果
(dmd-2.078.0)$ rdmd -betterC adc1.d
C main
C main

2. mainを変数にする

import core.stdc.stdio;
import core.stdc.stdlib : exit;

extern(C):

__gshared int main = 0;

pragma(crt_constructor)
void init()
{
    printf("hello, ");
    exit(0);
}

pragma(crt_destructor)
void fini()
{
    puts("world!");
}
  • 実行結果
(dmd-2.078.0)$ rdmd -betterC adc2.d
hello, world!

'main' is usually function がでないのが悲しいですね。

できないこと

DMD限定だとsectionいじって .text にmainを置くとか __attribute__((cleanup(hoge))) みたいなのはまだ使えないです。LDCとかGDCとかだとsectionは普通にできるはず。GDCはcleanupも使えるのかな、よくわかんないです。まだすべてのトリックが使えるというわけではなですが、なんかおもしろそうな材料が増えてよかったですね。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away