c - 为什么预处理器不扩展代码中稍后定义的类型

标签 c

我的问题相对简单,但对我来说却很神秘。

处理后,BLA_Str 不会扩展为 bla_Str。情况是这样的:

#include <stdio.h>
#include <stdint.h>

typedef BLA_Str blaInstance;

#define BLA_Str bla_Str

typedef struct 
{
   int bla;
}bla_Str;

void main(void){
//  printf("%u\n\r",5);
} 

最佳答案

预处理器仅执行一次文件遍历,扩展宏,并在遇到#define时将宏添加到其列表中。当到达终点线时

typedef BLA_Str blaInstance

它还不知道 BLA_Str 宏,因此它在输出中保持不变。

您通常应该将所有 #define 行放在开头,这样它们就会影响文件其余部分的所有内容。

您可以在 The C Book 中找到有关 C 预处理器工作原理的合理总结。 。它解释说:

There are two ways of defining macros, one of which looks like a function and one which does not. Here is an example of each:

   #define FMAC(a,b) a here, then b
   #define NONFMAC some text here

Both definitions define a macro and some replacement text, which will be used to replace later occurrences of the macro name in the rest of the program.

如果一个宏扩展为另一个宏,则通过重新扫描来处理:

Once the processing described above has occurred, the replacement text plus the following tokens of the source file is rescanned, looking for more macro names to replace. The one exception is that, within a macro's replacement text, the name of the macro itself is not expanded.

关于c - 为什么预处理器不扩展代码中稍后定义的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37225894/

相关文章:

c - 只有一个消息传递应用程序实例接收消息

c - 我应该如何通过免费传递 const char 指针来释放 char 指针?

c - 链表的问题

c - 线程完成后如何继续运行进程?

c - 由于对齐而在 C 结构中查找孔

c - 用户输入字符串到数组中,导致缓冲区溢出

c - 斐波那契数列

c - 库中的链接器脚本变量阻止动态链接

c - 函数中使用的 malloc 范围

python - 在Python中从C中读取带头的二进制数据