Creating a simple GCC Makefile in Linux using C Language
Makefile contains recipes implemented on various files to achieve a target. A target is the output file which is created by linking and compiling the base files. We are going to use GCC compiler to Makefile contains recipes implemented on various files to achieve a target. A target is the output file which is created by linking and compiling the base files. compile our C files. We are going to compile it on the linux machine. To know more about the Makefile check out the gcc website: https://www.gnu.org/s/make/manual/html_node/Introduction.html
- A Linux(Ubuntu) ready Machine- May be using virtual box or installed.
- A basic terminal knowledge.
- A basic C programming language knowledge.
How to implement Makefile:
1. Installing GCC
Step 1: Open terminal in your linux machine. Now type :
sudo apt install gcc
It will install gcc.
Step 2: Now type
sudo apt install build-essential
Your GCC is ready in your Linux Machine.
2. Creating .c files.
We have to create some C files which we need to compile using GCC and make using terminal window.
Step1: Type gedit in terminal. It will open a text editor as you can see below.
Now create a main.c file. Let us make a simple Hello World code.
Type in the editor the following code of hello world in C
Save the text as main.c
Step2: Let us create two more files. help.c and help.h
Using the same above method: Gedit open help.c and help.h
help.h is the header file for help.c. It contains function initialization and prototype.
Now you have 3 files- main.c, help.c, help.h.
In main.c we need to include help.h file . Make changes in main.c as shown in the below image.
3. Creating a makefile
Similarly open a text document using gedit in terminal. Save it as Makefile
Type below shown text in Makefile
- all: Target name– The output will be named as target.
- main.o – object file made from main.c and help.h
- gcc -c main.c- recipe to compile main.c and make output as main.o
- gcc -o all– recipe to make object file
- clean: command clean to remove all files
- rm all main.o– recipe to clear main.o. You can also add help.o
Save this file. Make sure your all .c, .h and Makefile are in the same folder.
4. Running the Makefile
Step1: Type make in terminal. It will execute your recipe.
Step2: type ls in terminal. You can see files generated. “all” is your target file or output file
Step3: Run your “all” or target. Type ./all
See the output, Press h when asked and you can see the help function getting executed.
This is how makefile works. When there are large number of files which are required to be linked with each other makefiles help you to do in a single command.
When there are errors in your code, GCC gives you error’s in terminal.
To learn More about Makefiles: Check GCC GNU Website. It’s a handy tool to get started.