Supposing I have:


#define foo 1
#define bar 1


#define foo 0

How can I generate a merged.h that looks like this, given I want app.h to redefine anything already defined in sdk.h:

#define foo 0
#define bar 1

One approach might be "don't do this, just let the preprocessor do it for you". I've tried that and it's not going to work for my situation I don't think. I'm really looking for an approach using a basic shell script.

  • 2
    Just include app.h after including sdk.h. If that doesn't work, then please update your question what exactly it is that goes wrong.
    – Kusalananda
    Aug 18, 2017 at 13:10
  • If it is only for handling the #define -s, then it could be easily implemented in some shellscript or maybe in awk/python/anything. However, if the first header uses some #define in it, then the result will be a lot of mystical errors. Furthermore, for anything more complex analyse, you need to essentially re-write the C preprocessor, which is not a funny task.
    – peterh
    Aug 18, 2017 at 13:32
  • does sort -k1,2 -u app.h sdk.h give you the correct results?
    – Jeff Schaller
    Aug 18, 2017 at 16:16

1 Answer 1


If the order of the contents in the header files is not important, you could do something like this:

$ awk '/#define/{a[$2]=$3; next}1;END{for(i in a){print "#define",i,a[i]}}' sdk.h app.h 
#define foo 0
#define bar 1

Note that any lines not containing #define will be printed first.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.