Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 months ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(21)
我最初的反应是
#ifdef
,当然,但我认为#if
实际上对此有一些显着的优势 - 原因如下:首先,你可以在预处理器和编译测试中使用
DEBUG_ENABLED
。 示例 - 通常,我希望在启用调试时有更长的超时时间,因此使用#if
,我可以这样写... 而不是 ...
其次,如果您想,您处于更好的位置从#define 迁移到全局常量。
#define
通常不被大多数 C++ 程序员所接受。第三,你说你的团队存在分歧。 我的猜测是,这意味着不同的成员已经采用了不同的方法,您需要标准化。 判定
#if
为首选意味着使用#ifdef
的代码即使在DEBUG_ENABLED
为 false 时也将编译并运行。 跟踪和删除不应该生成的调试输出比反之亦然要容易得多。哦,还有一个小的可读性问题。 您应该能够在
#define
中使用 true/false 而不是 0/1,并且由于该值是单个词法标记,因此这是您不需要在其周围添加括号的一次。代替
My initial reaction was
#ifdef
, of course, but I think#if
actually has some significant advantages for this - here's why:First, you can use
DEBUG_ENABLED
in preprocessor and compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using#if
, I can write this... instead of ...
Second, you're in a better position if you want to migrate from a
#define
to a global constant.#define
s are usually frowned on by most C++ programmers.And, Third, you say you've a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that
#if
is the preferred choice means that code using#ifdef
will compile -and run- even whenDEBUG_ENABLED
is false. And it's much easier to track down and remove debug output that is produced when it shouldn't be than vice-versa.Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your
#define
, and because the value is a single lexical token, it's the one time you don't need parentheses around it.instead of
他们俩都很丑。 相反,请执行以下操作:
然后,每当您需要调试代码时,请将其放入
D();
中。 而且您的程序不会被#ifdef
的可怕迷宫所污染。They're both hideous. Instead, do this:
Then whenever you need debug code, put it inside
D();
. And your program isn't polluted with hideous mazes of#ifdef
.#ifdef
只是检查是否定义了令牌,然后给出
#ifdef
just checks if a token is defined, giventhen
我们在多个文件中遇到了同样的问题,并且总是存在人们忘记包含“功能标志”文件的问题(对于超过 41,000 个文件的代码库,很容易做到)。
如果您有 feature.h:
但您忘记在 file.cpp 中包含头文件:
那么您就会遇到问题,在这种情况下,编译器将未定义的 COOL_FEATURE 解释为“false”,并且无法包含代码。 是的,gcc 确实支持一个会导致未定义宏错误的标志...但是大多数第 3 方代码要么定义要么不定义功能,因此这不是那么可移植。
我们采用了一种可移植的方法来纠正这种情况并测试功能的状态:函数宏。
如果您将上述 feature.h 更改为:
但是您再次忘记在 file.cpp 中包含头文件:
由于使用了未定义的函数宏,预处理器会出错。
We have had this same problem across multiple files and there is always the problem with people forgetting to include a "features flag" file (With a codebase of > 41,000 files it is easy to do).
If you had feature.h:
But then You forgot to include the header file in file.cpp:
Then you have a problem, the compiler interprets COOL_FEATURE being undefined as a "false" in this case and fails to include the code. Yes gcc does support a flag that causes a error for undefined macros... but most 3rd party code either defines or does not define features so this would not be that portable.
We have adopted a portable way of correcting for this case as well as testing for a feature's state: function macros.
if you changed the above feature.h to:
But then you again forgot to include the header file in file.cpp:
The preprocessor would have errored out because of the use of an undefined function macro.
出于执行条件编译的目的,#if 和 #ifdef 几乎相同,但不完全相同。 如果您的条件编译依赖于两个符号,那么 #ifdef 将不起作用。 例如,假设您有两个条件编译符号:PRO_VERSION 和 TRIAL_VERSION,您可能会遇到类似这样的情况:
使用 #ifdef 会使上述情况变得更加复杂,尤其是让 #else 部分正常工作。
我的代码广泛使用条件编译,我们混合使用了 #if 和 #if 。 #ifdef。 对于简单的情况,我们倾向于使用#ifdef/#ifndef,而每当评估两个或多个符号时,我们倾向于使用#if。
For the purposes of performing conditional compilation, #if and #ifdef are almost the same, but not quite. If your conditional compilation depends on two symbols then #ifdef will not work as well. For example, suppose you have two conditional compilation symbols, PRO_VERSION and TRIAL_VERSION, you might have something like this:
Using #ifdef the above becomes much more complicated, especially getting the #else part to work.
I work on code that uses conditional compilation extensively and we have a mixture of #if & #ifdef. We tend to use #ifdef/#ifndef for the simple case and #if whenever two or more symbols are being evaluation.
我认为这完全是风格问题。 两者实际上都没有比对方明显的优势。
一致性比任何特定选择都更重要,因此我建议您与团队一起选择一种风格并坚持下去。
I think it's entirely a question of style. Neither really has an obvious advantage over the other.
Consistency is more important than either particular choice, so I'd recommend that you get together with your team and pick one style, and stick to it.
我自己更喜欢:
因为它可以更轻松地创建寻找相反条件的代码,并且更容易发现:
与
I myself prefer:
Since it makes it easier to create code that looks for the opposite condition much easier to spot:
vs.
这是风格问题。 但我推荐一种更简洁的方法:
执行一次,然后始终使用 debug_print() 进行打印或不执行任何操作。 (是的,这两种情况都会编译。)这样,您的代码就不会因预处理器指令而出现乱码。
如果您收到警告“表达式无效”并且想要摆脱它,可以使用以下替代方法:
It's a matter of style. But I recommend a more concise way of doing this:
You do this once, then always use debug_print() to either print or do nothing. (Yes, this will compile in both cases.) This way, your code won't be garbled with preprocessor directives.
If you get the warning "expression has no effect" and want to get rid of it, here's an alternative:
#if
使您可以选择将其设置为 0 以关闭该功能,同时仍然检测开关是否存在。就我个人而言,我总是
#define DEBUG 1
,这样我就可以用 #if 或 #ifdef 捕获它#if
gives you the option of setting it to 0 to turn off the functionality, while still detecting that the switch is there.Personally I always
#define DEBUG 1
so I can catch it with either an #if or #ifdef#if 和#define MY_MACRO (0)
使用#if 意味着您创建了一个“define”宏,即将在代码中搜索的内容替换为“(0)”。 这是我讨厌在 C++ 中看到的“宏地狱”,因为它会通过潜在的代码修改来污染代码。
例如:
在 g++ 上给出以下错误:
只有一个错误。
这意味着您的宏已成功与 C++ 代码交互:函数调用成功。 在这个简单的例子中,它很有趣。 但我自己在代码中默默地使用宏的经验并不充满乐趣和满足,所以...
#ifdef 和 #define MY_MACRO
使用 #ifdef 意味着您“定义”某些东西。 并不是说你赋予它一个值。 它仍然是污染性的,但至少,它将被“替换为空”,并且不会被 C++ 代码视为合法的代码语句。 上面相同的代码,有一个简单的定义,它:
给出以下警告:
所以...
结论
我宁愿在代码中没有宏,但出于多种原因(定义标头保护或调试宏),我可以' t。
但至少,我喜欢让它们与我的合法 C++ 代码交互最少。 这意味着使用没有值的#define,使用#ifdef和#ifndef(甚至是吉姆·巴克建议的#if定义),最重要的是,给它们起这么长、这么陌生的名字,任何一个头脑清醒的人都不会使用它是“偶然”的,并且绝不会影响合法的 C++ 代码。
现在,当我重新阅读我的文章时
,我想知道我是否不应该尝试找到一些永远不会是正确的 C++ 的值来添加到我的定义中。 类似的东西
可以与 #ifdef 和 #ifndef 一起使用,但如果在函数内部使用,则不允许代码编译...我在 g++ 上成功尝试了这一点,它给出了错误:
有趣。
:-)
#if and #define MY_MACRO (0)
Using #if means that you created a "define" macro, i.e., something that will be searched in the code to be replaced by "(0)". This is the "macro hell" I hate to see in C++, because it pollutes the code with potential code modifications.
For example:
gives the following error on g++:
Only one error.
Which means that your macro successfully interacted with your C++ code: The call to the function was successful. In this simple case, it is amusing. But my own experience with macros playing silently with my code is not full of joy and fullfilment, so...
#ifdef and #define MY_MACRO
Using #ifdef means you "define" something. Not that you give it a value. It is still polluting, but at least, it will be "replaced by nothing", and not seen by C++ code as lagitimate code statement. The same code above, with a simple define, it:
Gives the following warnings:
So...
Conclusion
I'd rather live without macros in my code, but for multiple reasons (defining header guards, or debug macros), I can't.
But at least, I like to make them the least interactive possible with my legitimate C++ code. Which means using #define without value, using #ifdef and #ifndef (or even #if defined as suggested by Jim Buck), and most of all, giving them names so long and so alien no one in his/her right mind will use it "by chance", and that in no way it will affect legitimate C++ code.
Post Scriptum
Now, as I'm re-reading my post, I wonder if I should not try to find some value that won't ever ever be correct C++ to add to my define. Something like
that could be used with #ifdef and #ifndef, but not let code compile if used inside a function... I tried this successfully on g++, and it gave the error:
Interesting.
:-)
这根本不是风格问题。 不幸的是,这个问题也是错误的。 您无法从更好或更安全的意义上比较这些预处理器指令。
意思是“如果定义了宏”或“如果宏存在”。 宏的值在这里并不重要。 它可以是任何东西。
if 总是与一个值进行比较。 在上面的示例中,它是标准隐式比较:
#if 用法的示例,
您现在可以将 CFLAG_EDITION 的定义放入代码中
,也可以将宏设置为编译器标志。 另请参见此处。
That is not a matter of style at all. Also the question is unfortunately wrong. You cannot compare these preprocessor directives in the sense of better or safer.
means "if macro is defined" or "if macro exists". The value of macro does not matter here. It can be whatever.
if always compare to a value. In the above example it is the standard implicit comparison:
example for the usage of #if
you now can either put the definition of CFLAG_EDITION either in your code
or you can set the macro as compiler flag. Also see here.
第一个对我来说似乎更清楚。 与已定义/未定义相比,将其设置为标志似乎更自然。
The first seems clearer to me. It seems more natural make it a flag as compared to defined/not defined.
两者完全相同。 在惯用用法中,#ifdef 仅用于检查定义性(以及我在示例中使用的内容),而 #if 用于更复杂的表达式,例如 #if Defined(A) && !定义(B)。
Both are exactly equivalent. In idiomatic use, #ifdef is used just to check for definedness (and what I'd use in your example), whereas #if is used in more complex expressions, such as #if defined(A) && !defined(B).
向驱动程序指定条件定义的不同方式存在差异:
输出:
这意味着
-DA
是-DA=1
和 if value 的同义词被省略,那么在#if A
使用的情况下可能会导致问题。There is a difference in case of different way to specify a conditional define to the driver:
output:
This means, that
-DA
is synonym for-DA=1
and if value is omitted, then it may lead to problems in case of#if A
usage.我曾经使用#ifdef,但是当我切换到 Doxygen 进行文档记录时,我发现注释掉的宏无法被记录(或者至少 Doxygen 会产生警告)。 这意味着我无法记录当前未启用的功能开关宏。
尽管可以仅为 Doxygen 定义宏,但这意味着代码非活动部分中的宏也将被记录。 我个人想显示功能开关,否则仅记录当前选择的内容。 此外,如果有许多宏只有在 Doxygen 处理文件时才需要定义,这会使代码变得非常混乱。
因此,在这种情况下,最好始终定义宏并使用
#if
。I used to use
#ifdef
, but when I switched to Doxygen for documentation, I found that commented-out macros cannot be documented (or, at least, Doxygen produces a warning). This means I cannot document the feature-switch macros that are not currently enabled.Although it is possible to define the macros only for Doxygen, this means that the macros in the non-active portions of the code will be documented, too. I personally want to show the feature switches and otherwise only document what is currently selected. Furthermore, it makes the code quite messy if there are many macros that have to be defined only when Doxygen processes the file.
Therefore, in this case, it is better to always define the macros and use
#if
.我一直使用 #ifdef 和编译器标志来定义它......
I've always used #ifdef and compiler flags to define it...
或者,您可以声明一个全局常量,并使用 C++ if,而不是预处理器 #if。 编译器应该为您优化未使用的分支,这样您的代码就会更加干净。
这是C++ 陷阱 作者:Stephen C. Dewhurst说的是使用#if。
Alternatively, you can declare a global constant, and use the C++ if, instead of the preprocessor #if. The compiler should optimize the unused branches away for you, and your code will be cleaner.
Here is what C++ Gotchas by Stephen C. Dewhurst says about using #if's.
与许多事情一样,答案取决于情况。
#ifdef
对于保证在特定单元中定义或未定义的事物非常有用。 例如,包括警卫。 如果包含文件至少出现一次,则保证定义该符号,否则不定义。然而,有些事情并没有这样的保证。 考虑一下符号
HAS_FEATURE_X
。 存在多少个州?因此,如果您正在编写代码,尤其是共享代码,其中有些代码可能
#define HAS_FEATURE_X 0
表示功能 X 不存在,而其他代码可能只是没有定义它,那么您需要处理所有这些情况。#if !define(HAS_FEATURE_X) || HAS_FEATURE_X == 1
仅使用
#ifdef
可能会出现微妙的错误,即某些内容意外切换入(或切换出),因为某人或某个团队有将未使用的事物定义为 0 的约定在某些方面,我喜欢这种#if
方法,因为它意味着程序员主动做出了决定。 留下未定义的东西是被动的,从外部的角度来看,有时可能不清楚这是故意的还是疏忽的。As with many things, the answer depends.
#ifdef
is great for things that are guaranteed to be defined or not defined in a particular unit. Include guards for example. If the include file is present at least once, the symbol is guaranteed to be defined, otherwise not.However, some things don't have that guarantee. Think about the symbol
HAS_FEATURE_X
. How many states exist?So, if you're writing code, especially shared code, where some may
#define HAS_FEATURE_X 0
to mean feature X isn't present and others may just not define it, you need to handle all those cases.#if !defined(HAS_FEATURE_X) || HAS_FEATURE_X == 1
Using just an
#ifdef
could allow for a subtle error where something is switched in (or out) unexpectedly because someone or some team has a convention of defining unused things to 0. In some ways, I like this#if
approach because it means the programmer actively made a decision. Leaving something undefined is passive and from an external point of view, it can sometimes be unclear whether that was intentional or an oversight.它们都有不同的用途,
#if X
仅在满足以下条件时才会通过:定义了X
并且X
有一个值且该值不为零X
时才会通过They both serve different purpose,
#if X
will pass only if:X
is defined andX
has a value and the value is non zero#ifdef X
will pass only if:X
is defined当您可能需要多个级别的调试时,我喜欢
#define DEBUG_ENABLED (0)
。 例如:它使调试内存泄漏变得更容易,而无需让所有这些日志行妨碍您调试其他事情。
另外,定义周围的 #ifndef 使得在命令行中选择特定的调试级别变得更容易:
等等。
如果不是这样,我会优先考虑
#ifdef
,因为编译器/make 标志将被文件中的标志覆盖。 因此,您不必担心在提交之前更改回标头。I like
#define DEBUG_ENABLED (0)
when you might want multiple levels of debug. For example:It makes it easier to debug memory leaks, without having all those log lines in your way of debugging other things.
Also the
#ifndef
around the define makes it easier to pick a specific debug level at the commandline:etc.
If not for this, I would give advantage to
#ifdef
, because the compiler/make flag would be overridden by the one in the file. So you don't have to worry about changing back the header before doing the commit.有点题外话,但在 C++ 中使用预处理器打开/关闭日志记录绝对不是最佳选择。
有一些不错的日志记录工具,例如 Apache 的 log4cxx ,它们是开源的并且不受限制您如何分发您的应用程序。 它们还允许您更改日志记录级别而无需重新编译,如果您关闭日志记录,则开销非常低,并且使您有机会在生产中完全关闭日志记录。
A little off-topic, but turning on/off logging with the preprocessor is definitely sub-optimal in C++.
There are nice logging tools like Apache's log4cxx which are open-source and don't restrict how you distribute your application. They also allow you to change logging levels without recompilation, have very low overhead if you turn logging off, and give you the chance to turn logging off completely in production.