Generate include file name in a macro
I'm trying to generate include file name in macro. This is supposed to be legal in C+开发者_如何学Go+:
#define INCLUDE_FILE "module_impl_win.hpp"
#include INCLUDE_FILE
this works fine, but as soon as I try to generated file name it failes to compile
#define INCLUDE_FILE(M) M##"_impl_win.hpp"
#include INCLUDE_FILE("module")
Actually it gives me warning on MSVC2010
warning C4067: unexpected tokens following preprocessor directive - expected a newlin
but it doesn't include the file.
What is the problem? How can I get rid of it?
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)
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).
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.
精彩评论