How To: Write Compile Run a C Program on Ubuntu

There are many Integrated Development Environments (IDEs) no matter what platform you’re on, Window, Linux, Max OS, Unix, etc. You can install  and configure them and develop software projects in them. For example, you could install Codeblocks, Netbeans, any IDE from Eclipse and the list goes on.

This guide comes in handy if,

  • you want to write a simple small program on a Linux machine for example to test something
  • you want to understand how the compilation or execution process works when you write a program or project in an IDE and run it.

So to write a simple “Hello World” Program in C language on an Ubuntu machine, you can proceed as follows:

Open gedit, write your program code in it and save your program somewhere you can find it. “gedit” is the standard text editor that you can find on almost all the different types of Linux machines like Ubuntu, Mint, etc.

You code might look something like this:

#include <stdio.h>
int main() {  
printf("Hello world!");
return 0; 
}

Save this files as hello.c somewhere you can navigate to using your Terminal (We’ll get to this in a little bit). This is just your source code and needs to be translated into machine code so that the machine can understand it and so you can run it.

In order to translate the source code into machine code, you use the C compiler that comes pre-installed on Ubuntu called GCC short for GNU Compiler Collection.

Now in order to compile the code, open a terminal window like “Terminal” on an Ubuntu machine. In Terminal, go to the path you saved hello.c. You should be able to do that by using commands like “pwd”, “cd”, etc to navigate to the path you saved hello.c. I’m assuming you can find your way through your file system on a terminal on your Linux machine. If not, Google for example, “Ten most important Linux commands” and you will be able to learn your way through.

Once you’re inside the path where you saved the file, write the following to compile your source code using GCC:

gcc hello.c -o helloWorld

“gcc” is the name of your compiler. “hello.c” is the source code. “-o” implies output and “helloWorld” is the name of the executable file that the compiler is going to create from your source code.

After successful compilation, you’ll have the file “helloWorld” in the same directory where you save hello.c. You could check that if you used the command “ls” for example which would give you a list of files present in the directory you were currently in.

Then, assuming that you’re still in the same directory where you saved hello.c, you can now run helloWorld right from the terminal.

./helloWorld

As a result the sentence “Hello World!” will be printed in the terminal which is what you used as the argument for the printf function in your program.

As a final note, in Linux, everything is case sensitive. So be careful about your naming conventions. That means, “helloWorld” is NOT the same files as “helloworld”.