Search code examples
cgccc-preprocessorpragma

How to ignore a define directive?


I have the following problem. I'm writing C code that is dependent on someone else's code, which I am not able to make changes to. And in that code (that I'm not allowed to change) is a define preprocessor directive. My code is compiled before this other piece of code. And I need a way to circumvent this, so that my code is not affected by this define directive.

Is there a way to somehow tell the preprocessor to ignore all directives from now on?

What almost worked for me was the following pragma poison directive, but this unfortunately throws an error. Is there a way to suppress this error?

#pragma GCC poison define

I know that this is not an easy question to answer, but I'll really appreciate some help.


Solution

  • I think that you can do something like this: Assume that the problem is that the other code define string as char * and somewhere in the headers you need to include. You can define in your c files after the includes from the other code just:

    #ifdef string
        #undef string
    #endif
    

    If your code include every times the same headers you can put all includes in one header and sanitize it at end: An example could be other_include.h:

    #ifndef _OTHER_INCLUDE_H
    #include <otherheader_a.h>
    #include <otherheader_b.h>
    #include <otherheader_c.h>
    
    /*Sanitize string definition */
    
    #ifdef string
        #undef string
    #endif
    #endif /* _OTHER_INCLUDE_H */
    

    If you are not so lucky you must create a sanitize.h header and include it after all other include in your c files.

    Moreover If you need some portion of code where disable the macro and recover it after :

    #ifdef string
        #define _temp_string string
        #undef string
    #endif
    

    and when you want recover it

    #ifdef _temp_string
        #define string _temp_string
        #undef _temp_string
    #endif
    

    That not really elegant but you can use it as a fine grain to make your subroutine safe.