Makefile Tutoriallearning manual

Published on 2023-04-20 00:10:05 · 中文 · بالعربية · Español · हिंदीName · 日本語 · Русский язык · 中文繁體

Makefile is a program building tool that can run on Unix, Linux, and their styles. It helps to simplify the construction of executable files for programs that may require various modules. To determine how the module needs to be compiled or recompiled, make requires the help of a user-defined makefile. This tutorial will enhance your understanding of the structure and utilities of makefiles.
Compiling source code files can be tiring, especially when you have to include multiple source files and type the compile command every time you need to compile. Makefile is a solution to simplify this task.
Makefile is a special format file that helps automatically build and manage projects.
For example, suppose we have the following source files.
main.cpp hello.cpp factorial.cpp functions.h
main.cpp
The following is the code for the main.cpp source file-
#include <iostream>
using namespace std;
#include "functions.h"
int main(){
   print_hello();
   cout << endl;
   cout << "The factorial of 5 is " << factorial(5) << endl;
   return 0;
}
hello.cpp
The following code is used for the hello.cpp source file-
#include <iostream>
using namespace std;
#include "functions.h"
void print_hello(){
   cout << "Hello World!";
}
factorial.cpp
The code for factorial.cpp is as follows-
#include "functions.h"
int factorial(int n){
   
   if(n!=1){
      return(n * factorial(n-1));
   } else return 1;
}
functions.h
The following is the code for functions. h-
void print_hello();
int factorial(int n);
The simple way to compile files and obtain executable files is to run commands-
gcc  main.cpp hello.cpp factorial.cpp-o hello
This command generates Hellobinary file. In this example, we only have four files, and we know the order of function calls. Therefore, typing the above command and preparing the final binary file is feasible.
However, for large projects with thousands of source code files, maintaining binary builds becomes difficult.
The makecommand allows you to manage large programs or program groups. When you start writing large programs, you will notice that recompiling large programs takes longer than recompiling short programs. In addition, you will notice that you usually only handle a small portion of the program (such as a single function), while most of the other programs remain unchanged.
In the following sections, we will see how to prepare makefiles for our project.