编译时获取导入文件的文件路径

Get filepath of importing file at compile time

如果我有一个其他文件需要的文件,是否可以获取需要它的文件的绝对文件路径?

因此,如果 lib_file.cr 有一个宏,打算由导入它的 app_file.cr 调用,那么该宏能否在编译时发现 app_file.cr 的文件路径?

我试过这样的东西:

macro tester
  puts __DIR__
  puts __FILE__
end

但是当从执行要求的文件中调用时,它在编译时什么也没给出,而在运行时:

?
expanded macro: app_file

如果我将宏更改为:

macro tester
  {{puts __DIR__}}
  {{puts __FILE__}}
end

它在编译时给了我这个:

"/home/user/Documents/crystal_test/lib_file"
"/home/user/Documents/crystal_test/lib_file.cr"

那么有什么技巧可以在编译时在lib_file.cr中获取到app_file.cr的完整路径吗?

您可以使用带有 __FILE__ 的默认参数来获取调用宏的文件。

macro tester(file = __FILE__)
  {{puts file}} # Print at compile time
  puts {{file}} # Print at runtime
end