Skip to content

#If vs. If and Conditional Compilation

There was a curious question on the forums about what # meant.

And from the way it was asked I could see the asker was thinking “I know what If means but what about that # in front of it?” And that if they knew what the # meant that the entire thing would make more sense.

And that’s a fair thought – except for one problem. The # by itself doesn’t “mean” anything. It isn’t like *, ^, + or – in that sense. It’s not an operator.

#If isn’t just a special form of “if” with a # in front of it that behaves differently at runtime. #If is a completely different thing that only has meaning at the time your code is being compiled and will not exist in the final compiled code.

#If only has meaning to the compiler and can be used to include or exclude code from being sent to the compiler.

For instance if you have code like:

dim s as string
#if targetMacOS
 s = "macOS"
#endif

#if targetWindows
  s = "Windows"
#endif

msgbox s

Then when you run this code on a Mac you effectively get:

dim s as string
s = "macOS"
msgbox s

And the code for Windows hasn’t just been skipped – it doesn’t exist in the macOS version.

This is an enormously powerful and useful feature called conditional compilation and it can be used in all kinds of ways.

Conditional compilation lets you have a common API for code that actually has to be platform specific and to hide that platform specific requirement from the rest of the code that uses the method. You can read more about this in the Xojo Docs.