Phil Bouchard Phil Bouchard - 2 months ago 9
C Question

Howto partially preprocess a C file with specific working directory

I would like to expand include directives of a C file of my working directory only; not the system directory.

I tried the following:

gcc -E -nostdinc -I./ input.c


But it stops preprocessing when it fails to find the included system headers in input.c. I would like it to copy the include directive when it can't find it and keep preprocessing the file.

Answer Source

if your input.c file contains some system headers, it's normal that the preprocessor crashes when it cannot find them.

You could first use grep -v to remove all #include of system headers in your code, achieving something like this (list is non-exhaustive):

grep -vE "(stdio|stdlib)\.h" code.c > code_.c

you get for instance:

#define EXITCODE 0
int main(){
  int i = EOF;
  printf("hello\n");
  return EXITCODE;
}

then pre-process:

S:\c>gcc -E code_.c
# 1 "code_.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "code_.c"

int main(){
  int i = EOF;
  printf("hello\n");
  return 0;
}

note that the pre-processor doesn't care about functions or macros not defined. You get your code preprocessed (and your macros expanded), not the system ones.

You have to process all included files as well of course. That means an extra layer of tools to create temp source files and work from there.