#include anywhere

2019-02-04 16:06发布

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?

7条回答
成全新的幸福
2楼-- · 2019-02-04 16:27

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.

查看更多
淡お忘
3楼-- · 2019-02-04 16:28

#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

查看更多
倾城 Initia
4楼-- · 2019-02-04 16:41

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:

#include "/dev/console"

This allows for everything: a one-liner that can do everything, an error, its just a matter of compilation...

查看更多
霸刀☆藐视天下
5楼-- · 2019-02-04 16:44

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:

ANIMAL(Anteater)
ANIMAL(Baboon)
...
ANIMAL(Zebra)

AnimalLibrary.h:

#define ANIMAL(name) name,

enum Animals {
#include "Animals.h"
        AnimalCount
    };

#undef ANIMAL

extern char * AnimalTable[AnimalCount];

AnimalLibrary.cpp:

#include "AnimalLibrary.h"

#define ANIMAL(name) #name,

char * AnimalTable[AnimalCount] = {
#include "Animals.h"
    };

main.cpp:

#include "AnimalLibrary.h"

int main()
{
    cout << AnimalTable[Baboon];
    return 0;
}

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.

查看更多
做个烂人
6楼-- · 2019-02-04 16:46

Compilers will not complain, but everyone who has to maintain the code will.

查看更多
Fickle 薄情
7楼-- · 2019-02-04 16:50

Should work, it's processed by your preprocessor, your compiler won't even see it.

查看更多
登录 后发表回答