Archive for the ‘CS210’ Category

Monday
September 10

UNIX and C

By dschatz

How to build and run C programs on a unix system

For the purposes of this tutorial I will assume you are logged into a
Linux machine in the undergraduate lab in EMA 304

Writing, compiling, and running Hello World

Begin by opening gedit. You can find gedit under the bottom left menu
-> Accessories. Type in the hello world program as seen in the
image below

Note that gedit is just a text editor. There are many different text
editors that you can use, some include emacs and vi/vim. Feel free to
explore the many options provided to you. Several links are on the course
web page to help you.

To save the file you should create a directory in your home folder to
organize your files. Think of your home folder as your user directory on
a Windows machine. Perhaps you should create a directory called Classes
with a subdirectory for CS210 where you will save all your class
files.

Save the file as helloworld.c – you should notice that after saving it
as a .c file, gedit will apply syntax highlighting to the file

Open up the terminal under the bottom left menu -> System Tools. You
begin in your home directory. Try to change directories so that your
current directory is the same as the directory where you have saved your
c file. The command to change directories is cd. You can see the
contents of the current directory by using the command ls.

Your terminal may look different than the image below but the commands
should still be the same (with different directory names)

You can see the contents of your helloworld.c file by typing cat
helloworld.c
. You should see that the contents are exactly the text that
you entered into gedit with no extra markup or formatting.

To compile your program we will use gcc, the Gnu Compiler Collection
(see the course webpage for links for more information). Type gcc
helloworld.c -o helloworld
. This command invokes gcc to compile your c
file and output the executable as helloworld (with no extension). Were
there any errors? If so double check that you are in the correct
directory and make sure you entered the right code.

You should now see a new file, helloworld, in your current
directory. To execute your program, type ./helloworld. You should see
the expected output of your program.

Now make a change to your hello world program to have it print out
something different. Save the file and go back to the terminal. What do
you expect to see when you run the helloworld program this time? Try it
out and see if what happened matched your expectations.

You should see that the same text as before was printed out. This is
because the executable was built when you compiled from the previous
version of the code. So to update the executable, you should run the
compile command again.