How to Make Makefile File for Compilation

Makefile is a file where we can type some instructions on it  to compile a program automatically. We just use “make” instruction in command prompt.
The basic makefile is composed of:

target: dependencies
[tab] system command

Target is the output that we want. Dependencies is the related file to make the output that we want. System command is the rule to produce the output. Don’t  forget to press tab on keyboard before you type the system command.
Let’s we learn from example. The steps are:
1.       Make a work directory for all of our code.
2.       Make the first source code and save as main_text.c in your work directory.
#include "text.h"
void main()
3.       Make the second source code and save as text.c in your work directory.
#include <stdio.h>
#include "text.h"
void test()
      printf("Arsitektur Komputer I");
4.       Make the third source and save as text.h in your work directory.
#ifndef TES_H
#define TES_H
void test();
5.       Make the fourth source and save as makefile in your work directory.
all: coba

coba: main2.o coba.o
     gcc main_text.o text.o -o coba

main2.o: main_text.c
     gcc -c main_text.c

coba.o: text.c
     gcc -c text.c

-          main2.o will execute gcc c main_text.c and the result is main_text.o
-          coba.o will execute gcc c text.c and the result is text.o
-          coba will execute gcc main_text.o text.o o coba and result is coba.exe
-          in this case, we learn that the name of target and dependencies is up to us. But we still should use the name of the result of the target in the system command, not the name of the target. We still type:
gcc main_text.o text.o o coba  
NOT gcc main2.o coba.o o coba

6.       Open command prompt, Enter your work directory and type "make", Enter, Then type "coba", Enter. The result is :

Now, you can use makefile file to compile and bulid a program just by type "make" in command prompt.

1 comment:

  1. very nice and helpful article.
    thank you.
    Keep writing.

    P.S: repair the comment button