Open In App

MakeFile in C++ and its applications

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

traditional-method-directory

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.

commands-to-be-executed-for-compilation

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.

makefile-in-directory

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
using-make-on-our-makefile
Output in the Terminal


files-created-after-using-make
Directory after Executing make Command

STEP 5: After executing the file, you can use the below command to delete the files that we generated by the above command:

make clean
files-deleted-after-using-make-clean
Directory after Executing make clean Command

Note: 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.



Next Article
Article Tags :
Practice Tags :

Similar Reads