I have some C sources for which I want to expand #define
macros (and #ifdefs
and so on) but NOT #includes
. #includes
should be left untouched.
Is it possible by using the cpp (C preprocessor)?
I have some C sources for which I want to expand #define
macros (and #ifdefs
and so on) but NOT #includes
. #includes
should be left untouched.
Is it possible by using the cpp (C preprocessor)?
No, it isn't, since #include
is a preprocessor instruction.
The only possibility you have is to launch cpp on the files after having removed the #include
instructions.
If you have a Unix shell with GNU grep, this can be done, for instance, with:
grep -Pv '^\s*#\s*include\b' thefile.c|cpp
There is no direct way.. So I have tried the following program and it works for most of the .c
files that I have. I have taken @fge grep
and added some more code along with gcc -E
.. Hope this helps!
#!/bin/bash
if [[ $# -ne 1 || ! -f $1 ]] ; then
echo "Invalid args / Check file "
exit
fi
file_name=$1
grep '^\s*#\s*include' $file_name > /tmp/include.c
grep -Pv '^\s*#\s*include\b' $file_name > /tmp/code.c
gcc -E /tmp/code.c | grep -v ^# > /tmp/preprocessed.c
cat /tmp/include.c > $file_name.done
cat /tmp/preprocessed.c >> $file_name.done
If you have Emacs handy: c-macro-expand
bound to C-c C-e can expand only the marked the region. This will also take the includes into account but will limit the output of the command to the marked section. One of the best commands if you do macro programming.
If those included files looks like:
inc_file1.h
#if !defined(INC_FILE1_H)
#define INC_FILE1_H
/// some code
#endif
then you can define INC_FILE1_H yourself causing inc_file1.h inside declarations to not be processed
If you have one source file (or only a few), what you can do is to comment the #include
directives, for example:
#if 0
#include "include1.h"
#include "include2.h"
#endif
and then run the preprocessor on the source files.