gpt4 book ai didi

ruby - Rakefile 中的 Makefile 等效行为

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:27 26 4
gpt4 key购买 nike

所以我现在正在学习 ruby 并发现了 rake。我喜欢通过实现我已经知道的东西来学习新工具,所以我尝试转换一个 Makefile 我必须 rake

假设它看起来像这样:

main: build/*.o
clang -c $^ -o $@

build/%.o: src/%.c | build
clang -c $< -o $@

build:
mkdir build

这个 Makefile 的特别之处是:

  1. 模式匹配%
  2. 仅使用订购依赖项|构建

有什么方法可以使用 rake 来实现这个逻辑,还是我必须使用 ruby 本身?例如

task :default => "main"

file "main" => "build/%.o" do
sh "clang -o 'main' ??"
end

file 'build/%.o' => "src/%.c" do # order only dependency on `build`
sh "clang -c ?? ??"
end

最佳答案

这是 rake 非常擅长的事情,但不幸的是未得到充分利用:

task :default => "main"

# This assumes that your "main" is created by linking
# all *.o files, each of which is the product of compiling a *.c file

# FileList[] creates a list of all *.c source files. The pathmap then
# changes the directory from /src/ to /out/ and the extension to .o

file "main" => FileList["src/**/*.c"].pathmap("%{^src,out}d/%n.o") do |t|
sh "ld #{t.sources.join(" ")} #{t.name}"
end

# This is the rule that says: if you need a
# file out/bla.o, this will create it from /src/bla.c.
rule /out\/.+.o/ => ->(target) { target.pathmap("%{^out,src}d/%n.c") } do |t|
sh "cp #{t.source} #{t.name}"
end

一些注意事项:

  • 规则名称可以是正则表达式。我相信 glob 样式模式也是可能的,但发现始终使用正则表达式更容易
  • 如果一个规则的目标已经存在,并且比它的所有源都新,它不会被再次执行(像 Make)
  • 路径映射和文件任务是文件名的 Rake 扩展。其他实体(例如数据库条目)没有任何相似之处,但您通常可以自己创建它们

关于ruby - Rakefile 中的 Makefile 等效行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38411376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com