macro definition containing #include directive

Viewed 47654

Is there a way to define a macro that contains a #include directive in its body?

If I just put the "#include", it gives the error

C2162: "expected macro formal parameter"

since here I am not using # to concatenate strings.
If I use "\# include", then I receive the following two errors:

error C2017: illegal escape sequence
error C2121: '#' : invalid character : possibly the result of a macro expansion

Any help?

9 Answers

I will not argue the merits for it, but freetype (www.freetype.org) does the following:

#include FT_FREETYPE_H

where they define FT_FREETYPE_H elsewhere

I believe the C/C++ preprocessor only does a single pass over the code, so I don't think that would work. You might be able to get a "#include" to be placed in the code by the macro, but the compiler would choke on it, since it doesn't know what to do with that. For what you're trying to do to work the preprocessor would have to do a second pass over the file in order to pick up the #include.

I think you are all right in that this task seems impossible as I also got from

http://groups.google.com/group/comp.lang.c++/browse_thread/thread/03d20d234539a85c#

No, preprocessor directives in C++ (and C) are not reflective.

Pawel Dziepak

Anyway, the reason behind this attempt is that I am trying to make the following repeatedly used code snippet as a macro:

void foo(AbstractClass object)
{
    switch (object.data_type())
    {
    case AbstractClass::TYPE_UCHAR :
        {
        typedef unsigned char PixelType;
        #include "snippets/foo.cpp"
        }
        break;
    case AbstractClass::TYPE_UINT:
        {
        typedef unsigned int PixelType;
        #include "snippets/foo.cpp"
        }
        break;
    default:
        break;
    }
}

For another task, I need to have a similar function

void bar(AbstractClass object)

where I will place

#include "snippets/bar.cpp"

and of course it is in "snippets/foo.cpp" and "snippets/bar.cpp" that the task-specific code is written.

Why would the macro need to have an #include? if you're #include'ing whatever file the macro is in, you could just put the #include above the macro with all the rest of the #include statements, and everything should be nice and dandy.

I see no reason to have the macro include anything that couldn't just be included in the file.

I have no idea what you are actually trying to do but it looks like what you might want is a templated function.

That way the PixelType is just a template parameter to the block of code.

Contagious is right -- if you're doing:

myFile.c:

#include "standardAppDefs.h"
#myStandardIncludeMacro

standardAppDefs.h:

#define myStandardIncludeMacro #include <foo.h>

Why not just say:

myFile.c:

#include "standardAppDefs.h"

standardAppDefs.h:

#include <foo.h>

And forget the macros?

Related