How to ignore a define directive?

1.8k views Asked by At

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.

2

There are 2 answers

6
Michele d'Amico On BEST ANSWER

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.

4
syntagma On

You wrote that preprocessor directives run before the other directives, so nothing is defined at that time.

In this case I think the only solution would be to preprocess the file before the preprocessor stage using your own script and change the defined values to something that would suit your needs and would not have impact on your code. I don't think there is any better solution.