Total Pageviews

Saturday, November 13, 2010

Lesson 23 - C-Using C with UNIX

A little knowledge is necessary before you can write and compile programs on the UNIX system. Every programmer goes through the same three step cycle.

Writing the program into a file
Compiling the program
Running the program
During program development, the programmer may repeat this cycle many times, refining, testing and debugging a program until a satisfactory result is achieved. The UNIX commands for each step are discussed below.

Writing the Program

UNIX expects you to store your program in a file whose name ends in .c This identifies it as a C program. The easiest way to enter your text is using a text editor like vi, emacs or xedit. To edit a file called testprog.c using vi type


vi testprog.c
The editor is also used to make subsequent changes to the program.

Compiling the Program

There are a number of ways to achieve this, though all of them eventually rely on the compiler (called cc on our system).

The C Compiler (cc)

The simplest method is to type


cc testprog.c
This will try to compile testprog.c, and, if successful, will produce a runnable file called a.out. If you want to give the runnable file a better name you can type


cc testprog.c -o testprog
This will compile testprog.c, creating runnable file testprog.


Make, a Program Builder

UNIX also includes a very useful program called make. Make allows very complicated programs to be compiled quickly, by reference to a configuration file (usually called Makefile). If your C program is a single file, you can usually use make by simply typing


make testprog
This will compile testprog.c and put the executable code in testprog.


Improved Type Checking Using Lint

The C compiler is rather liberal about type checking function arguments, it doesn't check bounds of array indices. There is a stricter checker called lint which won't generate any runnable code. It is a good idea to use lint to check your programs before they are completed. This is done by typing


lint testprog.c
Lint is very good at detecting errors which cause programs to crash at run time. However, lint is very fussy, and generally produces a long list of messages about minor problems with the program. Many of these will be quite harmless. Experience will teach you to distinguish the important messages from those which can be ignored.

Running the Program

To run a program under UNIX you simply type in the filename. So to run program testprog, you would type


testprog
or if this fails to work, you could type


./testprog
You will see your prompt again after the program is done.

No comments:

Post a Comment