MakeFile in C++ and its applications
Last Updated :
25 Jul, 2024
In C++, building a simple program is easy with the help of CLI of the compiler. But it becomes progressively difficult to maintain and build the project when its size increases. We may need to write multiple lines of commands just to simply compile it. This can be simplified by using Makefile for the project and build it using this makefile.
In this article, we will learn how to create a makefile for our C++ project with the help of examples.
What is a Makefile?
A Makefile is a script used by the make
build automation tool to compile and link a program. It defines a set of tasks to be executed, with each task specifying how to compile and link parts of the program. Makefiles are essential in managing dependencies and ensuring that only the necessary parts of the program are recompiled when changes are made.
Make tool is generally preinstalled on most of the Linux Distros. We can install make in windows from the set available at GNU Make official site.
Structure of a Makefile
A Makefile is typically composed of rules. Each rule specifies how to produce one or more target files from a set of source files.
The general syntax of a rule is as follows:
target: dependencies
command
where,
- target: The file to be generated.
- dependencies: The files required to build the target.
- command: The shell command to build the target from the dependencies. This line must start with a tab character.
Makefile Variable
We can also define variables in the makefile using the below syntax:
variableName = value
This variable can be used to refer to the given value in other parts of the makefile using the following syntax:
$variableName
Variable references work by strict textual substitution.
There are more components we can add in the makefile. But for now, it is all we need to know for now to make a simple makefile. Let's look at one example.
Example of Makefile for C++ Project
Let's create a program to find the factorial and multiplication of numbers and print it.
Traditional Way
main.cpp
#include <bits/stdc++.h>
// Note function.h which has all functions
// definitions has been included
#include "function.h"
using namespace std;
// Main program
int main()
{
int num1 = 1;
int num2 = 2;
cout << multiply(num1, num2) << endl;
int num3 = 5;
cout << factorial(num3) << endl;
print();
}
function.h
#ifndef FUNCTION_H
#define FUNCTION_H
void print();
int factorial(int);
int multiply(int, int);
#endif
print.cpp
#include <bits/stdc++.h>
// Definition of print function is
// present in function.h file
#include "function.h"
using namespace std;
void print() { cout < "makefile" << endl; }
factorial.cpp
#include <bits/stdc++.h>
// Definition of factorial function
// is present in function.h file
#include "function.h"
using namespace std;
// Recursive factorial program
int factorial(int n)
{
if (n == 1)
return 1;
return n * factorial(n - 1);
}
multiply.cpp
#include <bits/stdc++.h>
// Definition of multiply function
// is present in function.h file
#include "function.h"
using namespace std;
int multiply(int a, int b) { return a * b; }
In the above project, we have a header file functions.h that declares the print(), multiply(), and factorial() function. Then we have the source code file for the implementation of each function. Finally, we have the main program that uses these functions.
Now, to compile it in traditional way without using any build tool script, we need to execute the following commands in the terminal/shell one by one.
Commands to Compile and Run the Above Program:
g++ -c main.cpp
g++ -c print.cpp
g++ -c factorial.cpp
g++ -c multiply.cpp
g++ -o main main.o print.o factorial.o multiply.o
./main
Note: g++ -c filename.cpp is used to create object file.
Compiling Project Using Makefile
We can compile the same project using makefile. Below is the Step-by-Step process:
STEP 1: Create a file with name "makefile" and open it with any text editor.
STEP 2: Inside the makefile, define the variables for compiler name, flags, target, source and object files.
STEP 3: After that, we can define the rules for the following:
- Rule of object file creation.
- Rule for compilation of the source code.
- Rule for execution of the target.
- Rule for cleaning the generated file when done execution.
makefile
# Compiler
CXX = g++
# Compiler flags
CXXFLAGS = -Wall -g
# Target executable
TARGET = main
# For deleting the target
TARGET_DEL = main.exe
# Source files
SRCS = main.cpp print.cpp factorial.cpp multiply.cpp
# Object files
OBJS = $(SRCS:.cpp=.o)
# Default rule to build and run the executable
all: $(TARGET) run
# Rule to link object files into the target executable
$(TARGET): $(OBJS)
$(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJS)
# Rule to compile .cpp files into .o files
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@
# Rule to run the executable
run: $(TARGET)
$(TARGET)
# Clean rule to remove generated files
clean:
del $(TARGET_DEL) $(OBJS)
STEP 4: After creating the file, you can use the make tool to build and run the project by using the following command:
make
Output in the Terminal
Directory after Executing make CommandSTEP 5: After executing the file, you can use the below command to delete the files that we generated by the above command:
make clean
Directory after Executing make clean CommandNote: It is recommended that we should keep our header files, source files, objects files and examples in separate folder for better modularity.
Advantages of Makefile in C++
- It makes codes more concise and clearer to read and debug.
- No need to compile an entire program every time whenever you make a change to a functionality or a class. Makefile will automatically compile only those files where change has occurred.
- Generally, in long codes or projects, Makefile is widely used in order to present projects in more systematic and efficient way.
Similar Reads
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++
Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
30 OOPs Interview Questions and Answers [2025 Updated]
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Vector in C++ STL
C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Templates in C++
C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.C++ ClassesA class is a user-defined data type, which holds its own data members and
9 min read
C++ Interview Questions and Answers (2025)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read
C++ Polymorphism
The word polymorphism means having many forms. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So, the same person exhibits different behaviour in different situations. This is ca
5 min read