Thuta Learning
C
BasicProgrammingBeginner

Get Started

CLesson 225 min

What you'll walk away with

  • Compile and run a C program with gcc -std=c17 -Wall -Wextra
  • Split a build into a compile step (-c) and a link step and say what each produces
  • Tell a compiler error from a linker error by reading the message
  • Check a program's exit status and explain what return 0 reports

Explain it simply

Explain it simply

To run C code you need a compiler, a tool that turns the .c file you wrote into an executable program the computer can run directly. While you are starting out, an online editor is fine. For real projects, install GCC or Clang on your own machine, because then you control the exact command and can read every message it prints.

Think of the compiler as a translator who translates a whole book before it goes to print. Once the translation (the executable) exists, readers no longer need the translator: you can run the program again and again without compiling, until you change the source.

Problem → Why → Solution

The problem: a Run button hides which step failed

Imagine your program calls a helper function greet(). You declared it at the top of the file but forgot to write its body. You press Run and get a wall of text ending in "collect2.exe: error: ld returned 1 exit status" (the paths and file names vary by system). No line number from your file is easy to spot, and editing the line that calls greet() changes nothing.

If you only ever press Run, it is hard to tell whether this is a typo, a setup problem or a bug. Once you know a build is several separate steps, the message becomes readable: ld is the linker, and "undefined reference to `greet'" means the linker found a call but no code for it.

link.c
#include <stdio.h>

void greet(void);   /* declared: the compiler is satisfied */

int main(void) {
    greet();        /* compiles fine, but no body exists anywhere */
    return 0;
}

Why doesn't the compiler catch this?

Compiling and linking are separate stages run by separate tools. The compiler only checks that greet() was declared, so it happily produces machine code with a hole where the call goes. Filling those holes with real code, from your files or from the standard library, is the linker's job, so the linker is the one that notices the body is missing. Compiler messages start with file:line:column; linker messages come from ld and name a symbol instead of a line.

Core concept: the toolchain and the gcc command

A C toolchain is a set of cooperating programs: the preprocessor, the compiler, the assembler, the linker and the C standard library, usually bundled with a debugger such as GDB or LLDB. You rarely call them one by one. The gcc command (or clang) is a driver: it runs each tool in order and hands the result along, so one command can turn hello.c into a finished executable.

Options control what the driver does. -std=c17 selects the C17 rules, so everyone who builds the project gets the same language version; leave it out and you get whatever mode your compiler version uses by default. -Wall and -Wextra switch on the most useful warnings. -o hello names the output file; without it GCC writes a.out on Linux and macOS, and a.exe on Windows. -g adds debugging information, and -c stops after compiling, so you get an object file (hello.o) instead of an executable.

StepCommandResult
Compile onlygcc -std=c17 -Wall -Wextra -c hello.chello.o (object file)
Linkgcc hello.o -o hellohello (hello.exe on Windows)
Both at oncegcc -std=c17 -Wall -Wextra hello.c -o helloThe executable; no .o is kept
Run./helloThe program's output and exit status

When the program runs, main's return value becomes the process's exit status. 0, or EXIT_SUCCESS from <stdlib.h>, means success; any other value, such as EXIT_FAILURE, tells the shell or a build script that something went wrong. Since C99, reaching the closing brace of main without a return statement also returns 0, but writing return 0; keeps the intent visible. In a shell such as Bash you can see the status with echo $? right after the program ends; PowerShell keeps it in $LASTEXITCODE.

Mental model: the gcc driver runs a relay
  1. gcc reads hello.c and the options
  2. Compiler writes an object file
  3. Linker adds libc, writes hello
  4. Shell runs it, reads exit status

When the relay stops, the runner who dropped the baton names itself: file:line errors come from the compiler, ld errors from the linker.

General pattern: build and run commands

bash
# compile and link in one step
gcc -std=c17 -Wall -Wextra source.c -o program

# or in two steps: compile to an object file, then link
gcc -std=c17 -Wall -Wextra -c source.c
gcc source.o -o program

# run it (on Windows the file is program.exe)
./program

The first form is what you use most for single-file programs. The second makes the driver's two stages visible, which helps in larger projects where editing one .c file should recompile only that file.

Example: a hello.c that reports its C version

This is the classic first program with one addition: it prints which C standard it was compiled for, using the predefined macro __STDC_VERSION__. Compile it on your machine with the commands below and compare the second line under different -std options.

bash
gcc -std=c17 -Wall -Wextra hello.c -o hello
./hello
echo $?      # exit status of the last command: 0
hello.c
// hello.c
#include <stdio.h>

int main(void) {
    printf("Hello C learner!\n");
    printf("Compiled as C version %ld\n", __STDC_VERSION__);
    return 0;
}

