gpt4 book ai didi

c-preprocessor - 自定义条件预处理器指令

转载 作者:行者123 更新时间:2023-12-02 02:43:00 27 4
gpt4 key购买 nike

是否可以在 C 中编写自定义条件预处理器指令。例如;

#define _IF_ (condition, explanation) \
#ifdef condition

每条评论都会很棒,谢谢。

最佳答案

简单回答

没有。

#define 预处理器指令不能发出另一个预处理器指令(如 #ifdef),因为 #ifdef 不在行。

Preprocessing directives are lines in your program that start with #. The # is followed by an identifier that is the directive name. For example, #define is the directive that defines a macro. Whitespace is also allowed before and after the #.

我能得到的最接近优雅语法的是这个。

#define _IF_(condition,explanation) condition

#if _IF_(1 == 2,"A False Case")
"This should not appear"
#endif

#if _IF_(1 == 1,"A True Case")
"This should appear"
#endif

此处演示:https://godbolt.org/z/JFljOm

虽然这个宏可能有更好的标签。


简答

如果您出于某种原因确实需要获得此语法并且您愿意稍微修改您的构建系统。

您可以通过预处理器运行您的代码两次以允许这种双重扩展。但是,预处理器宏也不能发出 # 字符,因此我们将使用 ??= 三字母来规避这一点。

// File a.prec

#define _IF_(condition, explanation) \
??=if condition
#define _ELSE_ ??=else
#define _ENDIF_ ??=endif

_IF_(1==1,"Yep")
"This Text"
_ENDIF_

_IF_(2==1,"Nope")
"Not This Text"
_ENDIF_

只用 -E 标志编译给我们。 https://godbolt.org/z/sJIScN

??=if 1==1
"This Text"
??=endif

??=if 2==1
"Not This Text"
??=endif

然后我们需要在主要编译步骤中启用-trigraphs 以将??= 解析为#。为我们提供所需的输出: https://godbolt.org/z/-0rqe5

"This Text"

这个解决方案会给你带来正常包含的问题,因为使用预处理器两次是不安全的,所以你需要对任何你只想在正常的编译步骤。

关于c-preprocessor - 自定义条件预处理器指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58039759/

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