Using the C compiler

The best way to learn C is to study examples , then compile and run them. Below we will work through one of these from beginning to end. You will see how to write the program, compile it, and run it.

There is also an on-line reference manual . It is not complete, but covers the basics. See the excellent book by Kernighan and Ritchie for a more information.


Writing your first C program

Let us write a program which displays the message " hello, world" on the screen. It looks like this:

  #include <stdio.h>
   main()
   {
     printf( "Hello, world" );
   }

The first step is to create a file called hello.c which consists of the five lines above. One way is to use the cat command, like this:

  % cat >hello.c
  (type in the text of the program) 
  (type control-D)
  %

For longer programs use an editor, e.g., emacs to do your writing. To check that the program is there and that we made no typing mistakes, we use ls and cat as follows:

  % ls hello.c
  % cat hello.c

The first command will tell us whether the file exists. The second one will display its contents (good for short files only).


Compiling and running the program

Now we must translate the program from a form which we understand to one which the computer understands. This is what the compiler ( cc or gcc ) does.

  % cc hello.c
  % a.out
  Hello, world
  %

The cc command did the translation and put the result in the file a.out. Using a.out as a commmand runs the program and so displays the message Hello, world

Another way to do things is like this:
  % gcc -o hi hello.c
  % hi
  Hello, world
  %

This time we used gcc instead of cc, and we used the -o option to name the translated file hi. Using hi as a command runs the program.


Notes: