Conditional Compilation

Sometimes you might want to have a single library using specific API depending on the platform it is compiled on. At some other time, you might want to do some optimizations only if you turn a flag ON. For all that, you can use conditional compilation macros (AKA preprocessor macros).

Note that #define doesn't exist; for that, learn about Haxe Macros.

Here's an example of multiplaform code:

    #if flash8
    // Haxe code specific for flash player 8
    #elseif flash
    // Haxe code specific for flash platform (any version)
    #elseif js
    // Haxe code specific for javascript plaform
    #elseif neko
    // Haxe code specific for neko plaform
    #else 
    // do something else
        #error  // will display an error "Not implemented on this platform"
        #error "Custom error message" // will display an error "Custom error message"
    #end

There is also a not prefix, which is the exclamation mark. So for a block that is compiled for every plaform except for PHP, you can do:

    #if !php
    // This code is not for PHP!
    #end

In addition to the various platform defines, you can also detect if this is a debug-enabled build (set using -debug):

    #if debug
    trace("Debug infos for all debug compiles");
    #end

You can define your own variables by using the Haxe compiler commandline options (for example using -D mydebug):

    #if mydebug
    trace("Some personalized debug infos");
    #end

Logical and/or operators are also supported:

    #if (neko && mydebug)
    // Only for "mydebug" mode on Neko
    #end

    #if (flash || php)
    // Code that works for either flash or PHP
    #end

You can compile code based on an haxe compiler version :

#if haxe_210
    trace(" haxe version >= 2.10");
#else
    trace(" haxe version < 2.10");
#end

«« Optional Arguments | Inline »»

version #15766, modified 2012-12-05 21:10:02 by foobar