Goals for this week:

  1. Practice compiling and running C programs: gcc and using make.

  2. Help getting started with set-up for Lab 1

  3. Introduction to Lab 1 and C syntax.

1. Setting up the lab directory

Let’s start by creating the directory structure and copying over some files (you may have some of this directory structure already created from Lab 0).

Do not type the $, that is the unix prompt. Comments about the command are after #.
$ cd                     # cd with no argument switches to your home directory (/home/you/)
$ mkdir cs31             # create a directory named 'cs31'
$ cd cs31                # cd into cs31 (change current working directory to cs31)
$ pwd                    # print the current directory name
/home/you/cs31           # the shell will respond with your current location
$ mkdir labs             # create a 'labs' directory
$ mkdir inlab            # create a `inlab` directory
$ cd inlab
$ pwd
/home/you/cs31/inlab     # the shell will respond with your current location
$ mkdir week01           # create a 'week01' directory
$ cd week01
$ pwd
/home/you/cs31/inlab/week01

# USAGE: cp <source> <destination>
$ cp ~richardw/public/cs31/week01/*  ./   # <-- the dot means "here" (the current directory)
$ ls
firstprog.c  functions.c  Makefile  README

There is a Using Unix guide on the CS Swarthmore helppages that contains some helpful information: https://www.cs.swarthmore.edu/help/basic_unix.html.

2. C Programming

2.1. Compiling and running C programs

C is a compiled language. Compilation is a process that translates C program code in a C source file into a binary machine-code form of the program that the system knows how to execute (the computer doesn’t understand high-level languages like C or Python or Java, instead it understands low-level machine code). If compilation succeeds (there are no syntax errors in your code), the compiler creates an executable file (the deafult name of which is a.out) that you can run from the comand line. For more info, refer to the basics of compiling and running C programs.

We’ll use the gnu compiler, gcc, to translate C to an executable form:

$ gcc firstprog.c

Then enter the path name of executable file on the command line to run it:

$ ./a.out

gcc supports command line options to include debug information in the executable file (-g) and to specify the name of the executable file (-o filename) rather than use the default "a.out". Let’s try it out on one of the files you copied over:

$ gcc -g -o firstprog firstprog.c
$ ./firstprog

Along with the code you copied over, there’s a Makefile. The Makefile contains rules for compiling executables from the .c source files. To execute these rules, type make command:

$ make        # this will compile all files as specified by the all: rule

make is a convenient way to compile without having to type in a long gcc command every time.

To clean up all the files that were compiled by make, you can run make clean:

$ make clean  # this removes all files generated by make (the can be rebuilt)

2.2. First C program: main, variables, printf

Let’s open firstprog.c in an editor. You can use whatever editor you feel comfortable with, including vim or emacs. You can also open these remotely in atom or Visual Studio Code (vscode) if you have those set up.

$ vim firstprog.c    # Choose whichever editor you are comfortable with.
$ emacs firstprog.c  # Only run one of these two lines (or use atom/vscode)

Look for examples of:

  • C comments

  • How to import a C library (stdio.h)

  • The main function definition, function bodies ( { } ), and C statements (end in ;)

  • Defining constants

  • Declaring variables (note all are declared at the top of the main function)

  • printf function (similar to Python print function with print formatting)

  • Note that all the code is inside the body of a function!

Now let’s compile and run the program:

$ make
$ ./firstprog

There is a suggestion for changing the code in a TODO comments. Let’s try adding to do that together. When we change the code we need to save it in our editor, and then recompile the program before running it again:

# edit firstprog.c, then save and quit the editor before you run lines below
$ make              # recompile
$ ./firstprog       # run
Save and Recompile

If you have used Python you may be used to making changes in your editor, saving, and running it immediately. In C, there is one extra step between saving the file and running which is recompiling it. Every time you change your C program, you have to recompile it to build a new binary

2.2.1. printf formatted output

printf uses placeholders for specifying how a value should be printed (how its series of bytes be interpreted). See firstprog.c for examples. Here is a brief summary:

Specifying the type:
   %d:   int     (ex. -234)
   %f:   float or double (ex. -4.34)
   %g:   float or double
   %s:   string  (ex.  "hello there")

2.3. Functions program

Let’s next open the functions.c program and look at an example of a C function. I will use vim in this example, but you can use any editor you would like.

$ vim functions.c

And let’s look at examples of:

  • Function Definition

  • Parameters and local variable declarations

  • Return type

  • All function bodies are between ( { } )

  • Function Call

  • Function Prototype

Then compile and run to see what this program does:

$ make
$ ./functions

There are some TODO comments in functions.c with some suggestions for things to try out in this code. We encourage you to try them on your own.

2.3.1. more about C functions

The syntax for functions in C is similar to that in Python, except that C function definitions must define the return type of the function and type and name of each parameter. Here are two examples:

/* sum: a function that computes the sum of two values
 * x, y: two int parameters (the values to add)
 * returns: an int value (the sum of its 2 parameter values)
 */
