How to compile and run a C program

Compile with warnings

Ask the compiler for a modern C dialect and strong diagnostics. Fix warnings instead of treating a produced executable as proof that the program is correct.

gcc -std=c17 -Wall -Wextra -Wpedantic hello.c -o hello
# Clang accepts the same options:
clang -std=c17 -Wall -Wextra -Wpedantic hello.c -o hello

Run the executable

On macOS and Linux, the current directory is not normally searched as a command location, so use ./. On Windows, run the generated .exe.

./hello
# Windows:
hello.exe

Understand the stages

Preprocessing expands directives, compilation translates C, and linking combines object code with libraries. A compile error prevents later stages.

  • -c file.c creates an object file without linking
  • -o name selects the output name
  • Multiple .c files can be passed to one compiler command

Use a debug build

During development, include debug information and avoid optimization that can make stepping confusing. Sanitizers can expose many memory errors on supported GCC and Clang systems.

gcc -std=c17 -Wall -Wextra -Wpedantic -g -O0 \
  -fsanitize=address,undefined hello.c -o hello