Tutorial Goals

This tutorial’s goal is to set you up correctly for when CS1010 ends,
and you have to set up everything yourself

By the end of this tutorial, you should be able to:

  1. Compile C programs without a Makefile
  2. Understand the tooling around C and other popular programming languages

Motivation

So far, every volume comes nicely bundled in a directory.
You run make to build,
and make test to run against testcases,
your code is magically formatted,
warnings show up highlighting possible issues with the program.
After completing this course,
no one is going to give you a nicely bundled directory.
What would you do?

We will talk about the flags used in compilation,
formatters, and linters.

What Is “Compiling”?

Your C code is text.
It’s easy for you to read,
but your computer can’t run it.
Your computer runs binary,
just 0s and 1s,
which it reads fine but you can’t.
Compilation is the translation step between the two.
For instance, when you run the command clang student.c -o student,
the compiler will transform student.c into an executable called student.

More precisely,
building a program is broken down into two steps:
compiling and linking.
The source code is compiled into object files,
and subsequently linked.
Even though it may seem like pedantry,
this distinction makes the subsequent parts easier to follow.

In the very first tutorial,
we show a simple command to compile your code.
Subsequently, on an ad-hoc basis, we introduced some flags along the way.
We will consolidate them here as much as possible,
and also share about some other flags that we use.

Flags You Should Have Seen Before

  • -o names the output file, instead of a.out,
    as you did for your first program.
  • -g keeps your variable names and line numbers in the executable,
    which is what aids GDB
    and sanitisers.
  • -fsanitize=address,undefined adds memory and undefined behaviour
    checks that run while your program runs,
    the ones you turned on for the sanitisers.

We will now cover the flags you may not have seen before.

Enabling Warnings (-W)

C is a language with a lot of footguns,
wouldn’t it be good if the compiler helped us out as much as possible?
With warning flags, it can!
As a baseline, most developers will enable -Wall and -Wextra
(read as “warning all”, and “warning extra”).

You’ve seen errors before:
the compiler gives up,
and you get nothing to run.
A warning is softer.
It still lets your program compile and run,
but the compiler is flagging something that looks wrong.
Because it doesn’t stop your program,
it’s easy to ignore and ship a bug by accident.
If you want to be strict, you might want to use -Werror,
which converts all warnings to errors, forcing you to resolve all of them.

Tip

Even though -Wall is commonly understood as “warning all”,
it doesn’t actually enable all the warnings.

On clang, there’s a -Weverything flag that turns on every warning it has.
It’s usually too noisy for real use (clang even says so),
but try it on your code once and see for yourself.

Run the following command:

clang -Wall -Wextra compile.c -o compile

How can we address those warnings?

Another flag that is commonly enabled is -Wpedantic. Find out what kind of issues -Wpedantic is meant to warn on.

Building Programs with Multiple Files

In our volumes, there is always more than one file.
Have you ever wondered how we do it?
(I hope you have, even if only a little)

You’ve been doing this all along without noticing.
Every volume has a main.c sitting next to your student.c,
and the two of them get built into a single program.

Building that program has a compile step and a link step.
Compiling needs the declarations,
while linking needs the implementation.

Compiling

Say you’ve split a program into two files.
helper.c has the function:

int helper(int x) {
  return x * 2;
}

and main.c calls it:

#include <stdio.h>
 
int main(void) {
  printf("%d\n", helper(2));
  return 0;
}

The obvious thing to try is to just list them both:

clang main.c helper.c -o program
main.c:4:17: error: call to undeclared function 'helper';
ISO C99 and later do not support implicit function declarations

To see why, imagine you’re the compiler.
You work under three rules:

  1. You only look at one file at a time.
    You compile main.c on its own,
    then helper.c on its own.
    Nothing you learned from one carries over to the other.
  2. You read top to bottom, and you never look forward.
    At any line, you only know what appeared above it.
  3. Everything you use must already be known.
    If you hit a name you haven’t been told about, you stop and complain.

main.c calls helper on line 4,
and nothing above line 4 in that file has ever mentioned helper.
Rules 1 and 2 mean you have no way to go and find it,
so rule 3 says you fail.

Swapping the order on the command line (i.e. clang helper.c main.c) doesn’t help,
because of rule 1.

The minimal fix is to put the function prototype at the top of main.c:

#include <stdio.h>
 
int helper(int);
 
int main(void) {
  printf("%d\n", helper(2));
  return 0;
}

Rule 3 is satisfied, and it compiles.

Because of rule 1, though, that prototype has to appear in every file
that calls helper.
Copying it by hand into each one gets old fast,
and the moment you change what helper takes,
every copy is now wrong.

Header Files

So instead of copying the prototype around,
write it once in a file of its own, helper.h:

int helper(int);

and pull it in wherever you need it:

#include "helper.h"

You’ve been typing #include <stdio.h> since week one,
and this is the same thing.
A little bit more detail on the inner workings,
it is not any fancy system,
it just copy and pastes the contents of that file in at that exact line,
before the compiler sees any of it.
We’ll come back to how that works later.

Why is "helper.h" in double quotes, when <stdio.h> gets angle brackets?

Would <helper.h> work?
What about "stdio.h"?

Now say a third file, report.c, also calls helper.
It includes the same header:

#include "helper.h"

so helper.h gets pasted into main.c and into report.c,
and the prototype now exists twice across your project.

That’s fine, and rule 1 is why.
Those two files are compiled separately and never see each other,
so neither of them knows the other has a copy.

Include what you use

Headers pull in other headers, so a file will sometimes compile without an
include it clearly needs, because something else already dragged it in.

You could try to keep track of what brings in what, and skip the ones you’d
get for free, but that’s a nightmare to manage once you have more than a
handful of files.
Just include what you use.

Include Guards

Consider the following situation:

// main.c
#include "file1.h"
#include "file2.h"
int main(void) {}
 
// file1.h
#include "file2.h"
int f1(int);
 
// file2.h
struct point {
  int x;
  int y;
};
 
  • main.c includes file1.h and file2.h
  • file1.h includes file2.h, and declares int f1(int);
  • file2.h defines struct point

Pictorially,

Do you see a problem?

A common way to get around this is to use include guards,
and you’ll find one in almost every header you ever open.

#ifndef FILE1_H
#define FILE1_H
 
// Contents of header file
 
#endif

Read it as: “if FILE1_H is not defined, define it, and keep everything up
to the #endif.”
The second time the file gets pasted in, FILE1_H already exists,
so the whole block is skipped.

Tip

Every modern compiler you’re likely to meet supports #pragma once,
which does the same thing in one line:

#pragma once
 
// Contents of header file

It is just easier, and you don’t have to invent a name for the guard.

Linking

At this stage,
we have a program with all the declarations it needs.
Once the preprocessor is done with main.c, the compiler sees something like:

// Contents of <stdio.h>, pasted in
 
int helper(int);
 
int main(void) {
  printf("%d\n", helper(2));
  return 0;
}

The prototype was enough for the compiler,
because the compiler only looks at one file at a time
and only needs to know the types line up.

Running the program is a different matter.
Knowing that helper takes an int and returns an int tells you nothing
about what it actually does, and at some point the program has to jump to
real code.

That’s the job of the linker.
Each .c file gets compiled on its own into an object file,
which is machine code but not a program yet.
main.o knows it calls something named helper,
but it has no idea where helper is.
Linking is what goes through the object files,
works out where each name actually lives, and fills in the gaps.

clang has been quietly doing both steps for you this whole time.
When passed in multiple files,
it compiles each one,
then links the results into a single executable.

Prerequisite

Create helper.h with the prototype of helper,
and include it in main.c.

You can stop after the first step with -c, which compiles but does not link.

Run it on each file separately:

clang -c main.c
clang -c helper.c

You should now have main.o and helper.o.
Neither is a program, so try running one and see what happens.

Then hand both object files to clang to do only the link step:

clang main.o helper.o -o program

Now change one line in helper.c.
Which of the two -c commands do you actually need to rerun?

main.c calls a function defined in helper.c.

Try compiling just the one file:

clang main.c -o program

Read the error, then compile both together:

clang main.c helper.c -o program

Keep that first error in mind.
The one you are about to see in the next section is the same kind:
the linker being asked for code that was never given to it.

Linking Libraries (-l)

Your own files are not the only thing that gets linked.
Let’s think about printf.
You wrote #include <stdio.h>,
which gave you the declaration of printf.
You never provided the definition,
so where does the linker find it?

