首页 > 解决方案 > Why is it sometimes valid to write an include statement in a codeblock?

问题描述

I amcoming from a python background, where the following is valid:

def f():
    import someLibrary
    someLibrary.libraryFunction()

So when I needed to debug C code, I wrote, in the middle of my function:

void f(int param)
{
     int status;
     /* other code */
     #include <stdio.h>
     printf("status: %d", status);
     /* more code */
}

And it compiled and worked as I expected. Later it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include~ statement with the contents ofstdio.h`. So why was this valid code?

标签: cinclude

解决方案


有人向我指出这不应该编译,因为 C 预处理器实际上用stdio.h 的内容替换了#include 语句。

这上面的逻辑没有道理。仅仅因为预处理器从stdio.h文件中插入文本并不意味着它不应该编译。如果该文件中没有任何会导致编译错误的内容,那么它将编译得很好。

此外,标头中通常有一个多重包含保护。因此,如果它们之前已经包含在内,则任何进一步尝试包含它都无效。在这种情况下,如果<stdio.h>之前已经包含在文件中(直接或间接),则#include将无效。

话虽如此,但不要这样做。在 C 中,标准头文件不应该包含在函数范围内。


推荐阅读