A program and its translation

Lesson 1 of 14 · C memory foundations

C source code is text that a compiler translates into a program. A typical hosted C program begins at main. This complete example prints one line:

#include <stdio.h>
int main(void) {
    printf("Memory has a lifetime.\n");
    return 0;
}

#include makes declarations from the standard input/output header available; printf prints formatted text. \n is a newline. Braces surround a block, and semicolons terminate statements. int says main returns an integer; zero conventionally reports success. void in the parameter list means no arguments. Comments // like this and /* like this */ document code and are not executed.

With a C compiler installed, save a complete example as example.c and translate it with cc -std=c11 -Wall -Wextra -Wpedantic example.c -o example, then run ./example. The shell command assumes a Unix-like system. Translation errors prevent a usable executable; successful compilation does not prove memory accesses safe. The compiler cannot diagnose every error, and behavior may differ across implementations.

A header usually declares interfaces shared by .c files; it does not itself link their implementations. Include guards (#ifndef, #define, #endif) prevent repeated definitions within a translation unit. #pragma once is common but not ISO C. Tests can compare actual results with expected results, but passing tests alone cannot establish absence of undefined behavior.

From source to execution

The preprocessor processes directives such as #include before the compiler translates each source file. Compilation produces object code; a linker resolves references between object files and libraries to create an executable. A declaration describes an interface; a definition supplies an object or function. A missing declaration may be diagnosed during translation, while a missing implementation often appears at link time. The executable still must be run to observe its behavior. An interpreter typically executes a representation under another program; real language implementations can combine interpretation and compilation.

For a multi-file program, a guarded header can declare int twice(int n);; the .c file defining twice and the caller each include it. Compile and link both files together, for example cc -std=c11 -Wall -Wextra -Wpedantic main.c twice.c -o app. In the header, #ifndef TWICE_H, #define TWICE_H, the declaration, and #endif prevent repeated inclusion in one translation unit. Do not put a non-static function definition in such a header merely to share its interface.

Read error messages from the first one onward: one missing semicolon can cause later misleading diagnostics. Warnings are useful signals, not a proof of correctness. An automated test calls code with chosen inputs and compares results with expectations; it covers those cases only. C has no built-in unit-test framework requirement.

Chapter index · Course index