跳至内容
Conditional Compilation (#ifdef, #ifndef, #else, #endif)

Conditional Compilation (#ifdef, #ifndef, #else, #endif)

条件编译 (#ifdef, #ifndef, #else, #endif)

预处理器条件编译指令允许根据特定条件的满足与否来编译或跳过程序的某部分。

该条件可以采取以下形式之一。

#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

任何条件编译指令都可以后接任意数量的行,这些行可能包含 #else 指令,并以 #endif 结束。如果条件满足,则 #else 和 #endif 之间的行将被忽略。如果条件不满足,则检查指令和 #else 指令(或者如果前者缺失则 #endif 指令)之间的所有行都将被忽略。

示例:

#ifndef TestMode
   #define TestMode
#endif
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   #ifdef TestMode
      Print("Test mode");
   #else
      Print("Normal mode");
   #endif
  }

根据程序类型和编译模式,标准宏的定义方式如下:

_MQL4__ 宏在编译 *.mq4 文件时定义,_MQL5__ 宏在编译 *.mq5 文件时定义。 _DEBUG 宏在调试模式下编译时定义。 _RELEASE 宏在发布模式编译时定义。

示例:

//+------------------------------------------------------------------+
//| 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
  }
最后更新于