int sum(int x, int y) {
   int z;      // a local variable declaration

   z = x + y;  // an assignment statement
   return z;   // return the value of the expression z
}

/*
 * a function that does not return a value has return type void.
 */
void blah( ) {
   printf("this function is called just for its side effects\n");
}

An example of calling these two functions from main looks like this:

int main() {
   int p;             // local variable declaration

   p = sum(7, 12);    // call to function that returns an int value
   printf("%d\n", p);
   blah();            // call to void function (doesn't return a value)

   return 0;
}

3. C debugger: gdb

The GNU debugger, gdb, is the C debugger we will use in this class. Usually, we will use gdb to debug a program, but this week we are going to use gdb as calculator.

gdb’s print command can be used to print the value of a expression in different representations (binary, decimal, hex); you can use it as a simple calculator to verify answers to hex, binary, and decimal arithmetic. For this use of gdb, we don’t have to have an executable to run gdb on. We can just run gdb, and then call its print command:

$ gdb

# print an expression in different representations:
# (/t in binary, /x  in hexadecimal, default is decimal):

(gdb) print/t 1234       # print/t: print decimal value 1234 in binary format
(gdb) p/t 1234           # p is shorthand for print
(gdb) p/x 1234           # p/x: print value in hexadecimal format
(gdb) p/d 1234           # p/d: print value in decimal format (the default)

# 0x is the prefix for a hexadecimal literals
# 0b is the prefix for a binary literals
# no prefix:  for decimal literals

(gdb) p 0xabf1           # print the hex value abf1 as decimal
(gdb) p 0b0101           # print the binary value 0101 as decimal
(gdb) p/t 0x1234         # print the hex value 0x1234 as binary
                         # (note: leading 0's are not printed out)
(gdb) p/d 0b1010         # print the binary value 01010 as decimal
(gdb) p/x  0b10100000    # print a binary value in hex

# add a binary and a hex value, print result in binary
(gdb) p/t 0b101001001 + 0xa2

# you can re-cast a value as a specific C type:

# tell gdb that the value 12 is a char (1 byte) and print as binary
(gdb) p/t (char)(12)
(gdb) p/t (char)(-12)   # print -12 char value (1 byte) in binary
(gdb) quit

4. One-time git / GitHub configuration

Before using Swarthmore’s GitHub Enterprise, you’ll need to complete some one time setup steps. Once you’ve done that, you should follow steps to clone your Lab1 repo using git: GitHub for lab checkout

You should already have this running from Lab 0, but if you need help we can help you after we introduce Lab 1.

5. Lab 1 Intro

Next, we’ll take a look at the first lab assignment. Note that all course assignments and lab practice (in-lab work, lab assignments, and homework assignments) will be posted to the Schedule part of the course webpage.

6. Handy Resources