Conditional Compilation (#ifdef, #ifndef, #else, #endif)
Preprocessor conditional compilation directives allow compiling or skipping a part of the program depending on the fulfillment of a certain condition.
That condition can take one of the following forms.
#ifdef identifier
// the code located here is compiled if identifier has already been defined for the preprocessor in #define directive.
#endif |
#ifndef identifier
// the code located here is compiled if identifier is not currently defined by #define preprocessor directive.
#endif |
Any of the conditional compilation directives can be followed by any number of lines possibly containing #else directive and ending with #endif. If the verified condition is true, the lines between #else and #endif are ignored. If the verified condition is not fulfilled, all lines between checking and #else directive (or #endif directive if the former is absent) are ignored.
Example:
#ifndef TestMode
#define TestMode
#endif
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
#ifdef TestMode
Print("Test mode");
#else
Print("Normal mode");
#endif
} |
Depending on the program type and compilation mode, the standard macros are defined the following way:
__MQL4__ macro is defined when compiling *.mq4 file, __MQL5__ macro is defined when compiling *.mq5 one.
_DEBUG macro is defined when compiling in debug mode.
_RELEASE macro is defined when compiling in release mode.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
#ifdef __MQL5__
#ifdef _DEBUG
Print("Hello from MQL5 compiler [DEBUG]");
#else
#ifdef _RELEASE
Print("Hello from MQL5 compiler [RELEASE]");
#endif
#endif
#else
#ifdef __MQL4__
#ifdef _DEBUG
Print("Hello from MQL4 compiler [DEBUG]");
#else
#ifdef _RELEASE
Print("Hello from MQL4 compiler [RELEASE]");
#endif
#endif
#endif
#endif
} |
|