1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Does the solution to [How do I run the preprocessor on local headers only?](https://stackoverflow.com/questions/20889460/) help? It is an answer to a C++ question, but the ideas (and scripts) work directly with C code too. – Jonathan Leffler Aug 20 '17 at 20:31
  • My own solution [below](https://stackoverflow.com/a/45786694/7392560) is much simpler because I don't need to create empty files, etc. – Phil Bouchard Aug 20 '17 at 23:44
  • Yes, if you have Haskell installed on your machine, or you find a pre-built copy, then it may well be better to use `cpphs`. – Jonathan Leffler Aug 21 '17 at 00:39

2 Answers2

1

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

I found a utility that does exactly what I was looking for:

$ cpphs --nowarn --nomacro -I./ input.c | sed -E 's|#line 1 "missing file: (.*)"|#include <\1>|'