Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a Makefile to compile a simple C program

Tags:

c

unix

makefile

Compile the following program

#include <stdio.h>
int main(void)
{
   printf ("Hello from your first program!\n");
   return 0;
}

a)-by using file of type Makefile

b)-the executable will be named Hello

"Please help to do an exercise. I know how to do it in CodeBlocks, but I don't know what Makefile is and how to write it in Linux. I compiled it using command "gcc filename.c" and subsequently "./a.out" but I still don't understand what the Makefile is. Is it a sort of shell script, an instruction? How would a Makefile for this task exactly look? Thanks in advance :) "

like image 608
Zhivago Avatar asked Feb 04 '14 09:02

Zhivago


1 Answers

This is your simple make file for hello program.

CC      = gcc
CFLAGS  = -g
RM      = rm -f


default: all

all: Hello

Hello: Hello.c
    $(CC) $(CFLAGS) -o Hello Hello.c

clean veryclean:
    $(RM) Hello

Suppose you have two makefiles in one directory named makefile.m1 and makefile.m2 and if you want build both make file then please use following commands

make -f makefile.m1
make -f makefile.m2

or use single Makefile that contains:

m1:
  make -f makefile.m1

m2:
  make -f makefile.m2

and use make m1 or make m2

Now lets clear your doubt about name of make file must not require Makefile

You can name makefile whatever you want. suppose i would like to give name myfirstmakefile.mk. To use it later you need to tell make what makefile you want. Use -f option for this:

make -f myfirstmakefile.mk

And again extantion .mk is also not manadatory you can use whatever you want but never forgot to use -f option.

so may this help make sense to you.

like image 123
Jayesh Bhoi Avatar answered Oct 02 '22 21:10

Jayesh Bhoi