Running Your First Program
With a compiler installed, the greenhouse logger can finally say something. Unlike Python, where you run the source file directly, C has a separate build step, and knowing what happens in it will explain half the error messages you ever see.
The rule
Edit, compile, run: C must become a program before it can do anything.
Save this as logger.c:
#include <stdio.h>
int main(void)
{
printf("Greenhouse logger ready\n");
return 0;
}Line by line:
#include <stdio.h>pastes in the standard I/O header, which declaresprintf.int main(void)is where every C program starts. It takes no arguments here and returns anint.printf(...)writes text.\nis a newline.return 0;tells the operating system the program succeeded. Any other value signals a problem.
Build it, then run it:
gcc -std=c17 -Wall -Wextra -o logger logger.c
./logger-o logger names the output file. Without it, GCC on Linux and macOS calls it a.out. On Windows the program is logger.exe.
That single gcc command runs four stages:
- Preprocess — handle
#includeand other#lines. - Compile — turn C into assembly.
- Assemble — turn assembly into an object file of machine code.
- Link — join your object file with the C library, where
printfis implemented, to make the executable.
The shortcut
When a build fails, fix the first error first, then rebuild. One real mistake often causes a cascade of later messages that vanish once it is fixed.
The mistake
The
printfline loses its;.
Treat warnings seriously too. A warning means the compiler accepted the code but suspects it does not do what you meant. Aim for a build with zero warnings, so a new one stands out the moment it appears. Once the build is clean, run the program and check its output against what you expected, because a program that compiles is not yet a program that is right.
Drills
Answer fast — trust the rule.
What does -o logger do in gcc -o logger logger.c?
On Linux, what is the executable called if you leave out -o?
What does return 0; at the end of main tell the operating system?
Which build stage connects your call to printf with the C library?
Remember
- Edit, compile, run:
gcc -std=c17 -Wall -Wextra -o logger logger.c, then./logger. - Shortcut: fix the first error first, and look just before the line the compiler points at.
- Trap:
#includeonly declaresprintf; the linker supplies the real code.
