Courses/CS 2114/Lab Manual/An Introduction to C++, Unix, and Code Editing

From A-State Computer Science Wiki
Jump to: navigation, search

An Introduction to C++, Unix, SSH and Komodo Edit

Introduction

This lab will introduce the programming environment used in this course.

Topics Covered in this Lab:

  • Brief Introduction to the C++ Language
  • 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 output, specifically C++'s cout
  • Familiarity with Unix, the Unix file system and directories.

The C++ Language

A Brief Introduction

Development of C++ began in 1979 by Bjarne Stroustrup, then employed by AT&T Bell Labs. His goal was to combine the program organization of Simula, the speed of BCPL programs along with BCPL's ease of linkage and C's efficiency, flexibility and portability. Originally titled C with Classes, the name C++, suggested by Rick Mascitti, was adopted in 1983.

By 1988 the number of users and number of implementations of C++ indicated a need for standardization. To start the process, Stroustrup, with assistance from Margaret Ellis, wrote The Annotated C++ Reference Manual which was reviewed by approximately one hundred C++ language users from various organizations. The organizational meeting of the ANSI (American National Standards Institute) C++ committee was held in December of 1989 with international attendees. In June 1991, the ISO (International Organization for Standardization) C++ committee convened with a majority of representatives being C++ programmers.

The first ISO/IEC C++ standard was released in 1998. This standard is informally referred to as C++98. While there have been minor revisions since 1998, the language itself was not changed until C++11, the standard released in 2011.

This information was gathered from various sources including those listed in the Recommended Reading section below.

Recommended Reading

Use of C++

C++ can be used for many diverse applications. The following links provide specific companies and products written partially or entirely in C++.


Relevant Computer Systems History

Many of the tools discussed here were originally part of the UNIX operating system, but are now available in other operating systems that provide a UNIX-like interface. For that reason, we will use the term "Unix" (not all uppercase) to refer to any UNIX-like system. These tools have an interesting history that you should read as time permits. In addition, click here to read about Komodo Edit.

Mimir.io

In a web browser, navigate to Mimir. This is the login page of the server through which you will access all of your homework assignments.

If you already have an account, simply login, but if you have not yet done so, create an account. Use your Astate email address as the site uses this to associate you with Arkansas State University. Once logged in, you will have the option to join the class using the class access code that you received via your student email; be sure to select the correct section when joining the class. Once joined, you should see the open assignments.

Getting Started - hello.cpp

Select the assignment that indicates the creation of hello.cpp. Click the IDE button to open the integrated development environment provided by Mimir.

Once open, take a moment to review the environment. On the left is a pane containing a list of files and folders as well as buttons for the most common actions. The center pane opens an untitled file ready for typing. The right pane contains a command line where you can compile and execute your programs.


Typing the code for hello.cpp

Modify the comments as needed, otherwise, type the following code exactly as it appears.


Verbatimcode.pngCode Illustration

Hellocpp.png


Save your work.

C++ - Program Components

In this section, each part of the program is examined in detail.

  1. The first section of the program, consisting of the lines starting with "//", 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 "//" is encountered on a line, the compiler ignores everything on the rest of that line.
  2. #include <iostream>
    
    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 cout and cin, respectively.
  3. using std::cout;
    
    This specifies to the compiler where cout is defined; std is a namespace, but it is not necessary to go into more detail at this time.
  4. int main ()
    
    The next line starts the vital part of the program, the function 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.
  5. 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.
  6. cout << "Hello, World!\n";
    
    This line does the significant work of this program. It sends the character string "Hello World!\n" to the standard output stream, cout, which is in effect the display (or "c"onsole "out"put)1. The stream insertion operator << causes anything to its right to be inserted into the stream on its left, in this case cout. The escape sequence character '\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. (For more escape sequences, refer to the textbook.)
  7. return 0;
    
    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.

1Actually, according to [Stroustrup], the "c" in cout means "character"; either mnemonic will work fine though.


Unix vs Windows Directory Structure

The Microsoft term folder corresponds to a directory in Unix. The Unix file system begins at a location called the root. This directory has the path name "/". Everything on the computer system that can be accessed through the filesystem is available within sub-directories starting with root. This is quite different from Windows, where the file system is based on disk drives. Windows paths begin with a drive letter, with sub-directories below it. In Unix, the drives are just parts of the whole system, and are listed below root (exactly where can vary from one system to another).


Unix Process Commands

In Unix, each running task is considered a process.

To view a list of processes, type ps and press Enter.

user.name@ComputerName  ~
$ ps
PID TTY   TIME     CMD
887 pts/0 00:00:00 bash
909 pts/0 00:00:00 ps

The exact list will depend on what tasks are currently running.

In the above list, two process, bash and ps, are associated with the current user. ps is the command used to generate the list while bash is the shell in which the command was executed. The bash process has an ID of 887 while the ps process has an ID of 909.

If a process "hangs", you can use the kill command to stop the process. As an example, if the process with the ID of 892 needs to be stopped, type kill 892

user.name@ComputerName  ~
$ kill 892

Unix Directory and File Commands

