问题描述
People recommend #ifdef
for conditional compilation by a wide margin. A search for #ifdef
substantiates that its use is pervasive.
还 #ifdef名称
(或等价的 #ifdefined(NAME)
和相关的 #ifndef NAME
(和 #if!defined(NAME)
)有一个严重缺陷:
Yet #ifdef NAME
(or equivalently #if defined(NAME)
and related #ifndef NAME
(and #if !defined(NAME)
) have a severe flaw:
#ifndef IS_SPECIAL
#error You're not special enough
#endif
source.cpp
source.cpp
#include "header.h"
显然会通过
#define IS_SPECIAL 1
#include "header.h"
但是,
#define IS_SPECIAL 0
#include "header.h"
错误的事情。而且一些C ++编译器传递了以 C 模式处理的文件(由于扩展名或命令行选项),从而有效地执行了 #define __cplusplus 0
。我见过当
which is quite the wrong thing to do. And some C++ compilers, passed a file processed in C mode (due to extension or command-line option) effectively do #define __cplusplus 0
. I have seen things break when
#ifdef __cplusplus
extern "C" {
#endif
/* ... */
#ifdef __cplusplus
}
#endif
是在 C 模式下处理的,其中 extern C
是无效的语法,因为 __ cplusplus
实际上是自动定义为 0
。
was processed in C mode, where extern "C"
is invalid syntax, because __cplusplus
was in fact automatically defined to 0
.
另一方面,此行为正确无误对于所有编译器:
On the other hand, this behaves correctly for all compilers:
#if __cplusplus
extern "C" {
#endif
/* ... */
#if __cplusplus
}
#endif
在这种情况下,为什么人们仍然使用 #ifdef
?他们是否只是不知道 #if
在未定义的名称上工作得很好?或者对于条件编译, #if
与 #ifdef
有实际的不利之处吗?
Why do people still use #ifdef
in this scenario? Are they simply unaware that #if
works perfectly fine on undefined names? Or is there an actual disadvantage to #if
vs #ifdef
for conditional compilation?
显然, #ifdef
确实具有有效的用法,例如提供可配置参数的默认值:
Obviously, #ifdef
does have valid uses, such as providing default values for configurable parameters:
#ifndef MAX_FILES
#define MAX_FILES 64
#endif
我只讨论标志测试的情况。
I'm only discussing the case of flag testing.
推荐答案
个人意见:从命令行进行控制稍微容易一些。与 -DOPTION = 1
相比,我更喜欢 -DOPTION
。
Personal opinion: it's marginally easier to control from the command line. I prefer -DOPTION
over -DOPTION=1
.
此外,名称的存在显然是二进制的。我不必处理{0,非零,未定义}。
Also, existence of a name is clearly binary. I don't have to be able to handle {0, non-zero, undefined}.
我不知道。这是什么语义?未定义的名称是否假定为0?我是否要向几乎不了解预处理器的人解释一下?
I wasn't aware. What are the semantics of this? Is an undefined name assumed to be 0? Do I want to have to explain that to the guy who barely understands the preprocessor to begin with?
对我来说,#ifdef /#ifndef 带来了明显的好处。
另外,我对这两种构造的主要用法是用于include警卫。使用 #ifndef
这种模式最干净。
To me, the binary nature of #ifdef/#ifndef
of name existence is a clarity benefit.Also, my primary usage of either construct is for include guards. That pattern is cleanest with #ifndef
.
这篇关于人们为什么使用#ifdef进行功能标志测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!