4

How can I get the compiled version of my Crystal script to get its own __FILE__. Here is an example. I have a file called ~/test.cr with the following contents:

puts __FILE__

I compile the script via Crystal

~$ crystal ~/test.cr -o ~/test.compiled

Next I run ~/test.compiled. I produces the result

/Users/Account1/test.cr

even though the __FILE__ is actually

/Users/Account1/test.compiled

Is there a way to make it produce

/Users/Account1/test.compiled

Instead of

/Users/Account1/test.cr
Some Dinosaur
  • 154
  • 1
  • 14

1 Answers1

7

The meta constant __FILE__ always point to the source file, not the executable. However, you can use $0 to get the current executable path (or the full path using File.expand_path):

foo.cr:

puts $0
puts File.expand_path($0)

Then compile and execute:

$~ crystal build foo.cr
$~ ./foo
./foo
/Users/MyUser/foo
waj
  • 1,185
  • 10
  • 14
  • 3
    Also, `$0` is an alias for `PROGRAM_NAME` which is larger to type but more descriptive – waj Mar 17 '16 at 12:29