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
which 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 ranger1 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.
LOG ON USING THE NX CLIENT:
We will be using a UNIX (xfce) Desktop environment
for all the exercises below.
To use the NX Client to connect to ranger,
double-click the mouse on the NX ranger Desktop icon
that looks like this:
Make sure the icon has the label NX ranger Desktop! When you double-click on the icon, you should get an NX login window:
Use your course account information to access ranger.
Inside the Login text box area
enter your course account's C-number
(that is, the 8 character login username you were assigned;
for example, c0155913).
In the Password text box area,
enter your course account's password; for example 74ab2w45.
Your password will not be displayed
but will echo as a row of asterisks, such as "********",
so be careful in your typing.
If you make a typing error, you will be asked to start over
by checking the Login username
and re-entering the Password information.
(If your configuration also requests the host,
enter ranger.cs.mtsu.edu)
After filling in the requested information,
click the Login button and after a few seconds
a full-screen window should appear (as depicted below).
We call this the UNIX Desktop window.
Note: If your new window is just a command window, then most likely you selected the wrong icon above, that is, it was not labeled NX ranger Desktop. If you are unsuccessful after several attempts, check to be sure the Caps Lock key is not locked on the keyboard. If it is, unlock it and try again. Otherwise, ask the lab assistant for help.
It may take a few seconds for the UNIX Desktop to appear and your window may temporarily be dark before finally fully displaying. This larger brownish window shows that your PC is properly connected to the ranger system. If you cannot get the UNIX Desktop window to appear, then ask a lab assistant for help.
GETTING A TERMINAL WINDOW:
Once you have an active UNIX Desktop,
you will open up a Terminal window.
There are several ways to open up a Terminal window.
The easiest is to double-click on the big desktop Terminal icon that,
on a customized account, is usually located in the upper left hand corner
of the UNIX Desktop and looks like this:
Alternatively, if the Terminal icon is missing, you can move your mouse to the top menu bar where the pull down selections for Applications Places System are located (top left) and select the Applications tab and then select the System item and then finally select the Terminal item.
Either way, you should now have a Terminal window
on your UNIX Desktop. (See picture below.)
You can move windows and arrange them as you like.
To move a window, click the left mouse button on the title bar of the window,
hold it down and drag the window into position.
To make a window active, click the mouse on that window.
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
/usr/local/home/accts/cs1170.
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 24 rows long and 80 columns wide;
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.cc
from the CS department 1170 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.cc cla2a.cc
In later sections you will learn how to create a file of high-level C++ source instructions with the "scite" editor and how to use the aCC compiler to create an executable file of machine instructions suitable for running on ranger. First, we explain a few simple commands. Read this section, then do the exercises below.
To display a (text) file named cla2a.cc 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.cc
on the screen. If it is longer than one screen (usually 24 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.cc 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.cc to the cs351 laser printer,
type
To send a copy of the file cla2a.cc 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.
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.cc > 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.cc | pr -n -t -e4
$ pr -n -t -e4 cla2a.cc
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 which 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.cc, type in
the following command in the Terminal window.
Now there are two files (named cla2a.cc 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.cc
into the CLA directory by typing
$ mv cla2a.cc 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.
Optional Section: The "vi" Editor
Note: this section is optional reading. Read it only if you are interested in another editor besides "scite". If you are pressed for time, you should certainly skip to the next section, The "scite" Editor
.There are no exercises due from this optional section.
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.cc
using vi (visual editor), you would type $ vi lab.cc
Read the following. Do not type in any commands until you start the next
exercise!
and press enter. Assuming lab.cc does not already exist, you would see a clean screen with a line of '~' on the left.
$ vi cla2b.cc
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.
Optional Exercise:
Type in this command in the Terminal window.
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.
Optional Exercise: 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.cc 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.
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.cc
using scite, you would type $ scite lab.cc &
Read the following. Do not type in any commands until you start the next
exercise!
and press enter. (Note that the UNIX command to invoke the scite editor is all lower-case letters.)
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.
Now type in the command in the Terminal window.
A new window, resembling a Microsoft WordPad window, should now open.
If it does not, ask for help from your lab assistant.
Exercise 15: It is time for all
Exercise 17:
If you are interested in learning more about using scite,
look over the scite menu.
The documentation at
http://scintilla.sourceforge.net/SciTEDoc.html
might also be useful.
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.cc and correct each line with an error on it.
After you are finished with the corrections, save it.
Use what you discovered about using scite to accomplish this.
Compiling and Capturing a Terminal Session
If you are familiar with Microsoft's WordPad, NotePad, or Word software,
you will find using scite straightforward. Remember, if you get
stuck just ask the lab assistant for some guidance to help you along.
Insert the following three lines of text:
good men to come to
the aid of their planet.
Exercise 16:
We will continue to work on the three lines of text that we typed in above.
We notice that we have made a mistake and we want the text to read "Now is
the time" instead of "It is the time". Using the mouse, highlight
the two letters of the word "It". Next type, "Now".
We also want to insert the word the
before the word time, so position the cursor at the t
in time.
Type the and a space.
The corrections are done.
Exit scite.
There is nothing to turn in for Exercise 17.
Exercise 18:
A sample C++ source file cla2c.cc
(that contains errors) has been prepared for you to copy and edit. Copy it to your account with
$ cp $CLA/cla2c.cc .
(Note: the dot (.) is required)
$ scite cla2c.cc &
Source code sitting in a file does nothing.
Once it is converted into executable machine code,
it can be executed and results can be generated.
The conversion is a multi-step process.
First, the high-level language (C++) source code is converted
into a machine-like code called object code
that is then linked with additional machine code from one or more libraries
to produce a true executable file.
In UNIX this process is accomplished with one command: the compiler command.
The C++ compiler command we will use is
aCC.
(Technically, the aCC command invokes the g++ compiler,
but now we're getting into more detail than you need to know at this point.)
$ aCC cla2c.cc
or
$ aCC cla2c.cc -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 "!a" would redo the most recent command starting with "a" -- probably aCC, 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 "!aC" or "!aCC" if you wanted to be sure to retrieve your most recently issued aCC 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 ex21.log
$ pr -n -t -e4 cla2c.cc
$ aCC cla2c.cc -o cla2c
$ cla2c
$ exit
Print the log file by typing Turn it into your lab instructor with the answer
sheet and the first printout.
(As an alternate way to log out,
move your mouse to the top menu bar where the pull down selections
for Applications Places System
are located. [Top left of the bar.]
Select the System tab
and then select the Quit option and proceed to log out.)
A Tip For Future Labs
It is a LOT easier to read closed lab instructions if the browser is INSIDE the UNIX Desktop. You can use the Mozilla Firefox browser found on ranger. (The Firefox browser is similar to the Internet Explorer browser found in Windows-based systems. On the current version of Linux running on ranger, the Firefox browser has been rebranded as Iceweasel. They really are the same product except for the name, so we will continue to refer to the program as Firefox.) To bring up the Firefox browser, move your mouse to the top window menu bar where the pull down selections for Applications Places System are located (top left) and select the Applications tab, then the Internet > option, and then select the Firefox Web Browser item. Alternatively, you can use the Firefox icon found on the window menu bar off to the right of the System menu item to bring up the browser. After bringing up your browser window, arrange the browser window and the other windows on your desktop so that none overlap. Remember that 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. You can make any window active by clicking the mouse on it. The following screenshot depicts one possible useful arrangement:
Congratulations!
You have finished Lab 2A.