In the last tutorial we understood what preprocessor does and how it works behind the scenes. We also learned the command that allows us to view the expanded source code file. Now, we will move to the next stage, which is compiling the expanded source code. So, let’s get into it.
What is a Compiler and What it Does?
Recall the following diagram:
The program execution process
Preprocessor produces the expanded source code which is then provided to the compiler. Like any other software, compiler is also a software (although a sophisticated one) which is developed to solve a specific problem. It’s a translator whose job is to convert a code written in one programming language to the other. In C, compiler translates the expanded source code to assembly code so that it can be fed to the assembler for further processing. This process is called compilation.
During compilation, it is possible that compiler may encounter errors (like syntax errors such as missing semicolons, undeclared or unused variables, etc) in the program. At this point, the compiler may stop the compilation and the errors will be reported to the programmer through a dedicated debug window (in Code::Blocks it is situated at the bottom where you will see the error logs). The complete translation is only possible if the rules of the programming language are followed throughout the program.
Note: How compiler works behind the scenes is out of the scope of this tutorial. It deserves a dedicated course on its own. At this point, as the programmers, it is enough for us to know what is a compiler and what it does.
So, in a nutshell
C compiler translates the expanded source code produced by the preprocessor to assembly code which is understood by the assembler.
The complete translation is possible only when rules of the language are strictly followed in the program.
How to View the Assembly Code File?
Recall, in the last tutorial — preprocessing, we generated the expanded source code file and named it add.i . Let’s now feed this file to the compiler and generate add.s file (.s is the extension for the assembly code file) by typing the following command in the command prompt or terminal:
gcc -S add.i -o add.s
The command has following elements:
gcc: activates GNU C compiler.
-S: flag which stops the assembler to take the assembly code for further processing. This means the final output will be an assembly code.
add.i: expanded source code file as the input.
-o: to generate a specific output file.
add.s: assembly file as the output.
Make sure in the command prompt (or terminal), you have opened the folder where add.i is situated. After typing the command, and if compilation is successful, you would be able to see add.s file in your folder (if you are following along, then this must be C Programs folder). You can open the file and see the assembly code which is generated by the compiler.
Leave a comment