This article will guide you to compile a C program on Ubuntu using the GNU gcc/g++ compiler. Additions were made in order to simplify and clarify the creation of a C program on Ubuntu.
1. Open up a terminal on Ubuntu and install the build-essential package by typing the following command in the terminal
1. Open up a terminal on Ubuntu and install the build-essential package by typing the following command in the terminal
- sudo apt-get install build-essential
- This will install the necessary C development libraries for your Ubuntu system to create C programs.
2. Create a directory and a sub directory to hold your C programs and your main HelloWorld program.
- mkdir -p CProgram/HelloWorld
- We are using CProgram for the main directory to hold our created C programs and we are using the sub directory HelloWorld to hold our main program.
3. Then we will change into our created directory by issuing the following command
- cd CProgram/HelloWorld
4. Next we will use a text editor such as gedit or nano to create our C or C++ source code using the following command.
- gedit main.c
- OR
- nano main.c
5. Enter the source code of your program. For example: the HelloWorld program is as follows:
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("Hello World,\nThis is my first program compiled on Ubuntu.");
#include<stdlib.h>
int main()
{
printf("Hello World,\nThis is my first program compiled on Ubuntu.");
return 0;
}
}
6. Save the file as main.c and exit.
7. Compiling your C program
- Make sure you are in the CProgram/HelloWorld directory before you compile your C programs.
Now type in the terminal:
- gcc -Wall -W -Werror main.c -o HelloWorldC
- The first line will invoke the GNU C compiler to compile the file main.c and output (-o) it to an executable called HelloWorldC.
- The options -Wall -W and -Werror instruct the compiler to check for warnings.
9. If you get the permission errors, you need to make the file executable. You can do this by issuing the following commands below
- chmod +x HelloWorldC
10. In order to execute your program you will have to type in the following commands.
- ./HelloWorldC
[Note: All the sentences that are highlighted are the commands that have to be written in Ubuntu terminal.]
i couldn't understand step 2. so will u please help me ?
ReplyDeleteMake a folder named "CProgram" and another folder named "HelloWorld" inside that folder. You can do this manually without the command line.
DeleteI did it bro. Thank you very much
ReplyDeleteI found all the difference between Dev C++ and Terminal
That's nice. All the best.
Delete