gpt4 book ai didi

c++ - 为什么人们使用#ifdef 进行功能标志测试?

转载 作者:IT老高 更新时间:2023-10-28 22:41:30 47 4
gpt4 key购买 nike

recommend #ifdef for conditional compilation by a wide margin .一个 search for #ifdef证明它的使用是普遍的。

#ifdef NAME (或等效的 #if defined(NAME) 和相关的 #ifndef NAME (和 #if ! defined(NAME)) 有一个严重的缺陷:

header.h

#ifndef IS_SPECIAL
#error You're not special enough
#endif

source.cpp

#include "header.h"

gcc -DIS_SPECIAL source.cpp

很明显,会过去的

source1.cpp

#define IS_SPECIAL 1
#include "header.h"

但是,会的

source0.cpp

#define IS_SPECIAL 0
#include "header.h"

这是完全错误的做法。而一些 C++ 编译器,通过在 C 模式下处理的文件(由于扩展名或命令行选项)有效地执行 #define __cplusplus 0。我见过东西坏了

#ifdef __cplusplus
extern "C" {
#endif
/* ... */
#ifdef __cplusplus
}
#endif

C 模式下处理,其中 extern "C" 是无效语法,因为 __cplusplus 实际上是自动定义为 0.

另一方面,这对于所有编译器都是正确的:

#if __cplusplus
extern "C" {
#endif
/* ... */
#if __cplusplus
}
#endif

为什么人们在这种情况下仍然使用 #ifdef?他们是否根本不知道 #if 在未定义的名称上工作得很好?或者 #if#ifdef 在条件编译方面是否存在实际劣势?


显然,#ifdef 确实有有效用途,例如为可配置参数提供默认值:

#ifndef MAX_FILES
#define MAX_FILES 64
#endif

我只讨论标志测试的情况。

最佳答案

Why do people still use #ifdef in this scenario?

个人意见:从命令行控制稍微容易一些。我更喜欢 -DOPTION 而不是 -DOPTION=1

此外,名称的存在显然是二元的。我不必能够处理 {0, non-zero, undefined}。

Are they simply unaware that #if works perfectly fine on undefined names?

我不知道。这有什么语义?未定义的名称是否假定为 0?我是否需要向一开始几乎不了解预处理器的人解释这一点?

Or is there an actual disadvantage to #if vs #ifdef for conditional compilation?

对我来说,名称存在的 #ifdef/#ifndef 的二进制性质是一个清晰的好处。另外,我对这两种结构的主要用途是包含 guard 。该模式使用 #ifndef 最为简洁。

关于c++ - 为什么人们使用#ifdef 进行功能标志测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21272744/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com