且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在包含文件中使用预处理器宏?

更新时间:2023-10-06 14:04:28

这是有效的C/C ++吗?

Is this valid C/C++?

用法有效C,前提是宏定义在 #include 指令出现时的作用域内.具体来说, C11的第6.10.2/4段说,

The usage is valid C, provided that the macro definition is in scope at the point where the #include directive appears. Specifically, paragraph 6.10.2/4 of C11 says

形式的预处理指令

A preprocessing directive of the form

# include pp-tokens new-line

允许

(与前两种形式之一不匹配).这包含在指令中的预处理令牌仅被处理像普通文字一样.(当前定义为宏名称的每个标识符被其预处理令牌的替换列表替换.)所有替换后产生的指令应与两者之一匹配以前的表格.

(that does not match one of the two previous forms) is permitted. The preprocessing tokens after include in the directive are processed just as in normal text. (Each identifier currently defined as a macro name is replaced by its replacement list of preprocessing tokens.) The directive resulting after all replacements shall match one of the two previous forms.

(添加了强调.)由于预处理器在C ++中的语义与C中的语义相同,据我所知,用法在C ++中也是有效的.

(Emphasis added.) Inasmuch as the preprocessor has the same semantics in C++ as in C, to the best of my knowledge, the usage is also valid in C++.

这些宏背后的原理是什么?

What is the rationale behind these macros?

我想它旨在提供标头名称或位置的间接指示(通过提供宏的替代定义).

I presume it is intended to provide for indirection of the header name or location (by providing alternative definitions of the macro).

我如何说服Clang解析这些标头?

How can I convince Clang to parse these headers?

再次提供该宏定义在 #include 指令出现时的作用域内,您无需执行任何操作.如果确实如此,那么Clang在这方面是错误的.在这种情况下,提交错误报告后(如果尚不知道此问题),您可能需要手动扩展麻烦的宏引用.

Provided, again, that the macro definition is in scope at the point where the #include directive appears, you shouldn't have to do anything. If indeed it is, then Clang is buggy in this regard. In that case, after filing a bug report (if this issue is not already known), you probably need to expand the troublesome macro references manually.

但是在执行此操作之前,请确保宏定义确实在范围内.特别是,它们可能受到条件编译指令的保护-在这种情况下,***的做法可能是(通过编译器命令行)提供满足条件所需的任何宏定义.如果希望您手动执行此操作,那么肯定会在构建文档中进行讨论.阅读构建说明.

But before you do that, be sure that the macro definitions really are in scope. In particular, they may be guarded by conditional compilation directives -- in that case, the best course of action would probably be to provide whatever macro definition is needed (via the compiler command line) to satisfy the condition. If you are expected to do this manually, then surely the build documentation discusses it. Read the build instructions.