Generate include file name in a macro

前端 未结 3 2108
日久生厌
日久生厌 2020-12-05 23:43

I\'m trying to generate include file name in macro. This is supposed to be legal in C++:

#define INCLUDE_FILE \"module_impl_win.hpp\"
#include INCLUDE_FILE
<         


        
相关标签:
3条回答
  • 2020-12-06 00:35

    You can also use Boost Preprocessor, especially the BOOST_PP_STRINGIZE/BOOST_PP_CAT macros:

    #include <boost/preprocessor/cat.hpp>
    #include <boost/preprocessor/stringize.hpp>
    
    #define INCLUDE_FILE(M) BOOST_PP_STRINGIZE(BOOST_PP_CAT(M, _impl_win.hpp))
    
    // expands to: #include "module_impl_win.hpp"
    #include INCLUDE_FILE(module)
    

    (cf. C Macro - Dynamic #include)

    Note that this suffers from the same problem as @Andrew's answer (leading underscore = reserved identifier).

    0 讨论(0)
  • 2020-12-06 00:41

    The problem is that eventually your code would look like this:

    #include "module""_impl_win.hpp"
    

    This generates the same warning and error you are seeing but in a slightly more obvious way.

    While the compiler will accept that syntax, the preprocessor will not.

    I don't have a suggestion to make what you are trying to do work. Personally wouldn't want to use that type of macro since it makes it more difficult to navigate the code visually and it would likely inhibit many editors from quickly navigating the code.

    0 讨论(0)
  • 2020-12-06 00:46

    I'd do this using a helper quoting macro. Something like this will give you what you want:

    #define QUOTEME(M)       #M
    #define INCLUDE_FILE(M)  QUOTEME(M##_impl_win.hpp)
    
    #include INCLUDE_FILE(module)
    
    0 讨论(0)
提交回复
热议问题