Objectives: Learn how to use UNIX directories. Learn how to edit a C++ program. Learn how to compile a C++ program. Learn how to execute a C++ program. Learn how to print files.
|
|
Sections:
Introduction
In the early days of computing, all programmers programmed
the computer using machine language because that is the only language that the
computer really understands.
However with the advent of compilers,
programmers today typically use high level languages,
that is, languages very close to the written word.
Examples of high level languages include C++, C, FORTRAN, Java, and Python.
Today programmers may use C++, for example, to provide instructions to
the computer instead of using machine language. Because the only language that
a computer understands is machine language,
we must have some type of translator
that is able to take a C++ program (source code) and translate this code
to machine language. This translator is called a compiler. A C++ compiler
takes C++ source code and translates this code into executable code
(the machine language version of the C++ source code).
This lab is an introduction to the UNIX
C++ compiler and its programming environment.
The language C++ was designed by Bjarne Stroustrup of AT&T Bell Labs in 1983. "Its main purpose is to make writing good programs easier and more pleasant for the individual programmer. C++ evolved, and continues to evolve, to cope with problems encountered by users, and through discussions between the author and his friends and colleagues."
As you work through this lab, you will be asked to do several exercises (see sections in red). Some exercises are provided for your learning experience. Some exercises will be used to determine your grade on this lab. Some exercises request that you generate a printout. Do all exercises to be successful on this lab. If you have not already done so, click on the link in the top right-hand area to create an answer sheet window.
Logging on to ranger
The computer system you will use for CSCI 1170 & CSCI 2170
is named ranger.
(Actually, ranger is an umbrella name for several actual machines,
such as ranger0 or ranger2. Because it doesn't matter which
particular ranger machine you are using, we'll just say ranger.)
Ranger runs the UNIX operating system,
an extremely powerful and popular system.
There are different "dialects" of UNIX,
such as Mac OS X or HP-UX.
The UNIX dialect running on ranger is called Linux.
Use your course account information to access ranger. For Login username enter your course account's C-number (that is, the 8 character login username you were assigned; for example, c0155913). For Password, enter your course account's password; for example 74ab2w45. Your password will not be displayed so be careful in your typing.
If you have trouble logging in ask a lab assistant for help.
GETTING A "better" TERMINAL WINDOW:
Once you have an active UNIX login,
you will likely want to open up a "better" Terminal window.
It is "better" in the sense it is clearer to read and easier to change
the font size. (For reference: this "better" terminal window comes
from running an application called sakura.) Enter the
following command
$
terminal &
The UNIX Operating System
The UNIX operating system was developed by Ken Thompson and
Dennis Ritchie of AT&T Bell Labs in the early 1970's.
UNIX (also often written "Unix") is not an acronym;
it is a pun on MULTICS, a failed system AT&T was experimenting
with when Thompson began the UNIX development.
Thompson, Ritchie, and their associates were programmers
who chose short names for UNIX commands. Short names
are great for poor typists but often cause confusion for a novice. UNIX commands
are usually named with the first two consonants from a word that (sort of) describes
the purpose of the command. They (and almost everything) are always in lower
case letters. For example, cp is for copy, rm
is for remove (delete), ls is for list
(directory); vi is for visual editor (oops!), and lp
is for line printer.
Exercise
2:
TIP: To make the answer sheet window active, click on Exercise 2 link
above. After you have placed your answer on the answer sheet,
minimize the window containing the answer sheet (click on the '-' on
the title bar) to continue the lab.
(Type your answer on the answer sheet. If you have not already done so,
click on the link in the top right-hand area to create
an answer sheet window.)
What is the name of the operating system we are using in this course?
(Don't get confused and give the dialect name.)
Before we learn how to use a few UNIX commands, we will explain what we mean
by a "file," the thing(s) most UNIX commands operate on. A file is an electronic
repository for information. A file could hold the text of a letter to a
friend, a set of high-level (text) instructions to the computer, or a collection
of binary (non-text) machine instructions readable only by the computer. A
directory is a collection of (related) files. If a manilla folder is an analogy
for a file, then a filing cabinet drawer would represent a directory.
You will need a file for experimentation.
It should be copied from a directory that will
be used throughout the course. One directory can contain another can contain
another, etc. In UNIX the directory names are separated by a "/" as in
/nfshome/cs2170/public_html/public.
The actual name of the file (we call it the basename)
goes at the right end
separated from the directory name that contains it by a "/".
USING THE TERMINAL WINDOW: Much of UNIX is "command driven"; that's a fancy way of saying that to get most things done, you type out command instructions inside a Terminal window instead of clicking on icons. UNIX is case-sensitive, that is, it distinguishes between upper and lower case letters. It is important to type the commands exactly as indicated. Failing to put in a space where required is an error; however when a space is required, the amount of space (i.e., the number of blanks) is usually not critical.
The default Terminal window size is 32 rows long and 80 columns wide
(historically the default was 24 x 80; we've upped it a bit);
that is what we usually want it to be.
You can resize a window by placing the mouse over the
top or side window edge, then click the left mouse button, hold and drag.
Although the Terminal window can be resized,
it MUST be at least 24 rows long and 80 columns wide.
Any smaller than these minimum dimensions and certain commands get messed up.
You can check the current size of your window by entering the following UNIX command:
$
stty size
(Do NOT enter the $ sign as part of your
command. It is meant to represent the prompt provided by the system.)
This will display the number of rows followed by the column width.
If the window is too small, resize it larger.
Exercise 3:
Check the current size of your window by entering the following UNIX command:
Next copy the file cla2a.cpp
from the CS department 2170 closed lab directory to your account area
by typing the command below at the prompt in the Terminal window
(Note: most UNIX commands, this is one of them, are silent
when they work correctly.
Thus you will not get any confirmation that you successfully
copied the file---it will simply happen and you'll get another
system prompt.)
Make the Terminal window active.
$
stty size
$
cp $CLA/cla2a.cpp cla2a.cpp
In later sections you will learn how to create a file of high-level C++ source instructions with the "vi" editor and how to use the C++ compiler to create an executable file of machine instructions suitable for running on ranger. First, we explain a few simple commands. Read this section first, then do the exercises below.
To display a (text) file named cla2a.cpp on the screen, type
The command cat
(short for "catenate", an old version of the word "concatenate") displays
(catenates it to what is already on the screen) the contents of the file cla2a.cpp
on the screen. If it is longer than one screen (usually 32 lines), the first
part of the screen scrolls off the top of the screen as other lines are displayed.
You will have to be a speed reader to keep up. To see one screen at a time,
use the "more"
command instead of "cat". More
displays the first screen of text from cla2a.cpp and waits for you to press
a key. Pressing a carriage return advances one line; the space bar
advances one screen of text; typing "q" will quit (exit); typing
"/" followed by a word
or phrase (and return) searches for the first occurrence of the given word
or phrase.
The "less" command is similar
to "more", but more advanced.
(The pun here is that "less is more".)
The Computer Science Computer Lab has several laser printers.
The default laser printer is cs360
and is located in KOM 360 towards the back of the room.
The laser printer in KOM 350 is cs350 and
the laser printer in KOM 351 (to the right of the entrance to KOM 360)
is cs351.
To send a copy of the file cla2a.cpp to the cs351 laser printer,
type
To send a copy of the file cla2a.cpp to the cs360 laser printer, type
and it will print to the same laser printer as the lengthier command above.
Usually each student is expected to obtain her/his own printout from the printer.
xxxx
If you want the lines numbered, use
"pr" is a UNIX formatting command -- it does things
like number the lines as they are being displayed
or change the output appearance of tabs (using -"e4").
The > symbol between "pr" and "temp" is the
UNIX file redirection symbol.
It makes the output from "pr" (which usually goes to the screen)
go to the file "temp" instead.
In turn, you use lph to print the file "temp" and then
"rm" to remove/delete file "temp".
$
pr -n -t -e4 cla2a.cpp > temp
$
lph temp
$
rm temp
Your printout can be found on the printer in KOM 351 (to the right of the entrance to room KOM 360). This hardcopy printout must be turned in with your answer sheet at the end of the lab.
Exercise 6:
We will not tell you to make the Terminal window active
anymore when we ask you to enter a command. YOU SHOULD REMEMBER TO DO IT ON
YOUR OWN.
By trying them, convince yourself that these two command lines accomplish the same end result (there is nothing to turn in as a result of this exercise):
$ cat cla2a.cpp | pr -n -t -e4
$ pr -n -t -e4 cla2a.cpp
Exercise 7:$ pwd
to print (display) your working directory name. Enter your working directory name on the answer sheet. Remember, to open the window containing the answer sheet, click on "Exercise 7:" link above.
The "ls" command displays a list of file names in the current working directory. A directory is like a drawer in a file cabinet that holds the files (the manilla folders). You can see (display) the list of files in your directory by typing
$ ls
or
$ ls -l (Note: use letter 'l' not the number '1')
The "-l" option ('l' for long) gives information about the file, as well as its name, such as its size and its protection (privilege or mode) bits: rwxr--r--. These bits describe what you (the owner) and others can do to the file: r = read; w = write; x = execute. If the first character on a line is a 'd' then the file is a directory (and not a regular file). If you were successful customizing your account, you should have directories. Find them.
To learn more about the "ls" command (or any UNIX command) use the "man" (short for "manual") command, as in
Notice that "man" uses more to display the file to the screen. Use
'q' to quit! Man is the UNIX on-line help command. If you don't know what
command to use for a task, like printing, you can use
('k' for keyword search) to get a list of UNIX commands that relate to the word "print."
Exercise
10:
To make a backup copy of the file cla2a.cpp, type in
the following command in the Terminal window.
Now there are two files (named cla2a.cpp and cla2a.bak) that contain exactly the same information.
If you want to keep it, you can copy it again. Be careful
when you delete files. Once they are deleted, you can not get them back. There is nothing to turn in as a result of this exercise.
Exercise 12:
To organize your account, we created directories OLA
(stands for Open Lab Assignments) and CLA (for Closed Lab Assignments)
during customization to hold your C++ open lab files and closed lab files.
Move the file
cla2a.cpp
into the CLA directory by typing
$ mv cla2a.cpp CLA
Change your working directory to CLA by typing
$ cd CLA
Dot-dot ("..") is a special name for the parent directory while "cd" by itself always returns you to your login (home) directory from wherever you are. Type one of the "cd" commands shown above in the Terminal window now.
$ mkdir mystuff
To make mystuff your current working directory, type
Now change back to the parent directory. (Type the "cd"
command in the Terminal window now.)
Remove the mystuff directory by entering
$ rmdir mystuff
Finally change to the CLA directory.
Important Note:
Even if not stated explicitly in a closed lab writeup,
all of our future CLosed Labs work must
be placed in this CLA directory.
The "vi" Editor
Read the following. Do not type in any commands until you start the next
exercise!
In the computer world, an editor is a program that facilitates the creation and modification (editing) of a text file. For us the text file will usually be a C++ source file (i.e. a file of instructions to the computer written in the syntax of the C++ language). To create a new file, say lab.cpp using vi (visual editor), you would type
$ vi lab.cpp
and press enter. Assuming lab.cpp does not already exist, you would see a clean screen with a line of '~' on the left.
$ vi cla2b.cpp
Before you type this command in the Terminal window, drag the top or bottom border of the Terminal window so it is as large as it will extend vertically.
Exercise
14:
Type in this command in the Terminal window.
$ vi cla2b.cpp
You should see a clear screen except for a column of
tilde (~) characters, a cursor, and perhaps a brief message on the last line.
If you do not, ask for help from your lab assistant.
Do not start typing until you read this entire section.
The vi editor has three modes: the command mode, the insert mode and the last line mode. The vi editor always begins in the command mode. The command mode is used for moving the cursor, deleting text, moving text, and other functions; the insert mode is used for entering and changing text; the last line mode is used to type in vi commands to allow one to go to a particular line, to cause indentation, etc.
As mentioned above, vi always begins in command mode. When in command mode, vi is controlled by one or two letter commands. You can not use the arrow keys to move around the screen nor can you just start typing and have what you type appear in the document.
How do you get into insert mode? In vi, when you want to insert (add) something, you type one of the following one letter commands
Once in insert mode (you have typed in one of the commands above), what you type can and will be held against you (i.e. it is inserted into the file). While typing you can use the backspace key to erase previously typed characters. Obviously, once you are in insert mode the one letter commands to vi like 'i' or 'a', do not work. To change back to command mode, you must press the ESC key to exit insert mode.
Exercise 15: It is time for all
good men to come to
the aid of their planet.
We are done inserting text, so exit insert mode by pressing the ESC key. Do these steps NOW in the Terminal window before proceeding.
Because beginners tend to forget to leave the insert mode before they type another vi command, commands often end up being inserted into their text.
Read the following before attempting the next exercise.
How do you delete selected text? When in command mode, the character on which the cursor is sitting can be deleted by pressing 'x' while 'X' deletes the character to the left of the cursor, if there is one. To delete a whole line press 'd' twice, i.e. "dd". If you press a number before the "dd", say 5, it will delete 5 lines starting from the cursor. You can use this technique to move a block of lines from one place in the file to another. Suppose you want to move 15 lines. Put the cursor on the first line, press "15dd", then move the cursor to where you want the deleted lines placed. Press 'p' (for paste) to put them below the cursor or 'P' to paste them above the cursor. Of course if you delete something else in the interim you will lose the 15 lines from the buffer and can not restore them.
How do you move the cursor? Make sure you are in command mode (press ESC if in doubt). There are two simple ways to move down one line: Press the ENTER key or a 'j'. There are two simple ways to move up one line: press the minus key '-' or 'k'. There are two simple ways to move right one character (position): press the space bar key or 'l'. The letter 'h' moves you left one position. You can move any number of lines or characters by typing a number followed by the key for the direction: "20j" moves down 20 lines; "60<space bar>" moves across 60 characters on the current line.
When in command mode, to move a screen at a time use CTRL-f (for forward) and CTRL-b (for backward). To see what line you are on use CTRL-g (look at bottom left of screen). To search forward for a string press '/' followed by the string and a return. To search backward press '?' followed by the string. To go to a specific line press ':' (this command always gets you into last line mode). Now follow by typing in the line number (and return), e.g. ":0" takes you to the top of the file while :50 places the cursor on line 50 of the file.
If you want to save changes you have made without exiting, to be prepared in case of a power failure use ":w" ('w' for write). To use any UNIX command without leaving vi type ":!<command>" for example ":!ls" to see a list of files on the current directory. To exit vi without saving changes made to the file press ":q!". Usually you will exit and save the changes with ":wq". If it appears on the screen you are in insert mode. Press ESC first.
and edit with
Comments in a C++ program appear after two slashes (//) or between a slash-asterisk and asterisk-slash pair (/* */). The comments in this program describe what should be corrected to make this program work. Read the comments in cla2c.cpp and correct each line with an error on it. After you are finished with the corrections, save it. Use the vi commands described above to accomplish this.
Compiling and Capturing a Terminal Session
$ c++ cla2c.cpp
or
$ c++ cla2c.cpp -o cla2c
In the first version, the executable file is called, by default, a.out while in the second version it is called cla2c (because of the -o cla2c; o for output). Hopefully, you will not receive any errors at this point if you were careful on the last exercise. However, if you do receive errors, you must edit the source program to remove the errors before you can go on the next exercise. To edit the source program, you must use scite again.
Exercise 20:
"Run" or "execute" the program by typing the name of
the executable:
$ a.out
or
$ cla2c
(Only one of these will work depending on the compile command from Exercise 19)
The program should cause the statement "Enter the first test score:
" to appear on the screen. The program now "waits" for you
to enter the first test score. Type in the following three test scores after
each score is requested:
90
80
65
and the program will then display the average of the test scores.
If you must edit, compile, and run repeatedly, you can avoid some typing by taking advantage of a shorthand notation. Typing "!s" at the UNIX prompt will reexecute the most recent command starting with an "s" like "scite". Entering "!c" would redo the most recent command starting with "c" -- probably c++, but beware, maybe a.out, depending on which was most recent. You can enter additional characters after the exclamation mark to retrieve the most recent command you entered that started with those letters; for example, you could enter "!c+" or "!c++" if you wanted to be sure to retrieve your most recently issued c++ command. Two exclamations (!!) reexecutes the last command.
Once our program works, we will need to get a printout of the changes, the compilation, and the results. That is, we need to capture a terminal session in a file so we can print it. In UNIX this is done with a program called "script". You start script by typing "script" followed by a file name for saving the session. Warning: Do not use the name of your source file! Once everything is in the log (script) file you want, type exit to close it.
Usually when we turn in a program we will want a source listing, perhaps with line numbers, a compilation (without errors), and a run showing inputs and outputs.
$ script lab2vex21.log
$ pr -n -t -e4 cla2c.cpp
$ c++ cla2c.cpp -o cla2c
$ cla2c
$ exit
Submit the log file by typing
One last thing to do!
From the PC you are working on, you must also submit the answer sheet
(AnswerSheet2v.pdf) using the following directions:
Exercise 22:
Congratulations!
You have finished Lab 2v.