What if you want to modify Makefile content while building your code
Well, it’s possible. Let’s say we have directory with source code: main.cpp
tree . ├── Makefile └── main.cpp
Source code is supper simple.
int main() { return 0; }
What we want to do is to run Makefile and make sure that all occurrences of main will be changed to directory name (e.g. myCode).
All we have to do is to get location of Makefile, update it, store it inside other file and call that other file. In the meantime we can perform some source code manipulation as well.
makefilelocation = $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) makefiletarget = $(makefilelocation).target BASENAME := $(notdir $(CURDIR)) all: call $(warning "I will call myself") call: copy $(MAKE) -f $(makefiletarget) exe exe: main.cpp gcc -o main main.cpp copy: @cp main.cpp $(BASENAME).cpp @sed -e "s/main/$(BASENAME)/g" $(makefilelocation) > $(makefiletarget) clean: -rm $(BASENAME).cpp $(BASENAME) $(makefiletarget)
After execution of this Makefile we will have something like this
tree . ├── Makefile ├── Makefile.target ├── main.cpp ├── myCode └── myCode.cpp