The Crystal Programming Language Forum

Conditional code and user defined compile time flag

Hi,
I want to conditionally compile parts of code based on a flag defined at the compiler command line.
Something like
p! myvar if flag==DEBUG
with the command
crystal build -D DEBUG myfile.cr
But this does not work :cry:
What is the proper syntax to do that ?
Thanks

{% if flag? :debug %}
  p! myvar
{% end %}

You could probably just tap into the existing debug flag that gets added when you use --debug.

1 Like

Thank you for your example: it works fine.
So, I investigated further and found that p! myvar if {{ flag? DEBUG }} is shorter !
:debug also works, but has a reverse behavior, because it is enabled by default, so you have to use the --no-debug flag to stop compiling debugging code.

Ah, fair enough.

Yes it’s shorter, but to be clear that is not the same thing as my code. What you have is essentially expanding to p! myvar if false. I.e. the debug statement is still included in the binary, and is executed/checked when you run your program. However, with my code the debug statements are not included in the built binary if you’re not in debug mode.

Regardless, is it possible that the Log module would be better for what you want to do? Depending on your exact use case…

Ah, interesting difference, indeed.
Thanks

I also found that {% is interpreted within a string. I wonder if this is normal or not.
This code compiles Ok

{% if flag? :debug %}
  puts "\{%s}" % "abc" 
{% end %}

but not this one.

{% if flag? :debug %}
  puts "{%s}" % "abc" 
{% end %}

With the note that the compiler will remove if false branches at compile time… so they are almost equivalent.