It comes from the standard C library, which is already compiled and sitting
on your machine, and which clang links into every program without being asked.
That is why printf has always just worked.

That only covers the library C considers its own.
Anything external to it, you have to name yourself, using -l.

The one you’ll hit first is maths.
pow and sqrt come from <math.h>,
but their code sits in a separate library called libm,
so you ask for it with -lm (read as “link m”):

clang mathy.c -o mathy -lm

Libraries that somebody else wrote and you installed are external too,
and every one of them follows this same shape.
OpenSSL, for instance, gives you cryptography functions,
and you reach for it the same way: #include <openssl/sha.h> for the compiler,
then -lcrypto for the linker.

Do you know how clang searches for stdio.h?
There’s a list of directories it searches, and -v prints it:

clang -v include.c

Warning

Forgetting -lm produces an error that looks nothing like the ones
you are used to:

undefined reference to `pow'

Notice that it does not mention a line number.
That is your clue that this is a linker error, not a compiler error.
The compiler was perfectly happy. The linker could not find the code.

Compile a program that calls sqrt, first without -lm:

clang mathy.c -o mathy

Read the error, then try again with the flag:

clang mathy.c -o mathy -lm

Summary

Just so that we stay grounded,
building a program has a compile step and a link step.
Compiling needs the declarations,
while linking needs the implementation.

Why not just #include "helper.c"?

You can, and for a single-file program it works.
It breaks as soon as a second file needs helper too:
both files end up with a copy of the body,
and the linker can’t pick between them.

That’s what the header split avoids.
The .h hands out promises, and exactly one .c holds the code.

Compiling Different Builds

Say you’re chasing a bug and you want the program to narrate what it’s doing:

for (int i = 0; i < 3; i++) {
  total += marks[i];
  printf("[debug] i=%d, total=%d\n", i, total);
}

Useful while you’re debugging, and something you’d never want in the version
you hand in.
So you delete the line, then a new bug turns up, so you type it back,
and round it goes.

What you actually want is one source file that can be built two ways.
That’s what #ifdef is for:

for (int i = 0; i < 3; i++) {
  total += marks[i];
#ifdef DEBUG
  printf("[debug] i=%d, total=%d\n", i, total);
#endif
}

Build it normally and the printf isn’t merely skipped, it isn’t in the
executable at all:

$ clang total.c -o total
$ ./total
total: 270

Then ask for it with -D, which defines the macro from the command line:

$ clang -DDEBUG total.c -o total
$ ./total
[debug] i=0, total=80
[debug] i=1, total=170
[debug] i=2, total=270
total: 270

This is called conditional compilation,
and unlike the if statements you write,
it’s decided while compiling,
and not during runtime.

conditional.c defines str differently depending on which macro is set.

clang -E -DIS_WINDOWS conditional.c

Notice you can define a macro without giving it a value.
Rerun with -DIS_LINUX and -DIS_MAC and compare what comes out.

Understanding Preprocessors

Note

It’s just copy paste.

You should be used to seeing these three things that start with #:
#include to paste in a header, #pragma once to stop it pasting twice,
and #ifdef to pick what gets compiled.

None of those are handled by the compiler.
They’re handled by the preprocessor, a step that runs first,
carries out the # lines, and passes plain C on to the compiler.
By the time the compiler starts, not a single # line is left.

The result is still valid C, just usually much bigger.
It isn’t normally saved anywhere, though by convention it’d be a .i file.
You can see it with -E, which stops after preprocessing:

clang -E include.c

The one directive you haven’t met yet is #define.

Macros are defined using the #define directive.
They can be used to define constants or even functions.
A way you can think about macros is that they are like find-and-replace rules.
For instance, if you write #define y 2 + 3 * 5,
the preprocessor will replace every instance of y with 2 + 3 * 5,
without evaluating the expression.

Below are some examples of macros:

#define PI 3.14159
#define max(a, b) ((a) > (b) ? (a) : (b))

Warning

As much as macros are useful, there are many pitfalls. See: https://gcc.gnu.org/onlinedocs/cpp/Macro-Pitfalls.html

Which finally explains the -DDEBUG trick from
earlier.
-D is just a #define written on the command line,
so -DPI=3.14 behaves exactly as if #define PI 3.14 sat at the top of your file.
#ifdef is then the preprocessor checking whether that define is there,
long before the compiler sees anything.

One catch: you cannot use -D to override a macro the source already defines.

Run clang -E macro.c and compare the output against the source.
Notice how each macro has been expanded.

macro.c also uses y without ever defining it,
so supply it from the command line:

clang -Dy=4 -E macro.c

Then try -DPI=4, when PI is already 3.14 in the code.
What happens, and does the catch above explain it?

Remembering the Flags

By now you’ve collected a handful of flags:

clang -g -Wall -Wextra -fsanitize=address,undefined compile.c -o compile

Typing that every time is a pain,
and it’s easy to leave one out by accident.
Instead, you can put the flags in a text file,
and pull them in with @<filename> when you compile.

Compile compile.c using the flags in compile_flags.txt:

clang @compile_flags.txt compile.c -o compile

View compile_flags.txt, each flag is placed on its own line.
Do you knwo what they mean?

Ensuring Code Quality

Compiling gets your code to run,
but running isn’t the same as being good.
Two kinds of tools help you keep your code clean.

Formatters

A formatter automatically arranges your code:
indentation, spacing, where line breaks go.
You stop fussing over layout, and everyone’s code ends up looking the same.
For C, the common one is clang-format.

Look at the messy file first:

cat messy.c

Then run clang-format on it and watch it tidy up:

clang-format messy.c

By default it prints the formatted code.
Add -i to edit the file in place.

Linters (Extra)

A linter reads your code and flags things that look wrong,
going beyond what the compiler warns about:
unused variables, suspicious patterns, common mistakes.
Think of it as a stricter, pickier reviewer.
For C, the common one is clang-tidy.

Run clang-tidy on the file and read what it complains about:

clang-tidy messy.c

Toolchains in Other Languages

While the tools (clang, clang-tidy, clang-format) are specific to C,
the ideas carry over.
Almost every language gives you the same three things:
a formatter to tidy your code,
a linter to catch mistakes,
and a way to build and run it.
In Python, for instance, you can opt to use black for formatting and ruff to lint.
Once you’ve seen the pattern here,
you’ll know what to look for in any new language you pick up.

The build and run step differs between languages.
In C it’s two separate steps: you build the code into an executable, then run that executable.
Python folds it into one: you just run the file, and the building happens behind the scenes.

C splits this into two steps: build, then run.
Why does Python do it differently, and what does it gain and lose by doing so?

Graded Task(s)

Bob ordered a pizza with three friends,
and when the box arrived, the slices were clearly not equal.
He suspects he got the smallest one,
and he wants proof before he starts an argument.

He has a ruler. He does not have a protractor.
So he measured the two straight edges of his slice,
and the straight-line distance between the two crust corners.
That is enough to recover the angle of the slice,
which is enough to get its area,
which is enough to prove he was robbed.

His phone is dead, so he is writing the calculator himself.
The trouble is he doesn’t know how to compile it,
because he usually asks his (other) friend to generate the scaffolding,
but unfortunately, that friend is away on a trip.
You are the backup friend.
He sends you the code, and a build script build.sh.
He wants two things done.

  1. Move the calculation functions, those functions starting with pizza_,
    into a new file.
  2. Compile the two files into a single program

Why can't Bob do the refactor himself?

Well… being a Nano user, he accidentally opened Vim, and chaos ensued.
Look at the file to see what happened.

Enter the Graded Task Folder

Enter ~/tutorial-graded before starting

Ensure you complete every task listed here

  1. Move every function starting with pizza_ into a new file helper.c,
    put their declarations in helper.h, and include the header from main.c

  2. Format main.c, helper.c, and helper.h with clang-format

  3. Fill in compile_flags.txt and update build.sh to compile both source files

    • The compiled program should not print r=... c=...,
      but Bob should be able to turn it back on without editing the source code
    • Keep the compiler flags in compile_flags.txt, not in build.sh
  4. Run verify . from ~/tutorial-graded to complete the task:

    abc@tut9:~/tutorial-graded$ verify .
    

Before you leave: verify your progress

Run this command inside your Tutorial environment:

progress

It shows whether you have successfully completed the tutorial and which
individual tasks have been recorded as complete.

The progress command is available only inside a Tutorial environment, not in
the general CS1010 WebTop environment.