使用#define定义没有值的常量的目的是什么?

时间:2014-04-08 16:43:48

标签: preprocessor

使用#define定义没有值的常量的目的是什么?

如:

#define TOKEN

2 个答案:

答案 0 :(得分:4)

您可以使用它来启用或禁用使用#ifdef#ifndef的某些代码,例如:

#ifdef TOKEN
    printf("token is defined");
#endif

这样做的一个用途是在调试版本中切换日志记录。另一个是include guards

答案 1 :(得分:0)

正如@Nutomic所说,这种#define对于启用/禁用某些代码位非常有用。我已经看到这用于为给定的库创建编译时选项:

#ifdef STRICT_PARSING
  //...
#endif

#ifdef APPROXIMATE_PARSING
  //...
#endif

#ifdef UNICODE //this is especially useful when trying to control Unicode vs ANSI builds
  //call Unicode functions here
#else
  //call Ansi functions here
#endif

#ifdef USE_STL //another good one, used to activate or deactivate STL-based bits of an API; the function declarations were dependent on USE_STL being defined. A plain-C API was exposed either way, but the STL support was nice too.
  std::string MyApi();
#endif