LoginSignup
8
7

More than 5 years have passed since last update.

C, C++ のヘッダファイルの依存関係を rake で扱う

Last updated at Posted at 2012-12-26

rake + gcc で C や C++ のオブジェクトファイルとヘッダファイルの間の依存関係を扱うにはどうしたら良いかなーと試行錯誤して、 一つの解答にたどり着きました。オブジェクトファイルを生成するときに MMD オプションで依存関係を *.d ファイルに吐いておき、 2回目以降のコンパイルでは、それを rake から読み込んで利用します。

Rakefile
def get_headers(file)
  if File.exists?(file)
    File.read(file).gsub("\\\n ", "").scan(/^\S+: (.+)$/)
        .flatten.map {|s| s.split(' ') }.flatten
  else
    []
  end
end

# rule の場合は proc を通して
rule '.o' => ['%X.cpp',
              proc {|file| get_headers(file.pathmap('%X.d')) }] do |t|
  sh "#{GXX} #{CFLAGS} -c -o #{t.name} -MMD #{t.prerequisites[0]}"
end

# file の場合は直接
file 'myapp.o' => ['myapp.cpp', *get_headers('myapp.d')] do |t|
  sh "#{GXX} #{CFLAGS} -c -o #{t.name} -MMD #{t.prerequisites[0]}"
end
8
7
3

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