How to write a simple Makefile

How to write a simple Makefile 

Neelkanth_98$ cat Makefile 

main_bin: main.o func.o
        echo "linking stage"
        gcc -o main_bin main.o func.o

func.o: func.c
        echo "compilation stage func.o"
        gcc -c func.c -Iincludes

main.o: main.c
        echo "compilation stage main.o"
        gcc -c main.c -Iincludes

clean:
        rm -rf *.o

Neelkanth_98$ cat main.c

#include "includes/demo_include.h"

void main()
{
    printf("Enter main function \n");

    func();

    return;

}

Neelkanth_98$ cat func.c

#include "includes/demo_include.h"

void func(void)
{
    printf("\n called function\n");
    return;
}


Neelkanth_98$ cat includes/demo_include.h

#include <stdio.h>

void func(void);

Makefile basics

Makefile is a set of targets and rules to build them. A target is "something which can be built and results in a given file".
Each target has 2 parts:
  • list of dependencies"sensitivity list" (other files and targets which are needed for this target) (after :, comma-separated),
  • list of shell commands which are executed to build this target (below the above, indented).
 
Example:

main: main.o module1.o module2.o 
       g++ main.o module1.o module2.o -o main

Can be written as,

main: main.o module1.o module2.o
       gcc $^ -o $@

The variables (everything starting with $ is a variable) will be expanded to the dependencies list and the target name, as you expect.