Sample Video Frame

Created by Zed A. Shaw Updated 2024-02-17 04:54:36

Exercise 1: Dust Off That Compiler

2024 Note: I mention a "PDF" in the video but that's not available anymore. Also, your error output might be different as compilers may have improved their error detection.

After you have everything installed, you need to confirm that your compiler works. The easiest way to do that is to write a C program. Since you should already know at least one programming language, I believe you can start with a small but extensive example.

#include <stdio.h>

/* This is a comment. */
int main(int argc, char *argv[])
{
    int distance = 100;

    // this is also a comment
    printf("You are %d miles away.\n", distance);

    return 0;
}

If you have problems getting the code up and running, watch the video for this exercise to see me do it first.

Breaking It Down

There are a few features of the C language in this code that you might or may not have figured out while you were typing it. I'll break this down line by line quickly, and then we can do exercises to understand each part better. Don't worry if you don't understand everything in this breakdown. I am simply giving you a quick dive into C and promise you will learn all of these concepts later in the book.

Here's a line-by-line description of the code:

There's a lot of information in this breakdown, so study it line by line and make sure you at least have a grasp of what's going on. You won't know everything, but you can probably guess before we continue.

What You Should See

You can put this into an ex1.c and then run the commands shown here in this sample shell output. If you're not sure how this works, watch the video that goes with this exercise to see me do it.

$ make ex1
cc -Wall -g    ex1.c   -o ex1
$ ./ex1
You are 100 miles away.
$

The first command make is a tool that knows how to build C programs (and many others). When you run it and give it ex1 you are telling make to look for the ex1.c file, run the compiler to build it, and leave the results in a file named ex1. This ex1 file is an executable that you can run with ./ex1, which outputs your results.

How to Break It

In this book, I'm going to have a small section for each program teaching you how to break the program if it's possible. I'll have you do odd things to the programs, run them in weird ways, or change code so that you can see crashes and compiler errors.

For this program, simply try removing things at random and still get it to compile. Just make a guess at what you can remove, recompile it, and then see what you get for an error.

Extra Credit

Previous Lesson Next Lesson

Register for Learn C the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.