#包括任何地方

2022-01-25 00:00:00 include c++ c-preprocessor

#include <file> 是仅用于标头,还是只是机械的在此处注入此代码",可以在代码中的任何位置使用?

Is the #include <file> meant to be used for headers only or is it simply a mechanical "inject this code here" that can be used anywhere in the code?

如果我在 cpp 函数的中间使用它来从单一来源注入"代码会怎样?这会奏效还是编译器会为此大喊大叫?

What if I use it in the middle of a cpp function to just "inject" code from a single source? will this work or will compilers scream about this?

推荐答案

它是一个机械的在此处注入代码设备.如果您愿意,可以包含一个包含歌德浮士德的文本文件.你可以把它放在任何地方,甚至在函数的中间(当然,#include 需要换行!).

It is a mechanical inject the code here device. You can include a text file containing Goethe's Faust if you wish to. You can put it anywhere, even in the middle of a function (of course, #include needs a fresh line!).

但是,仅对头文件使用 #include 是一种严格的约定.可能有一些我不会反对的原因,例如提取机器生成的代码或将所有翻译单元合并到一个文件中.

However, it's strong convention to only use #include for header files. There may be reasons where I wouldn't object on it, for example pulling in machine-generated code or merging all translation units in a single file.

相关文章