Week 01 (Wednesday)

C Program Structure1/18

Each C program consists of



A Makefile helps to organise the compilation of modules of a C program


seqq: seqq.c
	gcc -Wall -Werror -o seqq seqq.c

The UNIX command make

... Makefiles3/18

Can have multiple targets:

example: a.o b.o c.o
	gcc -o a.out a.o b.o c.o

a.o: a.c
	gcc -Wall -c a.c

b.o: c.c
	gcc -Wall -c b.c

c.o: c.c
	gcc -Wall -c c.c

Module Interfaces4/18

Names are shared via module interfaces

... Module Interfaces5/18

Example module interface stdio.h

typedef FILE ...;

FILE *stdin, *stdout, *stderr;

FILE *fopen(char *fileName, char *mode);
int  fgetc(FILE *inf);
int  fputc(int ch, FILE *outf);
char *fgets(char *strbuf, int max, FILE *inf);
int  fputs(char *str, FILE *outf);

Many more examples available in .h files under /usr/include

Exercise: MyInt module6/18

Design an interface to a module that provides:

Provide an implementation, testdriver and Makefile for the module.

... Exercise: MyInt module7/18

Can generalise the Makefile by defining and using variables

Can also add a target to clean up directory


CFLAGS=-Wall -Werror

tester: tester.o MyInt.o
	$(CC) $(CFLAGS) -o tester tester.o MyInt.o

tester.o: tester.c MyInt.h
	$(CC) $(CFLAGS) -c tester.c

MyInt.o: MyInt.c MyInt.h
	$(CC) $(CFLAGS) MyInt.c

	rm -f tester tester.o MyInt.o core

... Exercise: MyInt module8/18

# General structure of a Makefile

target: dependencies

C Execution: External View9/18


... C Execution: External View10/18

Command-line arguments:

File streams: Environment variables:

... C Execution: External View11/18

Example argc and argv:


C execution: Startup12/18

All C programs must have a main() function.

Executing a C program causes main() to be invoked

Program execution stops when the main() function returns. (In fact, any non-zero value indicates execution errors; can use different values for different errors; check return status via $? in Unix shell)

C execution: Redirect13/18

The streams stdin, stdout, stderr can be redirected

C execution: Memory14/18

An executing C program partitions memory into:

... C execution: Memory15/18



Lifetime: duration that a variable is available in memory.

Variables in the global data ...

Objects in the heap ... Objects in the stack ...

Exercise: Buggy Function17/18

Explain what is wrong with this function:

// returns a string of 'x' characters
// e.g. xs(5) -> "xxxxx", xs(0) = ""
char *xs(int n) {
	int i;
	char buffer[100];
	// truncate if try to add too many 'x's
	if (n > 100) {
		n = 100;
	} else if (n < 0) {
		n = 0;
	for (i = 0; i < n; i++) {
		buffer[i] = 'x';
	buffer[i] = '\0';   // terminate string
	return buffer;

How could we fix the problem?

Tips for Next Week's Lab18/18

Command line arguments; Makefiles

Produced: 11 Aug 2016