How to create a simple make file and compile c++ project in linux?

Introduction

  Make file is used to compile and link C++ header files, cpp files and associated libraries in Linux platform. Look at the bellow example.

 Assume that we have two cpp files that includes 2 header files and one Library file, to write a make file for this C++ project, do the following things.

 

  "Example1.cpp" associated to "example1.h"

 

  "Example2.cpp" associated to "exaple2.h" and a lib file called "example2LIB"

 

·         open a text file and name as "makefile" (Normally no extension)

·         open the file in any text editor

·          Wrtite the bellow expression

·         g++  -c  example1.h Example1.cpp exaple2.h Example2.cpp -lexample2LIB -o example

Ø  g++ - For calling Linux based c++ compiler

Ø  -c - Compile the codes

Ø  -l - Link to libraries

Ø  -o - Final binary out put

 

·         Save the file.

·         Open Terminal and move to the project path

·          Type make to compile and link the code , If you got any error in code type vi space cpp or .h file name ,

·         press i and edit the code correctly press ESC then press :wq to save ["q! to exit without save]

·         If any conflict in object files and intermediate files just add one more line in make file to clean up

 

·         clean:

o   rm -f <Foldername>/*.o

 

·         To execute the clean command  type "make clean" in terminal

·         To avoid re-usage of same keywords or commands in make file creation and make some generality to your make file , just use variables like the following way

·         Syntax: Variable name=<value>

Ø  Eg:  CC=gcc

Ø  CPP=g++

 

·         To retrive the values from variables use "$" sign

·         Eg : $(CPP) -c example.h example.cpp -o example

 

·         To display a message to screen when making process use @echo

·         Eg: @echo "Cleaning up directory."

 

Article by

 Johnson Augustine

johnsonaugustine@live.in


See All Responses Below...
Author
Message Rating
Posted on:
Please Login to Post Your Comments
Name (Max. 100 characters)
Please post your comments here
Select Language
Comments
Attach File(Max. Size: 2 MB)
A few simple rules when posting your Comments,
  1. Please post only answers relevant to the topic of discussion.
  2. Please dont misuse this site or do not be abusive, offensive, inappropriate,harass anyone on the boards or post ads or spam. Doing so will delete your inappropriate messages and will block or delete your account on this site. 

 
TekTipsDownload
GateExam
Academic Projects
TekTipsExperts
Android