Compile and run
- C course
- Beginner
- Lesson 3/116
- 3 min
Learn to compile and run a C program with gcc.
Compiling with gcc
To run a C program you first need to compile it. The most common compiler is gcc. To compile hello.c into an executable named hello:
gcc hello.c -o helloThen run it with ./hello. The -o hello part sets the output file name; without it the default name is a.out.
Compilation stages
Compilation actually has four stages:
- Preprocessing:
#includeand#defineare expanded - Compilation: code is turned into assembly
- Assembly: assembly is turned into machine code
- Linking: external libraries are added
gcc runs all stages with a single command.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which command produces an executable?
- execute hello.c
- run hello.c
- gcc hello.c -o hello Correct answer
- compile hello.c
Explanation: gcc hello.c -o hello compiles hello.c into an executable named hello.
2 Output file flag
gcc hello.c ____ hello
gcc hello.c -o hello
Explanation: -o sets the output file name.
3 Match the commands
| Term | Meaning |
|---|---|
gcc |
Compiler |
./hello |
Run |
hello.c |
Source file |
a.out |
Default output |
4 What is produced by 'gcc main.c'?
- main.exe
- program
- main.class
- a.out Correct answer
Explanation: Without -o, gcc names the output a.out.