multiple makefiles in one directory

Makefile

Makefile Problem Overview


I have a makefile in a directory of mine which builds scripts with certain environment variables set. What if I want to create another makefile in the same directory with different environment variables set? How should I name the two make files? Does makefile.1 and makefile.2 work? How do I call them?

Makefile Solutions


Solution 1 - Makefile

You can give sensible names to the files like makefile.win and makefile.nix and use them:

make -f makefile.win
make -f makefile.nix

or have a Makefile that contains:

win:
  make -f makefile.win

nix:
  make -f makefile.nix

and use make win or make nix

Solution 2 - Makefile

You can name makefile whatever you want. I usually name it like somename.mk. To use it later you need to tell make what makefile you want. Use -f option for this:

make -f somename.mk

Solution 3 - Makefile

Actually you can have two set of environment variables in the same make file. for example

COMPILER = gcc
CCFLAGS1 = -g
CCFLAGS2 = -Wall

a: main.c
        ${COMPILER} ${CCFLAGS1} main.c
b: test.c
        ${COMPILER} ${CCFLAGS2} test.c

then you can just say make a or make b. Depending on what you want.

Also it is possible with -f flag to call which makefile you want to call.

Solution 4 - Makefile

You can do something like this rather than using multiple makefiles for the same purpose. You can pass the environment or set a flag to the same makefile. For eg:



ifeq ($(ENV),ENV1)
 ENV_VAR = THIS
else
 ENV_VAR = THAT
endif

default : test

.PHONY : test
test:
        @echo $(ENV_VAR)





Then you can simply run the make command with arguments



make ENV=ENV1





Solution 5 - Makefile

I have two makefiles in the same directory. Many of the recipes have identical names and here are two solutions:

1. Prefix in make
proja_hello:
           @echo "hello A"

projb_hello:
           @echo "hello N"
2. Keep two separate files
  1. Project A has makefile. Type make hello.
  2. Project B has a separate make file called projb.mk. Type bmake hello.
  3. This works since I've added alias bmake ='make -f projb.mk to my .bashrc. Note! This command can be called anywhere but only works where projb.mk exists. Note! You lose autocompletion of make with the alias and typing make -f projb.mk hello is not better than typing make projb_hello.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilliam JiaView Question on Stackoverflow
Solution 1 - MakefileperrealView Answer on Stackoverflow
Solution 2 - MakefileLeonid VolnitskyView Answer on Stackoverflow
Solution 3 - MakefileSwairView Answer on Stackoverflow
Solution 4 - MakefileElpisView Answer on Stackoverflow
Solution 5 - MakefileHunaphuView Answer on Stackoverflow