Code breakdown

  1. Line 1// hello.c

    A comment naming the file. The compiler ignores it, but the file name matters to you: the source must end in .c.

  2. Line 2#include <stdio.h>

    Brings in the declaration of printf from the standard I/O header. The actual printf code lives in the C library, and the linker adds it.

  3. Line 4int main(void) {

    Execution starts here. Writing (void) states that main takes no arguments, and it means the same thing in every C standard.

  4. Line 6printf("Compiled as C version %ld\n", __STDC_VERSION__);

    __STDC_VERSION__ is a number the compiler defines for you: 201710 under -std=c17 and 201112 under -std=c11, with other values in other modes. Its type is long, so the format is %ld.

  5. Line 7return 0;

    Becomes the exit status. Typing echo $? right after running the program prints 0.

You should see
Hello C learner!
Compiled as C version 201710

Installing a compiler

SystemOne common way
Debian / Ubuntu Linuxsudo apt install build-essential (includes gcc and make)
macOSxcode-select --install installs Apple's Clang; the gcc command there also runs Clang
WindowsMinGW-w64 GCC from MSYS2 or w64devkit, or a Linux toolchain inside WSL

After installing, open a new terminal and run gcc --version. If a version line appears, the compiler is on your PATH. A message like "command not found" usually means the compiler's bin folder is not on PATH yet. Microsoft's MSVC compiler spells its options differently; this course uses GCC-style commands, which Clang also accepts.

Reading a compiler message

text
Anatomy of a GCC diagnostic
---------------------------
semi.c:4:26: error: expected ';' before 'return'
  |    | |    |      |
  |    | |    |      +-- what the compiler expected to see
  |    | |    +--------- severity: error stops the build, warning does not
  |    | +-------------- column
  |    +---------------- line
  +--------------------- file

This message comes from a file that forgot a semicolon on line 4. An error stops the build and no new executable is written. A warning lets the build finish but says the program may contain a bug. If the message starts with a file name and line number, it comes from the compiler; if it mentions ld or collect2, it comes from the linker.

In real projects

How this shows up in real projects

Nobody types gcc commands by hand for a project with fifty files. Build tools such as make and CMake store the commands and rerun only what changed. Because compiling and linking are separate, editing one .c file means recompiling that file into its .o and relinking, not rebuilding everything. Under the hood they still call the same compiler driver with the flags you learned here.

Teams also pin the language mode and warnings in the build configuration, for example -std=c17 -Wall -Wextra -Werror in a CI pipeline, where -Werror turns every warning into a build failure so new warnings cannot sneak in. When a CI build fails, the log shows exactly the compiler and linker messages from this lesson, and being able to say "that is a linker error, a library is missing from the link line" saves a lot of guessing. Debuggers such as GDB need the -g option to map machine code back to your source lines.

Common mistakes

Common mistakes

1. Running an old executable

You fix a bug in hello.c, run ./hello, and see the old output. The executable is a separate file and does not change until you compile again. Make compile-then-run a single habit, for example gcc ... -o hello && ./hello, where && runs the program only if the build succeeded. Remember that a failed build leaves the old file in place.

2. Forgetting -o and running the wrong file

Without -o, GCC writes a.out (a.exe on Windows). If an older hello is still lying around, ./hello runs that stale file while your fresh build sits in a.out.

3. Fixing the call instead of the definition

With "undefined reference to `greet'", the call is fine; the linker cannot find a body. Look for a missing definition, a misspelled name in the definition, or a .c file you forgot to put on the command line, such as typing gcc main.c -o app when greet lives in greet.c.

4. Leaving out the header

Calling printf without #include <stdio.h> makes recent GCC versions stop with "implicit declaration of function 'printf'" and suggest including '<stdio.h>'. Older compilers only warned, which is why old tutorials sometimes leave the line out.

Mini challenge

Mini challenge: repair a broken build

The greet.c below does not build. Fix its three problems one at a time, recompile after each fix, and note whether each message came from the compiler or the linker.

  • Add the header that declares printf
  • Fix the compiler error the build reports first
  • Write the missing definition of print_banner() so the link step succeeds
  • Build with gcc -std=c17 -Wall -Wextra and get zero warnings
greet.c
// greet.c: this file does not build yet. Fix it one error at a time.
// TODO 1: printf needs its header; add the right #include line here

void print_banner(void);   // declared here, but never defined

int main(void) {
    print_banner();
    printf("Build log: compile ok, link ok\n")    // TODO 2: compiler error
    return 0;
}

// TODO 3: define print_banner() so the linker can find it.
//         It should print "=== greet v1 ===" on its own line.

Expected: With all three problems fixed, the build succeeds without warnings and prints: === greet v1 === Build log: compile ok, link ok

Show hint

Build after each fix, not after all three. A definition repeats the declaration's first line, replaces the ; with { }, and puts statements inside. The last message comes from ld and names print_banner.

Show solution
greet.c
// greet.c
#include <stdio.h>

void print_banner(void);

int main(void) {
    print_banner();
    printf("Build log: compile ok, link ok\n");
    return 0;
}

void print_banner(void) {
    printf("=== greet v1 ===\n");
}

Quick quiz 1 / 3

Which of these messages comes from the linker rather than the compiler?

Quick quiz 2 / 3

You run gcc -std=c17 -Wall -Wextra -c app.c. What do you get?

Quick quiz 3 / 3

You edit hello.c to print a new message, then type ./hello and the old message appears. What is the most likely cause?

What to remember

  • A compiler driver such as gcc runs the preprocessor, compiler and linker for you; -c stops after compiling.
  • Build with gcc -std=c17 -Wall -Wextra file.c -o name so the language mode and warnings are explicit.
  • file:line:column messages come from the compiler; "undefined reference" comes from the linker.
  • main's return value is the exit status: 0 or EXIT_SUCCESS means success.
  • Recompile after every edit, because the executable does not update itself.

ISO C Working Group (WG14) — ISO/IEC JTC1/SC22/WG14

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Get Started | Thuta Learning