macro definition containing #include directive

前端 未结 9 925
抹茶落季
抹茶落季 2020-12-08 06:55

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

相关标签:
9条回答
  • 2020-12-08 07:36

    C and C++ languages explicitly prohibit forming preprocessor directives as the result of macro expansion. This means that you can't include a preprocessor directive into a macro replacement list. And if you try to trick the preprocessor by "building" a new preprocessor directive through concatenation (and tricks like that), the behavior is undefined.

    0 讨论(0)
  • 2020-12-08 07:43

    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.

    0 讨论(0)
  • 2020-12-08 07:43

    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?

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