Managing projects with makefile
Makefiles are special format files that automatically build and manage your projects using make utility
Why we use Makefile?
1) Language independent — the only dependency you need is Make tool.
2) Simpler and cleaner base syntax for defining targets compared to a shell script.
Today there are many different flavors of Make tool on different systems. Linux by default uses the GNU Make, Windows needs to have it installed separately or if you’re using WSL — Windows Subsystem for Linux, you can get a GNU Make via most Linux distributions.
On macOS you can install and update it with
brew install make
Lets learn how make utility works
If you run the command
make
it will look for the file names as “Makefile” in your current directory and will run it
If you have multiple make files in the directory then you can run the specific file by this command
make -f myfile
There are multiple switches to the make file you can run the command
man make
to get more details
Lets Create a very simple make file in the root directory for any of your project
install:
composer installtest:
phpunitfoo:
echo “bar”
By default, Makefile needs tabs in front of the target commands. The install is the target name which can be executed from the command line with make install, and the next line(s) prefixed with a tab character define target steps.
To run the install target:
make install
same as if you want to run the tests then run this command
make test
Here are few components in make file
Character @
Every time you run the make file it also output the command to prevent it outputting the command you can add @ in front of the
command
Example :
install:
@composer install
Default goal
Whenever you run make without specifying the target name it will try to execute the first target. You can avoid this by setting a special variable .DEFAULT_GOAL:
.DEFAULT_GOAL := helphelp:
@echo “help needed”
Phony targets
Make is by default dedicated to generating executable files from their sources.All target names are by default the names of the files in the project folder. The built-in .PHONY target defines targets which should execute their recipes even if the file with the same name as target is present in the project.
When you’re adding a Makefile in your project you should define all custom targets as phony to avoid issues if file with same name is present in the project.
.DEFAULT_GOAL := help
.PHONY: test installhelp:
@echo “help needed”test:
@echo “Testing command here”install:
@echo “Installing command here”
Passing variables:
Some targets might require additional variables. With Make you can use arguments make foo arg=value.
.DEFAULT_GOAL := help
.PHONY: test install foohelp:
@echo “help needed”test:
@echo “Testing command here”install:
@echo “Installing command here”foo:
@echo $(arg)
@echo $(arg)
Then you can run it like this
make foo arg=bar
Reach me via twitter Mian Muhammad Asif Akhtar or email http://mianasif.info for any query