LoginSignup
12
12

More than 5 years have passed since last update.

自分をコンパイルするCのソース

Posted at

小さなプログラムを書いていると、コンパイラに渡すオプションとソースコードが別管理になっているのが不便に感じる。
そこで。

hello.c
#if 0
CC_OPTS="clang -std=c99 -Wall"
target = $0+".bin"
t0=File.exist?(target) && File.mtime(target)
puts %x( #{CC_OPTS} #{$0} -o #{target} )
t1=File.exist?(target) && File.mtime(target)
if t1 && ( !t0 || t0<t1 )
  puts %x(./#{target})
end
__END__
#endif
#include <stdio.h>

int main()
{
  puts( "hello, world!");
  return 0;
}

こんな風にして、これを ruby のプログラムとして実行する。
言語の設定を変えてもう一度貼ると:

hello.c[ruby]
#if 0
CC_OPTS="clang -std=c99 -Wall"
target = $0+".bin"
t0=File.exist?(target) && File.mtime(target)
puts %x( #{CC_OPTS} #{$0} -o #{target} )
t1=File.exist?(target) && File.mtime(target)
if t1 && ( !t0 || t0<t1 )
  puts %x(./#{target})
end
__END__
#endif
#include <stdio.h>

int main()
{
  puts( "hello, world!");
  return 0;
}

便利。
タイムスタンプをもう少しまじめに見た方がいいかなぁとか、出来上がるバイナリの名前がしょぼいとか、まあいろいろあるけれど。

12
12
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
12
12