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?
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?
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!).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.#include and other preprocessor directives like #define or #import, can appear anywhere in the source, but will only apply to the code after that inclusion. It is meant to include the referenced code into the source file that calls it. This MSDN page explains it quite well. http://msdn.microsoft.com/en-us/library/36k2cdd4(v=VS.71).aspx
It will work - more or less its semantic meaning is: place code in that file here
EDIT: For abusing usages of #include I can just recommend the following:
This allows for everything: a one-liner that can do everything, an error, its just a matter of compilation...
Not only does it work anywhere, but it can lead to some interesting techniques. Here's an example that generates an enumeration and a corresponding string table that are guaranteed to be in sync.
Animals.h:
AnimalLibrary.h:
AnimalLibrary.cpp:
main.cpp:
Be sure not to put the usual include guards in any file that will be included multiple times!
Gotta agree with William Pursell though that this technique will have people scratching their heads.
Compilers will not complain, but everyone who has to maintain the code will.
Should work, it's processed by your preprocessor, your compiler won't even see it.