Wednesday, March 23, 2011

Make the C preprocessor ignore certain #include directives

Hi folks!

I use a parser generator here, that unfortunately insists on putting a

#include <some/file.h>

at the top of every generated source file. The header has since long been renamed. While it is no problem forcing the compiler (gcc) to use the new header with -include new/header.h, removing the above directive from every generated file complicates the build-process.

Is there a way to tell gcc to simply ignore some/file.h?

From stackoverflow
  • Replace some/file.h with an empty file.

    edgar.holleis : No, because it's a system header. But with -I. it's possible to make gcc find it anyway. Thanks.
  • No. You can post-process your generated file - I say: NO!!!

    Or you can just add '.' to your system include directories (or whatever your local include path is - make sure it's also a <> system include path).

    Then make a 'some' directory and stick your own permanent 'file.h' in there that has 1 line for #include and get rid of your -include.

    I'm guess there's some reason that might not work - cause it seems like the more straight forward and understandable thing to do before using -include. Especially since you can comment the pass-through file to explain what's going on.

  • Why not make a symlink from some/file.h to new/header.h, and remove the -include directive?

    edgar.holleis : Because it used to be a system header living in /usr/include. It shouldn't be necessary to modifie /usr/include just to compile some app.
  • #include <some/file.h>
    

    may start as something like

    #ifndef _FILE_H_
    #define _FILE_H_
    

    If so, just add #define _FILE_H_ before the #include command and it should ignore it. I'm not sure whether this is the best solution, though.

    edgar.holleis : For that to work it would have to find some/file.h first.
  • Try using preprocessor directives like #if and #ifdef and gcc -DSYMBOL=value command line flag.

    In example, if you compile using *gcc -DREQUIRE_STDC=1 -o myfile.o myfile.c*, and your .c file contains:

    
    
    #if defined(REQUIRE_STDC) && defined(__STDC__)
    #include "some/file.h"
    #else
    #include "another/file.h"
    #endif /* defined(REQUIRE_STDC) && defined(__STDC__) */
    
    

    It will compile using "some/file.h" if have both STDC and REQUIRE_STDC symbols defined. Also your header may include the proper directive to avoid multiple inclusions of the same file:

    
    
    #ifndef MY_HEADER_FILE
    #define MY_HEADER_FILE 1
    
    /* your C declarations here */
    
    #endif /* MY_HEADER_FILE */
    
    

    Also, you could the gcc preprocessor manual.

    edgar.holleis : Thats possible for normal source files. In my case the source is generated on the fly and I don't have the necessary control over its resulting output.

0 comments:

Post a Comment