Basics of C, and compilation.

Basics of C, and compilation.

·

2 min read

After writing a C program, to use it, it must be compiled to make an executable file that can be run. The GNU/Linux system comes with a native compiler, the gcc compiler that can be used to do just this. The way to compile with gcc is simply to invoke it by running gcc filename.c to create an executable. Now the executable in this case will be called a.out by default. If you wan te executable to be named something different, specify the name using the -o flag when running gcc. e.g. To get an executable named cisfun, run gcc filename.c -o cisfun.

The C compilation process

The compilation process in C goes through several steps, preprocessor, compilation, assembly and linking. The compiler typically invokes all these when it is invoked. When you write C code it is converted to assembly code before being converted to machine code. The gcc compiler allows for the compilation process to be stopped at various stages. It does this using various flags. On your GNU/Linux terminal, run man gcc to learn more about these flags.

To run the preprocessor alone, use the -E flag with gcc, to run the assembler and generate assembly code, use the -S option. To run the assembler but not link use the -c flag. Since there are different assembly syntaxes, the -S flag can be coupled with other options such as the -masm option to specify the syntax. It is also important to note that gcc runs in the shell hence the file can be stored in variables and used in compilation.

Basic Output functions.

To print to the standard outputs, C provides several functions. One is the puts function which prints the given string of characters and ends by print a newline. It is defined in the <stdio.h> header and returns the number of characters it has printed. Run man puts to learn more about puts.

The putchar function is one such function that prints a single character to the output. Run man putchar to learn more about how it works and interprets the values given to it.

The most common function used to print in C is the printf function. Printf prints formatted output to the standard output and returns the number of characters it has printed. Formatting your output can be tricky and we'll come back to printf in a future article.

Another function that writes to the stdout is the write function. We'll look at it wit the printf function, but you could run man 3 write to learn more.

I hope this gets you started on C well.