Search code examples
clinuxmakefile

Why are Makefiles in Linux so useful?


I want to know why makefiles in Linux are so useful (I mean in the practical sense). Why can't we just compile all our programs in the normal way?


Solution

  • Makefiles do so much work for you, and are frequently more powerful than people realize. Take the following simple makefile

     all: helloworld
    

    that's one line, and (gnu make, at least) would know to run cc -o helloworld helloworld.c Then, as the project grows, you add one more rule:

    helloworld: helloworld.o ui.o xml.o mailcomponent.o
       $(CC) -o $@ $@.c $^ $(LDLAGS)
    

    and make knows to run

    cc -c ui.c
    cc -c xml.c
    cc -c mailcomponent.c
    cc -c helloworld.c
    cc -o helloworld helloworld.o ui.o xml.o mailcomponent.o
    

    Then say you want to optimize everything.

    CFLAGS=-O2
    

    at the beginning of the file takes care of you.

    When the project gets larger, make keeps track of the files which have and haven't changed, preventing extraneous, and time-consuming re-compiles.

    Makefiles are wonderful timesavers, and I haven't even touched on more advanced recipes.