What's the best way to programmatically create a header file for another project?

Here's the specific use case: one program fingerprints the device for discrete information like version number, id string, etc, and then creates a header file populating static structs/program constants. This header file is then consumed by multiple projects to define a type of that class.

I thought about reading writing in an xml or flat file, that means consuming projects need to know that structure of the and plug in libraries to read it.

  • 1
    I think this is better suited for SO. – Mahmoud Hossam Apr 29 '11 at 21:17
  • 1
    This question is fine here: Programmmers.SE is about write-boarding ideas. There's nothing about this question that involves getting into code. – user8 Apr 29 '11 at 21:32
  • These things can be done with a macro language like m4 which is very well suited to generate files from templates. – Martin Wickman Apr 29 '11 at 21:55

If you're building on *NIX (Unix, Linux, or OSX), a common approach is to have a make rule that converts a .h.in to .h using sed (or perl). The implementation would vary on Windows, but what you should be aiming at is



Your fingerprinting tool (or a wrapper around it) then does simple text replacement, so you end up with

#define VERSION 2.3.4
#define COPYRIGHT "(C) 2011 Stack Overflow"
#define SOMETHING_ELSE "A bucket of fish"

You could use Ant to do replacements (although Ant isn't really the right tool for C programming)

Depending on what exactly you're fingerprinting, automake/autoconf might be worth investigating - on Windows you may need to run these under MinGW or cygwin.

Using a template like this means you can leave any header comments, macro definitions, etc. in the header template.

  • They often use m4 for this. It has a learning curve, but works out well in the long run. en.wikipedia.org/wiki/M4_(computer_language) – S.Lott Apr 29 '11 at 22:28
  • m4 is usually used to generate code that then uses sed to create the macros, actually. – alternative Apr 30 '11 at 0:51
  • Thanks, that's something like I was angling towards. The project is to poll a usb device, and produce a set of pre-populated #defs and structs which describe the device (e.g. hw id, transfer rate, etc) in a single file. You can then include that file in any number of projects, e.g. in Teensy usb programming projects. – Sorcerer13 May 3 '11 at 18:53

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.