Want To Know: How To Compile Using GCC

Image for post
Image for post

After reading this, you should be able to understand the process it takes to compile a C program using gcc as your compiler!

What is gcc exactly? GCC is a component of the “GNU toolchain” for developing and writing operating systems. More specifically, GCC stands for “GNU Compiler Collection”.

There are 4 main components in the compiler; a preprocessor, a compiler, an assembler and a linker.

First step writing any C program. It is our source code and the file with extension of .c. (e.g. main.c). Preprocessor generates an intermediate file with assembly code.

Converts .c file into assembly code/language. Which is still not broken down enough for the computer to understand. Computers only understand binary language. (e.g. 0001110110101000)

Changes the assembly code to object code. Object code is then given to the linker!

Takes object code and libraries and generates an executable program.

First know that I am working in my C_Projects directory, where I will be using the gcc command on file containing my source code.

  1. First, use the command gcc and the name of the file with the source code you’d like to execute. In the example below, the filename I used is task1.c.

See below:

Image for post
Image for post

2. When you use the ls command, you can then see that an executable file name a.out was created.

See below:

Image for post
Image for post

3. To run the executable program simple type in ./a.out and press enter and you can see it execute on the next line in your terminal window.

In the example below, you can see that my program printed out “hello” followed by a new line:

Image for post
Image for post

*You are more than welcome to rename the executable file to be whatever you would like it to be, and in my example I will change it to be TASK1 (remember bash is case sensitive). To do this I will remove my a.out and recompile with gcc but change the output file name to TASK1 using the -o option with gcc. I used the ls command to display the changes made to the executable filename!

Example below:

Image for post
Image for post

Hopefully, after reading this, you are more comfortable with the compiling process using gcc. Remember that man pages can always be used as a resource to better understand different commands and in this case, man gcc can become very helpful for individuals wanting more customization during the compiling process! Until next time!

Full-Stack Software Engineering Student at Holberton School

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store