First steps to programming C (GNU Linux)
Previous Knowledge, as advice I encourage you to review information about c (programming language), compiler, GCC (GNU Compiler Collection), Linux text editors (vi, vim, emacs, atom, etc.), Linux shell, Bash, assembler.
Let’s to write our first program in C, for this we will use a Linux text editor (vi, emacs, atom, etc), write the next code and save it as hello.c :
Once you have done this could to start the compilation process in order to get a executable file for your program, so let’s go to go in depth the compilation process in C.
To start the compilation process in Linux we can use the compiler GCC that basically takes the C code and convert it into a machine language — binary code (0100101…) — , GCC compile a program in four phases (pre-processing, compilation, assembly, linking) to finally give us an executable file.
This is the first stage for a source C code file, here the file is processed by a preprocessor which removes all the comments from our file hello.c, includes code from header (e.g. C standard library functions as stdio.h) and source file, and replaces macros (if there are any that are used in the program) with code. If you just want to do the preprocessing stage should use the command gcc -E hola.c in the same directory as the file hola.c is located.
The compiler compiles the pre-processed source code into assembly code for a specific processor, the output file is an Assembly code that can work on different computers with different architectures e.g. Intel syntax depends on the parameters specified to GCC.
By using -S (uppercase), gcc converts the preprocessed C source code into assembly language and creates a file called hola.s containing the generated assembly instructions for the hola.c file.
During this stage, an assembler is used to translate the assembly instructions to object code. The output consists of actual instructions to be run by the target processor, therefore our hola.s file will change to machine level instructions.
This tells the compiler to run the preprocessor on the file hello.c and then compile it into the object code file “hello.o”. The option “-c” means to compile the source code file into an object file but not to invoke the linker. The contents of this file is in a binary format.
Finally, the linker links the object code with the library code to produce an executable file. Like the preprocessor, the linker is a separate program called ld. Also like the preprocessor, the linker is invoked automatically for you when you use the compiler gcc. The normal way of using the linker is as follows:
In that line the instruction tells to the gcc compiler to link together three object files (hello1.o, hello2.o, and hello3.o) into a binary executable file hello. Now you have a file called hello that you can run.