Monday, January 16, 2012

How to make a makefile

Sometimes a part of makefile needs to be dynamically generated. Instead of doing it prior to running make you can do a cool trick with GNU Make. You can just usually write the rule how to generate dynamic makefile and define dependencies and the recipe.

dynamic.mk: generate.sh config_file.xml
$< > $@

include dynamic.mk

A bit of explanation $< is the first prerequisite $@ is the target being made and the > is the normal bash redirection of standard output to file. So the second line is equivalent to:
generate.sh > dynamic.mk

When make encounters an include directive of a makefile it tires to look up the rules to update it as a target. It will remake any that are out of date or don't exist (issuing a warning for the non-existent ones).

You can define dependencies when the dynamic part of the makefile needs to be remade and when it is up to date. This way make itself ensures that makefiles are up to date.

No comments: