Basic compiling on the Unix

Purpose

To provide basic information on how to compile your C program on Unix. This page is intended for people who want to practice programming C now. This material will be greatly supplemented later in the course.

Compiling your program on Unix

The Unix command for compiling C code is gcc. This is a compiler from Gnu for Linux. If you are using a Unix machine like Solaris you may need to use the command cc.) When you compile your program the compiler produces a file containing binary code which is directly readable by the machine you are on. This file is called an executable file, because it can be executed by the machine. But this executable file may not be readable on other machines. ANY program you want to run on a department machine, you should compile on a department machine. DO NOT transfer the executable file from one machine to another. It is best to recompile the code.

Suppose you have a file hello.c which you want to compile (or use hello.c.) Type the following on the command line
       gcc hello.c
If no error messages were printed to the screen, your code compiled. Now do ls and you will see a file called a.out. By default, gcc places the executable into this file, overwriting any existing file of the same name. You specify the name of your executable, say hello by the following line:
       gcc hello.c  -o hello
If your code compiled you will see the file hello in your directory. It is that easy.

To run your file, you need to make sure that the user file permission for that file is set to x for executable. Just type the name of your executable on the command line:
       hello
If you happen to recieve a message from the shell that it cannot find the file, then you will need to type:
       ./hello
What happened is that when you type a command, the shell has to look for the executable to run the command. It does not assume that the executable resides in your home directory. In fact it has a very specific order of directories in which it looks for executables. If it does not find the executable in any of these it gives up its search. It may be that your shell is not set-up to look in your current directory. By typing ./hello you are telling the shell exactly where to go to find the executable: your current directory (.). You can see the search path using the shell variable $PATH,
       echo $PATH
what you will see is a colon-separated list of directories. The shell searches these directories from left- to-right. For example, on my current machine I recieved
       /home/kaharris/bin:/usr/local/bin:/usr/X11R6/bin:/usr/bin:/bin:/usr/include:.
The last directory searched is my current directory.