User:HGoat/C++ Lab Manual
Introduction
[edit]This lab will introduce the programming environment used in this course.
Topics Covered in this Lab:
- Unix and the GNU C++ compiler
- creating, saving, compiling, and executing programs
- basic C++ program structure
- the course website and submitting programs
Questions Answered in this Lab:
- How is a program file opened or created?
- What does a compiler do with a program?
- What do the different pieces of a program do?
- How does a computer program communicate with a user?
Demonstrable Skills Acquired in this Lab:
- ability to create a simple C++ program
- ability to compile and run a program
- familiarity with console input and output, specifically C++'s {\tt cin} and {\tt cout}
Relevant Computer Systems History
[edit]The content of the following sections was gleaned from a variety of Wikipedia entries and edited into a time line relevant to this laboratory.
UNIX
[edit]In the 1960s, the Massachusetts Institute of Technology, AT\&T Bell Labs, and General Electric worked on an experimental operating system called Multics (Multiplexed Information and Computing Service), which was designed to run on the GE-645 mainframe computer. AT{\&}T Bell Labs pulled out of the Multics project but one of the Bell Labs team, Ken Thompson, continued to develop for the GE-645 mainframe, and wrote a game for that computer called Space Travel. However, he found that the game was too slow on the GE machine and was expensive, costing \$75 per execution in scarce computing time. Thompson thus re-wrote the game in assembly language for Digital Equipment Corporation's PDP-7 with help from Dennis Ritchie, creator of the C programming language. This experience, combined with his work on the Multics project, led Thompson to start a new operating system for the PDP-7. Thompson and Ritchie led a team of developers at Bell Labs developing a file system as well as the new multi-tasking operating system itself. They included a command line interpreter and some small utility programs. In the 1970s the project was named Unics, and eventually could support two simultaneous users. Brian Kernighan, co-author with Ritchie of the landmark book The C Programming Language, invented this name as a contrast to Multics; the spelling was later changed to Unix (officially trademarked as UNIX).
GNU
[edit]On September 27, 1983, Richard Stallman announced the plan for the GNU operating system. GNU's objective was to bring a wholly free software operating system into existence. At the time, Unix was already a popular proprietary operating system. The design of Unix had proven to be solid, and it was modular, so it could be reimplemented piece by piece. It was decided that GNU would be mostly compatible with Unix. GNU's name is a recursive acronym for GNU's Not Unix; while its design is Unix-like, it is free software and contains no Unix code. As the goal was to make a whole free operating system exist, not necessarily write an entire operating system, Stallman tried to use existing free software when possible. This included the X Window System for graphical display, the TeX typesetting system, and the Mach microkernel (developed by Carnegie Mellon University in 1985 in support of operating system research). By 1990, the GNU system had an extensible text editor (Emacs), a very successful optimizing compiler (GCC), and most of the core libraries and utilities of a standard Unix distribution. GNU remains in active development; its official kernel, GNU Hurd, is incomplete. The third-party Linux kernel is most commonly used instead.
Linux
[edit]MINIX, a Unix-like system intended for academic use, was released by Andrew Tanenbaum in 1987. While source code for the system was available, modification and redistribution were restricted at the time. A further limitation was that MINIX's 16-bit design was not well adapted to the 32-bit design of the increasingly cheap and popular Intel 386 architecture for personal computers. In 1991, Linus Torvalds began work on a non-commercial replacement for MINIX, a project for use on his new 80386 PC that later became the Linux operating system kernel, a modular Unix-like operating system. On 25 August 1991, he announced this system in a posting which began: ``I'm doing a (free) operating system (just a hobby, won't be big and professional like gnu) for 386(486) AT clones. He intended to call his system Freax, merging ``freak, ``free, and an ``x as an allusion to Unix. He had already considered the name ``Linux but thought it too egotistical. In order to facilitate development, the files were uploaded to the FTP server of the Helsinki University of Technology in September 1991. Torvald's coworker responsible for the server did not feel Freax was a good name, so he dubbed the project Linux without consulting Torvalds. Torvalds later consented and, after many arguments, finally admitted that Linux was simply the better name. Linux derives much of its basic design from principles established in Unix during the 1970s and 1980s. The GNU userland is an important part of most Linux systems, providing the shell and Unix tools which carry out many basic operating system tasks.
Cygwin
[edit]In 1989 John Gilmore, Michael Tiemann and David Henkel-Wallace founded Cygnus Solutions (then Cygnus Support) to provide commercial support for free software; their slogan was ``Making free software affordable. Cygnus is a recursive acronym for ``Cygnus, Your GNU Support. Cygnus Solutions was the maintainer of several key GNU software products, including the GNU Debugger and GNU Binutils (which included the GNU Assembler and Linker). It was also a major contributor to the GCC project. Cygnus was the original developer of Cygwin, a collection of free software tools to provide in Microsoft Windows a command line and programming interface familiar to Unix/Linux users. While Cygwin provides programming language header files and libraries making it possible to recompile or port Unix applications for use on computers running Microsoft Windows operating systems, it does not provide binary executable programs capable of running without Cygwin installed.
Creating a C++ Program
[edit]A simple program to write the traditional ``Hello, World! message will be created in this section.
- As directed by your laboratory proctor, start Cygwin on your computer.
- As directed by your laboratory proctor, start an editor and use it to enter the following contents for file hello.cpp.
// ***** hello.cpp ***** // // Course: CS 2114 // Name: your name // Date: today's date // Lab 1: Programming in C++ #include <iostream> using std::cout; int main () { cout << "Hello, World!\n"; return 0; } // The compiler expects a completely blank line at each source file's end.
- Enter ls to see a \ul{l}i\ul{s}ting of the current directory's files. (The Microsoft term folder corresponds to a directory in Unix.) The list should include hello.cpp.
- Enter ls -l to see a \ul{l}ong listing of the current directory's files; in addition to the file names, their size and date of creation, among other attributes, will be displayed.
\ul{FOR IN-LAB CREDIT: Demonstrate for the lab proctor the presence of file hello.cpp.}
Program Components
[edit]In this section, each part of the program is examined in detail.
- The first section of the program, consisting of the lines starting with ``{\tt //}, is a comment block. This is where the program name, author name, description of what the program is to do, and other related information are to be placed. See the course's documentation guidelines for more information. Comment lines may be placed anywhere deemed useful in the program. When ``{\tt //} is encountered on a line, the compiler ignores everything on the rest of that line.
- This is a preprocessor directive which tells the compiler that information in the header file iostream is needed to make this program work; iostream allows programs to write to the screen and read from the keyboard using the identifiers {\tt cout} and {\tt cin}, respectively.
#include <iostream>
- This specifies to the compiler where {\tt cout} is defined; {\tt std} is a namespace, but it is not necessary to go into more detail at this time.
using std::cout;
- The next line starts the vital part of the program, the function {\tt main}. This line tells the compiler that the following function is named main and that it will return an integer value. Every console-based program must have a function named main.
int main ()
- Braces \{ and \} enclose the body of function main. Everything inside the braces makes up the body of the function. This is where the computer is told what steps to take to solve the problem.
- This line does the significant work of this program. It sends the character string ``Hello World!{\bsn} to the standard output stream, {\tt cout}, which is in effect the display (or \ul{\tt c}onsole \ul{\tt out}put). The stream insertion operator {\tt <<} causes anything to its right to be inserted into the stream on its left, in this case {\tt cout}. The escape sequence character {\tt {\bs}n} indicates the end of a line, which moves the cursor to the beginning of the next line as if the enter key had been pressed when typing.
cout << "Hello, World!\n";
- This line returns the value zero from this program to the program that initiated it, usually the operating system. The value returned can be used to indicate the completion status of the program. Values other than zero are typically used to indicate an error condition. Every program in this course will return zero.
return 0;
\end {enumerate}
Compiling and Executing a C++ Program
[edit]The GNU project supports g++, a free C++ compiler. It can convert the human-readable source code created in the previous section into machine-executable program code.
- Compile and link the program with g++ hello.cpp. If there are no errors, Unix will simply display another prompt. (Most Unix programs are quiet rather than verbose.) If there are errors, seek assistance from the lab proctor.
- Enter ls to see a listing of the current directory's files. The list should include hello.cpp as well as a.exe, which is the default name for an executable program.
- Enter ./a.exe or possibly just a.exe to execute the program. (The single period is the path name for the current directory; if it is not present in the system path variable, you must explicitly include it to specify the program's location.)
- Enter g++ -o speak hello.cpp to give the executable the name speak; execute it with ./speak or speak.
- Enter rm a.exe and rm speak to \ul{r}e\ul{m}ove (erase) the executables; enter ls and confirm that only hello.cpp remains.
- Enter g++ -c hello.cpp to compile the program only. Enter ls to see that the object file hello.o was created. This object file cannot be executed, but it can be linked with other object files to create a large executable.
- Enter g++ hello.o to link the program only. (The real value of this step will not become apparent until additional object files are present for linking.) Execute the resultant file a.exe.
- Enter g++ -o speak hello.o to name the resultant executable speak; execute file speak.
\ul{FOR IN-LAB CREDIT: Demonstrate the speak program for the lab proctor.}
Compiler Errors
[edit]In this section, several different kinds of errors will be introduced into the working program of the preceding sections. It is better to become familiar with errors in this manner than to encounter them for the first time when they have occurred by accident; at the close of this section, you may wish to experiment with other potential mistakes.
- Edit the file hello.cpp and remove the semicolon from the end of the line beginning with {\tt cout}.
- Save the file and compile it again.
- Consider the error messages that appear: Note that the compiler reports an error at the start of the line following the {\tt cout} line. This is simply the first place that the compiler knew something was amiss. Since C++ is very flexible on formatting program code, the line
hello.cpp: In function `int main()': hello.cpp:12: error: expected `;' before "return"
could have been entered ascout << "Hello, World!\n";
Try this to verify that the program behaves the same.cout << "Hello, World!\n" ;
The function main could also have been written
int main () { cout << "Hello, World!\n"; return 0; }
Try this as well. It is easy to see in this version why the compiler complains about the missing semicolon at the start of the word {\tt return}. It is important to understand that the compiler sees the original version and the two succeeding variations above in exactly the same way: any number of carriage returns and blank spaces may be replaced by a single blank space. (An exception to the rule is spacing inside quotation marks, as the compiler wants to print exactly what it finds there.) Indentation and spacing help to make programs more readable; a good first rule to follow is to indent three spaces inside each pair of curly braces.
- Correct the semicolon error above and then change the spelling of cout to cour and examine the messages generated.
hello.cpp: In function `int main()': hello.cpp:11: error: `cour' undeclared (first use this function) hello.cpp:11: error: (Each undeclared identifier is reported only once for each function it appears in.)
- Correct the spelling error above and then remove the second {\tt "} from the {\tt cout} line and examine the messages generated.
hello.cpp: In function `int main()': hello.cpp:11: error: missing terminating " character hello.cpp:12: error: expected primary-expression before "return" hello.cpp:12: error: expected `;' before "return"
- Correct the {\tt "} error above and then remove the zero from the {\tt return} line and examine the messages generated.
hello.cpp: In function `int main()': hello.cpp:12: error: return-statement with no value, in function returning 'int'
\ul{FOR IN-LAB CREDIT: Demonstrate at least one of these errors for the lab proctor.}
Program Directories
[edit]The directory in which file hello.cpp is currently stored will quickly become crowded if every new program written is also placed here. For that reason, a sub-directory will be created for each new program's files.
- Enter mkdir sp01 to \ul{m}a\ul{k}e a \ul{dir}ectory named sp01 corresponding to lab 01 for Structured Programming; enter ls again to verify that the new directory is present.
- Enter ls sp01 to verify that no files are present in the new directory.
- Enter cp hello.cpp sp01/sp01.cpp to \ul{c}o\ul{p}y file hello.cpp into the new folder sp01 and rename the copy as sp01.cpp.
- Enter cd sp01 to \ul{c}hange \ul{d}irectories from the current directory to sp01.
- Enter ls again to verify the presence of sp01.cpp.
Using Computer Memory for Variables
[edit]The C++ language contains a keyword {\tt int} which requests that a location in memory which can hold an integer be set aside and labeled as indicated; further, a value can be stored in this location using the assignment operator {\tt =}.
- Add the following line to the program in file sp01.cpp to set aside an integer location named number1 containing the value 5; this line (and all additions to follow) should immediately precede the {\tt return 0} statement. \bq # This value can be displayed by adding the following {\tt cout} statements to the program. \bq
int number1 = 5;
Note that both literal character strings following {\tt cout} are surrounded by quotation marks while the variable name is not.cout << "The value stored in the variable is "; cout << number1; cout << ".\n"; // sentence-ending period, then carriage return to next line
- Compile and execute the program to see the value displayed.
- Add the following pair of lines to create a second variable and display its value; note that the redundant semicolons and {\tt cout}s are removed when displaying this second value. \bq # Execute the program again.
int number2 = 7; cout << "The value stored in the second variable is " << number2 << ".\n";
Performing Computer Arithmetic
[edit]The C++ language contains arithmetic operators to calculate the following: \\[10pt] \hspace*{0.25in} ::TABLE DELETED
- Add the following to the program to perform an addition and display its result. \bq Note the use of two operators in the first line; addition has higher precedence than assignment, so {\tt number1} and {\tt number2} are added, after which their sum is assigned to {\tt sum1}.
int sum1 = number1 + number2; cout << "The sum of the two numbers is " << sum1 << ".\n";
- Execute the program and verify that the result is correct.
- The result can be made even more meaningful if the operands are included in the display. Make the following changes to the program. \bq # Execute the program again. Add additional instructions to examine the product of the two numbers.
cout << "The sum of " << number1 << " and " << number2 << " is " << sum1 << ".\n";
FOR IN-LAB CREDIT: Demonstrate a multiplication to the lab proctor.
Reading from the Keyboard
[edit]As has been demonstrated, results are written to the screen in C++ with {\tt cout}. Information may be read from the keyboard with {\tt cin} (console input).
- Begin by adding a second {\tt using} statement for {\tt cin} following that already in place for {\tt cout}. \bq # Add the following sequence to the program to read an integer value from the keyboard. \bq
using std::cin;
# Execute the program.cout << "Enter a number: "; int number3; cin >> number3; cout << "The number you entered is " << number3 << ".\n";
- Add another sequence to read another value from the keyboard into a variable number4 and execute the program again.
- Add the following sequence to the program to perform addition on the two values read from the keyboard. \bq # Add an additional sequence to the program to perform subtraction and multiplication on the same two values.
int sum2 = number3 + number4; cout << "The sum of " << number3 << " and " << number4 << " is " << sum2 << ".\n";
FOR IN-LAB CREDIT: Demonstrate subtraction and multiplication for the lab instructor.
The vi Editor
[edit]For the sake of tradition, every computer science student should be familiar with the vi editor, the historic (1975) piece of software that was used by many early Unix programmers to write their programs; there are traditionalists who continue to use vi to this day. (The name ``vi is pronounced vee-eye; it is an abbreviation of the word ``visual.) You may wish to visit {\tt http://www.eng.hawaii.edu/Tutor/vi.html\#start} for detailed instructions on how to use the vi editor. Unlike visual editors such as Windows' Notepad, vi uses character commands to manipulate file content. A minimal set of character commands follows: