Search code examples
makefilecommand-linegnu-maketarget

makefile target command line


I'd like to use the first argument (target) of the make command as a value of a variable inside the Makefile so that instead of:

make var=arg1

I can do

make arg1

So that in the Makefile I can refer to it as TARGET:

$(TARGET): $(OBJS)
    @echo -e "\n\n\t\t*** Compiled $(TARGET) successfully! ***\n" ;
    $(FL) $(LFLAGS) -o $(BUILDS_DIR)$@ \
        $(OBJS) \
        $(LIBS)
    @echo -e "\n\n\t\t*** Linking $(TARGET) completed! ***\n"`

Additionally, is it possible to set TARGET to default value if make is called without an target argument?

Thanks


Solution

  • You can get a list of all command line goals from $(MAKECMDGOALS) which is a list of all targets specified on the command line (you shouldn't make the assumption that there is only one of these though...).

    Alternatively, you could use the % as follows:

    %: $(OBJS)
        @echo making $@
        ...
    

    Notice that this is a pattern rule with as long stem as possible, so it will only be executed if there is no other rule to service the command-line target (unless there is another %: rule, in which case it will only run the first). If you make multiple targets, this will be run once per target.