Convert C
code into machine code in 4 steps:
- Preprocessing (Convert all preprocessor instructions:
#…
) - Compiling (Convert
C
code to machine code) - Assembling (Compile the necessary libraries)
- Linking (Merge the compiled code with the compiled libraries)
Libraries
Libraries are pre-written collections of code that can be reused in other programs. On *UNIX systems, they are usually located in the /lib/
and /usr/include
directories.
Math.h
For example, math.h
is very useful to implement complex arithmetic operations.
#include <math.h>
double A = sqrt(9);
double B = pow(2, 4);
int C = round(3.14);
int D = ceil(3.14);
int E = floor(3.99);
double F = fabs(-100);
double G = log(3);
double H = sin(45);
double I = cos(45);
double J = tan(45);
Using Libraries
To use a library, we first have to include it in the C
code.
#include <cs50.h> // cs50.h library will be included.
Then, the library must be linked at compile time.
gcc -o hello hello.c -lcs50
./hello
Optimization Flags
-O2
Optimize for speed-O3
Optimize for speed aggressively-Os
Optimize for size-Og
Optimize for debugging-Oz
Optimize for size aggressively
Make
Make
Is a build automation tool that automates the process of compiling, linking and building executables.
An example Makefile
could look like the following:
hello:
gcc -o hello hello.c -lcs50
clean:
rm -f hello
make #Compiles hello.c
make clean #Removes the executable (hello) generated by the make command.