Using #define to include another file in C++/C

后端 未结 4 1196
刺人心
刺人心 2020-12-15 20:57

I want to define a macro which includes another header file like so:

#define MY_MACRO (text) #include \"__FILE__##_inline.inl\"

So that whe

相关标签:
4条回答
  • 2020-12-15 20:58
    #if 0 /*Windows*/
    #define MKDIR_ENABLER <direct.h>
    #define MY_MKDIR(x,y) _mkdir((x))
    #else /*Linux*/
    #define MKDIR_ENABLER <sys/stat.h>
    #define MY_MKDIR(x,y) mkdir((x),(y))
    #endif
    
    #include MKDIR_ENABLER
    
    int main(void)
    {
        MY_MKDIR("more_bla",0644);
        return 0;
    }
    

    This code includes the appropriate header file for mkdir (because it's different on UNIX and Windows) and introduces a nice wrapper for it.

    0 讨论(0)
  • 2020-12-15 21:12

    You cannot use __FILE__ because that is already quoted, and #include doesn't support string concatenation. But you can use macros after #include:

    #define STRINGIZE_AUX(a) #a
    #define STRINGIZE(a) STRINGIZE_AUX(a)
    #define CAT_AUX(a, b) a##b
    #define CAT(a, b) CAT_AUX(a, b)
    #define MY_MACRO(file, name) STRINGIZE(CAT(file, CAT(name, _inline.inl)))
    #include MY_MACRO(aaaa, qqq)
    

    You should use the equivalent Boost.Preprocessor macros instead of CAT and STRINGIZE to prevent global namespace pollution.

    0 讨论(0)
  • 2020-12-15 21:18

    It's not possible to use #define to construct other preprocessor directives, unless you run the preprocessor twice.

    But in your case even running the preprocessor twice won't help because the #include must be a single string of the form "..." or <...>.

    0 讨论(0)
  • 2020-12-15 21:18

    You can't write other pre-processor directives using the pre-processor. However, I believe you could define just the file name:

    #define MY_MACRO(name) "__FILE__##name_inline.inl"
    
    #include MY_MACRO(name)
    

    The pre-processor runs multiple times until there are no further substitutions it can make, so it should expand the name first and then #include the referenced file.

    EDIT: I just tried it and the pre-processor can't handle the quotes like that.

    #define MY_MACRO(x) <__FILE__##x_inline.inl>
    #include MY_MACRO(foo)
    

    works OK, but <> may not be what you wanted.

    EDIT2: As pointed out by sth in comments, the __FILE__ does not expand correctly, which makes this probably not what you want after all. Sorry.

    0 讨论(0)
提交回复
热议问题