Compiling with gcc

gcc (the GNU C compiler) turns C source code into a program the CPU can run. clang is another compiler that accepts the same commands.

gcc hello.c -o hello     # compile hello.c into the program hello
./hello                  # run it

Without -o, the program is called a.out (a.exe on Windows). For C++, use g++ in the same way.

The flags you should always use

FlagWhat it does
-Wall -Wextraturn on warnings about code that is legal but probably wrong
-std=c11follow the C11 standard (-std=c++17 for C++)
-gkeep line numbers and variable names for the debugger
-O2optimize: a faster program, but harder to debug
-o namename the output file
-lmlink the math library (needed for sqrt on some systems)

A good everyday command:

gcc -Wall -Wextra -std=c11 -g main.c -o main

Why warnings matter

#include <stdio.h>

int main(void) {
    int stock = 3;
    if (stock = 0) {
        printf("sold out\n");
    } else {
        printf("in stock: %d\n", stock);
    }
    return 0;
}
Open in compiler

stock = 0 is an assignment, not a comparison: it sets stock to 0, and the if sees 0, which is false. It is legal C, so plain gcc compiles it without a word, and the program prints "in stock: 0". With -Wall, gcc warns you:

warning.c:5:9: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
    5 |     if (stock = 0) {
      |         ^~~~~

Press Visualize: StepVioz is stricter and refuses to run it at all. Do the same with gcc: treat every warning as a bug until you have understood it. -Werror turns warnings into errors, so the program will not build until they are fixed.

The four steps inside gcc

  1. Preprocess (gcc -E main.c): paste in the #include files, replace #define names, drop comments.
  2. Compile (gcc -S main.c makes main.s): translate C into assembly for your CPU.
  3. Assemble (gcc -c main.c makes main.o): turn assembly into machine code, an object file.
  4. Link: join the object files and the C library (where printf lives) into one program.

Errors from steps 1 to 3 point at a line of your code. Errors from step 4 (the linker) say undefined reference: you used a function that is declared but never defined anywhere.

Quick check

1. Which flag turns on the most useful warnings?
2. if (x = 0) compiles. What does it do?
3. 'undefined reference to average' comes from which step?
My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.