#include anywhere

后端 未结 7 1044
心在旅途
心在旅途 2020-12-15 08:55

Is the #include 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?

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 09:57

    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.

提交回复
热议问题