What does the include in the middle of code in C?

后端 未结 3 525
抹茶落季
抹茶落季 2021-01-14 05:13

Please, could you tell me what does the code below do?

...code...
#include file.h
...code...

I was used to put includes a the beggining of

3条回答
  •  情书的邮戳
    2021-01-14 05:42

    As everyone tells you #include can be used every where (provided it is on its own logicial line). And there are cases where you want to #include several times the same file. Read first the X macro wikipage, and the C preprocessor wikipage.

    And I have a concrete example in my MELT monitor (related to MELT ...).

    I have a predef-monimelt.h (generated) file containing lines like
    MOM_PREDEFINED_NAMED( name, id,hash) e.g.

    MOM_PREDEFINED_NAMED(GET,_9dsak0qcy0v_1c5z9th7x3i,1573018885)
    MOM_PREDEFINED_NAMED(HEAD,_47fatww79x6_vh8ap22c0ch,3922245622) 
    MOM_PREDEFINED_NAMED(web_handler,_7sav6zery1v_24sa6jwwu6c,2339220870)
    #undef MOM_PREDEFINED_NAMED
    

    My monimelt.h file (a real header file) define external pointers and an enum, so has notably:

    // declare the predefined
    #define MOM_PREDEFINED_NAMED(Name,Id,H) extern momitem_t* mom_named__##Name;
    #include "predef-monimelt.h"
    
    /// declare the hash of the predefined as an enum
    #define MOM_PREDEFINED_NAMED(Name,Id,H) mom_hashname__##Name = H,
    enum {
    #include "predef-monimelt.h"
    };
    

    My main.c file contains notably a routine :

      // if this routine is compiled, we are sure that all predefined hashes
      // are unique
      const momitem_t *
      mom_predefined_item_of_hashcode (momhash_t h) {
        switch (h) {
      #define MOM_PREDEFINED_NAMED(Nam,Id,Hash) case Hash: return mom_named__##Nam;
      #include "predef-monimelt.h"
        default:
        return NULL;
         }
      }
    

    but my items.c includes the predef-monimelt.h file twice (to create the predefined items at initialization, and to define their variables):

     void mom_create_predefined_items (void) {
       int nbnamed = 0;
     #define MOM_PREDEFINED_NAMED(Nam,Id,H) do { \
       mom_named__##Nam = mom_make_item_of_identcstr(#Id); \
       mom_named__##Nam->i_space = momspa_predefined; \
       mom_register_item_named_cstr (mom_named__##Nam, #Nam); \
       nbnamed ++; \
     } while(0);
     #include "predef-monimelt.h"
     } // end of mom_create_predefined_items
    
     // declare the predefined
     #define MOM_PREDEFINED_NAMED(Nam,Id,H) momitem_t* mom_named__##Nam;
     #include "predef-monimelt.h"
    

    FWIW, the MELT monitor is GPLv3+ licensed software

提交回复
热议问题