Search code examples
gcccompilationmakefilegnu-makeobject-files

Makefile rules vs source and object files


I'm studying how 'make' works and I encountered a little oddity

Suppose I have a folder with only 'helloworld.c' and 'Makefile'

Makefile contains

helloworld: helloworld.o
    gcc -o helloworld helloworld.o

The output of 'make' in a bash console is

cc -c -o helloworld.o helloworld.c

gcc -o helloworld helloworld.o

The rule "helloworld" depends on the file "helloworld.o" which is not present, hence make creates it (the first line in the output).

But why?

I would have expected it to fail, in absence of a "helloworld.o:" rule that tells it how to compile said file. Why does it run the first command out of its own will?

Thanks


Solution

  • The reason is implicit rules.

    From the GNU Make manual:

    Implicit rules tell make how to use customary techniques so that you do not have to specify them in detail when you want to use them. For example, there is an implicit rule for C compilation. File names determine which implicit rules are run. For example, C compilation typically takes a .c file and makes a .o file. So make applies the implicit rule for C compilation when it sees this combination of file name endings.

    In other words, make knows how to build helloworld.o from helloworld.c even if you don't specify an appropriate rule.

    To get more information on this subject you can follow GNU Make manual, especially section 10, which is devoted to the usage of implicit rules.