When you first logon to Unix, it will open up the shell in your "home" directory. In most Unix systems, the "home" directory is "/home/your_username".

  • The pwd command will display the location of the current diretory.

    Type pwd and press Enter to see what the full path of your home directory is.

    user.name@ComputerName  ~
    $ pwd
    /home/user.name/
    The exact directory may differ depending on how Unix is set up.

  • The mkdir command will create a new directory (folder).

    Enter mkdir sp01 to make a directory named sp01 corresponding to lab 01 for Structured Programming

    user.name@ComputerName  ~
    $ mkdir sp01

  • The ls command will display a listing of the files and directories of the current directory.

    Enter ls (that is a lowercase L followed by an s) to see a listing of the current directory's files and folders.

    user.name@ComputerName  ~
    $ ls
    sp01

    Enter ls sp01 to verify that no files are present in the new directory.

  • The cd command will change to a different directory.

    Enter cd sp01 to change directories from the current directory to sp01.

    user.name@ComputerName  ~
    $ cd sp01


    Note that after using cd, the command prompt now says you are in directory sp01 under the previous directory you were in (in this case, the home directory ~).

    user.name@ComputerName  ~/sp01
    $ _


    There is a shortcut name for your home directory. It is "~". You can change directories to your home directory simply by typing "cd" at the command window... This is the same as "cd ~", or "cd" followed by the full path to your home directory.

    You can change to the parent directory by typing cd ...


Compiling and Executing a C++ Program

CompilationProcess.png

The C++ Compilation Process - from Source Code to Executable Code

The program code typed by the user is called source code and is stored in a text file called the source file.

When compilation begins, the preprocessor reads the source code searching for the # symbol; the # symbol indicates a preprocessor directive. There are several preprocessor directives. Research preprocessor directives or review CPlusPlus's Preprocessor Directives for a tutorial. The preprocessor directive demonstrated in the hello.cpp program is the include directive. This directive gives a programmer access to previously written code. The filename specified, in this case iostream, is called a header file. Header files contain declarations of functions and possibly constants that can be used by a program once it has been included.

The modified source code is then compiled. The compiler converts the modified source to object code, considered to be machine-language. Any deviation in syntax will confound the compiler; these errors are reported to the programmer and the entire compilation process is halted.

Once any syntax errors have been corrected and the object code created, the next step is to link all necessary object code files to create an executable file. This is the job of the linker.

Once created, the executable file may be executed as many times as required without the need to recompile. If a change is necessary, the compilation process must be revisited.

Compile and Execute the hello.cpp Program

Unix supports clang and gcc, free C++ compilers. It can convert the human-readable source code created in the previous section into machine-executable program code. Before submitting any program, you should first verify it will compile and execute correctly; thorough testing is important. When you have finished editing the file, save it and then move to the command prompt pane.

  1. Compile and Link: 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 a lab proctor.
    user.name@ComputerName  ~/sp01
    $ g++ hello.cpp
    If g++ does not print anything then everything is OK.
  2. Display a listing of the current directory's files. The list should include hello.cpp as well as a.out, which is the default name for an executable program.
  3. Execute: Enter ./a.out (period followed by /a.out) or possibly just a.out 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.)
    user.name@ComputerName  ~/sp01
    $ ./a.out
    Hello World!
  4. Compile and Link - specify executable filename: Enter g++ -o speak hello.cpp to give the executable the name speak; execute it with ./speak.


Using Switches with the g++ Compiler

For grading purposes, all programs will be compiled using the command

g++ -Wall -Wextra -pedantic -std=c++17

What follows g++ are called switches.

  • -Wall -Wextra turns on all warning messages, including uncommon ones; you should treat warning messages as errors and attempt to correct the problem.
  • -pedantic increases the sensitivity of the compiler to errors/warnings specified by the C++ ANSI standard.
  • -std=c++17 tells the compiler to use the C++17 standard (the most recent standard available in g++).


Before submitting any program, it should be compiled with the set of switches mentioned above and tested (executed). Try compiling hello.cpp by using the following command:

user.name@ComputerName  ~/sp01
$ g++ -Wall -Wextra -pedantic -std=c++17 hello.cpp
If g++ does not print anything then everything is okay.


Execute the newly generated file by using the following command:

user.name@ComputerName  ~/sp01
$ ./a.out



Submitting a Program

Once you have successfully compiled and executed your program, submit it for grading. The airplane button in the left pane will start the submit process from the IDE. In order to make a choice in the pop up windows that follow, type the first few letters of your choice, then you can use the arrow keys to select the correct option. Once selected, press Enter. When submitting programs, always submit the .cpp file.

Create a New Program - spILoutput.cpp

Return to the Mimir assignment page (or use the Dashboard link) and select the assignment to create spILoutput.cpp. Follow the directions found within and submit the program when completed.


// ***** spILoutput.cpp *****


#include <iostream>
using std::cout;

int main ()
{
    // replace this comment with a statement to display your first name to the screen
    // replace this comment with a statement to display your last name next to your first name
    // be sure to include a space to separate the two names.
    // look to the cout statement in the hello.cpp program to complete these two lines of code

    return 0;
}
Sampleoutput.pngExample of expected output.
John Doe



Remember, before submitting any program, it should be compiled with the set of switches mentioned above and tested (executed). Try compiling spILoutput.cpp by using the following command:

user.name@ComputerName  ~/sp01
$ g++ -Wall -Wextra -pedantic -std=c++17 spILoutput.cpp
If g++ does not print anything then everything is okay.


Execute the newly generated file by using the following command:

user.name@ComputerName  ~/sp01
$ ./a.out

Once completed, submit the program.


Labsubmitsinglefile.pngUpload the following files: hello.cpp, spILoutput.cpp


Appendix: Some Useful Linux Commands

The table below lists a handful of linux commands that you will probably find very useful for code development. You can also find this table at the wiki page Common_Linux_Commands.


Command Action
ls list directory contents; add -l for more information
pwd print working directory: shows path to your current working location
cd dir change directory to dir; .. means "parent"
mkdir new_dir make a new directory with name new_dir
rm file removes file; add -r to delete a directory
cp source dest copy file source to dest
mv old new move (or rename) file or directory old to new
cat file prints contents of file to terminal
more file same as cat but allows paging of long files
vim file command-line editor: edits or creates file
clear clears the screen
exit exits the login session (i.e. "log out")

More information about these commands can easily be found online.