问题描述
我在学习C之前遇到了 #define
预处理器指令,然后在一些读取的代码中遇到它。但除了使用它来定义常量的替换和定义宏,我没有真正低估的特殊情况下,它使用没有一个身体或令牌字符串。
I have encountered the #define
pre-processor directive before while learning C, and then also encountered it in some code I read. But apart from using it to definite substitutions for constants and to define macros, I've not really understook the special case where it is used without a "body" or token-string.
以这一行为例:
#define OCSTR(X)
就这样!什么是使用这个或更好,什么时候使用 #define
必要?
Just like that! What could be the use of this or better, when is this use of #define
necessary?
推荐答案
这在两种情况下使用。第一个和最常见的涉及
条件编译:
This is used in two cases. The first and most frequent involvesconditional compilation:
#ifndef XYZ
#define XYZ
// ...
#endif
但是它也可以是
用于像系统依赖的东西:
You've surely used this yourself for include guards, but it can also beused for things like system dependencies:
#ifdef WIN32
// Windows specific code here...
#endif
更可能在命令行上定义,但
也可以在config.hpp
文件中定义。)这通常
只涉及对象类宏(没有参数列表或
括号)。
(In this case, WIN32 is more likely defined on the command line, but itcould also be defined in a "config.hpp"
file.) This would normallyonly involve object-like macros (without an argument list orparentheses).
第二个是条件编译的结果。某事
like:
The second would be a result of conditional compilation. Somethinglike:
#ifdef DEBUG
#define TEST(X) text(X)
#else
#define TEST(X)
#endif
允许写如下内容:
TEST(X);
将调用 DEBUG
如果
不是,则不执行任何操作。
which will call the function if DEBUG
is defined, and do nothing if itisn't.
这篇关于什么用例需要#define没有令牌字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!