Hour 1. Writing Your First Program

Using C++

In 1979, a Danish computer scientist at Bell Labs in the United States began work on an enhancement to the C programming language. Bjarne Stroustrop explained on his personal website that he wanted a language “in which I could write programs that were both efficient and elegant.”

A lot of other people wanted that too.

Stroustrop’s creation, which he dubbed C++, has held a spot among the world’s top programming languages for decades. Many programming trends have come and gone over the years, but this language remains a contemporary and useful choice for software development on desktop computers, embedded devices like smartphones and MP3 players, and many other computing environments.

C++ is a portable language that works equally well on Microsoft Windows, Apple Mac OS, Linux, and UNIX systems. The best way to learn the language is to write programs without regard to the operating system the program runs on.

Sams Teach Yourself C++ in 24 Hours offers a hands-on introduction to the language that makes absolutely no assumptions about your operating system. This book can achieve this because it covers standard C++ (also called ANSI/ISO C++), the internationally agreed-upon version of the language, which is portable to any platform and development environment.

The code presented throughout the book is standard ANSI/ISO C++ and should work with any development environment for C++ that’s up-to-date.

New features that will be part of C++0x, the language’s next version, also are covered. Some of the most useful ones have begun showing up on an experimental basis in popular C++ development environments ahead of its scheduled release date in early 2012.

C++ programs are developed by a set of tools that work together called the compiler and linker.

A compiler turns C++ programs into a form that can be run. The compiler translates a program from human-readable form called source code into a machine-runnable form called machine code. The compiler produces an object file. A linker builds an executable file from the object file that can be run.

There are several popular environments for C++ programming that you might have used before or know how to obtain. Some of these are GCC (the GNU Compiler Collection), Microsoft Visual C++, NetBeans and Code::Blocks.

If you have a C++ compiler on your system and know the basics of how to use it, you will have no trouble completing the programming projects in this book.

If you don’t have a C++ compiler, don’t know how to use a compiler, or don’t know how to find one, relax. The next section will help.

Finding a Compiler

The programs in this book were created and tested first with GCC, a free and open source set of programming tools that support C++ software development. GCC is extremely popular on Linux and available for Windows and Mac OS systems, too. GCC works in a command-line environment where you type in a command to make the C++ compiler and linker create a program.

Some computers have GCC installed along with the operating system.

If you know how to use the command line on your computer, you can type the following command to see whether GCC is installed:

g++ ––version

G++ is GCC’s C++ compiler and linker. If you see a message like this, you have it on your computer:

g++ (Ubuntu 4.4.1-4ubuntu9) 4.4.1

Copyright (C) 2009 Free Software Foundation, Inc.

This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY o
FITNESS FOR A PARTICULAR PURPOSE.

The version message displays the operating system and version number of the compiler. G++ is all that you need to create the programs in this book.

If you don’t have GCC, you can install it on Microsoft Windows as part of MinGW (Minimalist GNU for Windows), a free set of development tools for creating Windows software.

Visit the MinGW website at http://www.mingw.org to find out more about the software and download it. Click the Downloads link on the home page—which may be in the sidebar—to open a web page where it is available for download.


By the Way

Apple users can get GCC by installing XCode from their Mac OS X installation CD or by registering as an Apple developer at http://developer.apple.com.


The download page is on SourceForge, a project-hosting service for software. Click the proper download link to download an installation wizard for MinGW on your computer.

After the download completes, open the folder where it was downloaded and double-click the MinGW icon to run the Installation Wizard. Click Next to begin.

Follow the instructions to review the software license agreement and decide how to install the program.

During one step, the wizard asks which components you want to install, as shown in Figure 1.1. Check the MinGW base tools and G++ compiler check boxes and click Next.

Figure 1.1 Installing MinGW’s C++ compiler.

image

You’re asked where to install the software. C:MinGW is the default folder. You can either keep that default or choose another folder, which will be created if necessary. Click Next to continue.

As the final step, you’re asked which Start Menu folder to put shortcuts for MinGW in. Choose one (or accept the MinGW default) and click Install. MinGW is downloaded and installed on your computer.

A progress bar marks how the process is going. If it completes successfully, you’re ready to open a command line on your Windows computer and see whether it’s there.

To open a command line

• On Windows XP or Windows 7, choose All Programs, Accessories, Command Prompt.

• On Windows Vista, choose Programs, Accessories, Command Prompt.

The command window is a plain window with a blinking cursor next to the folder you are currently working in. To change to another folder, use the CD command followed by a space and the name of the new folder. The following command moves you to the folder where MinGW’s G++ tool is located:

cd C:MinGWin

In this folder, you can run the command to see that G++ is working properly:

g++ ––version

To make it possible to run G++ from any folder, you can add its location to your Windows computer’s Path variable. Path holds the list of folders to check whenever a program is run and it can’t be found in the current folder.

To edit your Path, open the Environment Variables dialog, as follows:

1. Right-click the My Computer icon on your desktop or Start menu and choose Properties. The System Properties dialog opens.

2. Click the Advanced tab or Advanced System Settings link to bring it to the front.

3. Click the Environment Variables button. The Environment Variables dialog opens.

4. Choose Path and click Edit. The Edit System Variable dialog opens.

5. In the Variable Value field, add the following to the end of the Path value: ;C:MinGWin (being sure to include the semicolon at the beginning).

6. Click OK to close each of the dialogs.

The next time you open a new command window, the g++ ––version command should work in any folder. Switch to different folders to see that it works.

Microsoft Visual Studio also supports C++ programming—the current version of that integrated development environment is Visual Studio 2010. Although the installation of that software is too complicated to cover in detail here, some guidance also is offered in this book for people learning C++ with Visual Studio.

Compiling and Linking the Source Code

Before you create your first C++ program later this hour, it’s worthwhile to understand how the process works.

C++ programs begin as source code, which is just text typed into an editor such as Windows WordPad, Gedit, Emacs, or Vi. Although Microsoft Word and other word processors can save files as plain text, you should use a simpler editor for programming because you don’t need all the formatting and presentation capabilities of a word processor. Source code consists of plain text with no special formatting.

The source code files you create for C++ can be given filenames ending with the extensions .cpp, .cxx, .cp, or .c. This book names all source code files with the .cpp extension, the most common choice of C++ programmers and the default for some compilers. Most C++ compilers don’t care about the extension given to source code, but using .cpp consistently helps you identify source code files.

Source code is the human-readable form of a C++ program. It can’t be run until it is compiled and linked.

After your source code is compiled, an object file is produced. This file is turned into an executable program by a linker.

C++ programs are created by linking together one or more object files with one or more libraries. A library is a collection of linkable files that provide useful functions and classes that you can rely on in your programs. A function is a block of code that performs a task, such as multiplying two numbers or displaying text. A class is the definition of a new type of data and related functions.

Here are the steps to create a C++ program:

1. Create a source code file with a text editor.

2. Use a compiler to convert the source code into an object file.

3. Use a linker to link the object file and any necessary libraries to produce an executable program.

4. Type the name of the executable to run it.

The GCC compiler can handle compiling and linking in a single step.

Creating Your First Program

Now that you’ve been introduced to how the process works, it’s time to create your first C++ program and give the compiler a test drive.

Run the text editor you’re using to create programs and open a new file. The first program that you will create displays text on the screen.

Type the text of Listing 1.1 into the editor. Ignore the numbers along the left side of the listing and the colons that follow them. The numbers are there simply for reference purposes in this book.

As you type, make sure to enter the punctuation on each line properly, such as the :: and << characters on line 5.

When you’ve finished, save the file as Motto.cpp.

Listing 1.1 The Full Text of Motto.cpp.


1:  #include <iostream>
2:
3:  int main()
4:  {
5:      std::cout << "Solidum petit in profundis! ";
6:      return 0;
7:  }


The point of this project is to become familiar with the steps of creating a C++ program. If you don’t know what each line is doing, that’s no reason to panic—you’ll begin to learn what’s going on here during Hour 2, “Organizing the Parts of a Program.”

After you save the file, it needs to be compiled and linked. If you’re using GCC, the following command accomplishes both tasks:

g++ Motto.cpp -o Motto.exe

This command tells the G++ compiler to compile the file named Motto.cpp and link it into an executable program named Motto.exe. If it compiles successfully, no message is displayed. The compiler only says something if there’s a problem, displaying an error message and the line (or lines) where it appeared.

If you get a compiler error, recheck the program line by line. Make sure that all the punctuation is included, particularly the semicolon at the end of lines 5 and 6.

After fixing any potential problems, try the compiler again. If you continue to experience problems and can’t find the cause, you can download a copy of this program from the book’s website at http://cplusplus.cadenhead.org. Go to the Hour 1 page.

When the program has been compiled properly, you can run Motto.exe like any other program on your computer: Type its name Motto.exe as a command and press Enter.

The Motto program displays the following output:

Solidum petit in profundis!

This is the motto of Aarhus University, a public school with 38,000 students in Aarhus, Denmark, and the nation’s second-largest university. The motto is Latin for “Seek a firm footing in the depths.”

Aarhus alumni include environmental writer Bjorn Lomborg, Nobel laureate chemist Jens Christian Skou, Danish Crown Prince Fredrik, and some guy named Bjarne Stroustrop.

Summary

Congratulations! You can now call yourself a C++ programmer, although if you quit at this point, no one will call you an ambitious one.

The C++ language has been a popular choice for software development for more than three decades. The language has its idiosyncrasies, but when you become comfortable with how programs are structured, it is easy to build on your knowledge by creating more sophisticated programs.

Over the next few hours, you learn the basic building blocks of C++, creating several programs each hour that demonstrate new facets of the language and programming techniques.

Solidum petit in profundis!

Q&A

Q. What is the difference between a text editor and a word processor?

A. A text editor produces files with plain text in them—just letters, numbers, spaces, and punctuation. There are no formatting commands for things such as bold or italic text, justified lines, special margins, and so forth. You don’t need any of that formatting in C++ source code, and if you use a word processor it can save things in the file that the compiler won’t understand. If you have trouble getting the Motto program to compile and you’re using a word processor, try a simpler editor such as Notepad on Windows to see whether that solves the problem.

Q. My compiler has a built-in editor. Is that the right thing to use?

A. It sounds like you’re using an integrated development environment (IDE), a graphical tool that speeds the process of writing, debugging, and testing programs. Sophisticated compilers such as Microsoft Visual C++ include a full IDE, enabling the programmer to access help files, edit and compile the code in place, and resolve compile and link errors without ever leaving the environment. These are a much better way to write C++ programs, but only if you know how to use the IDE already. Trying to learn C++ as you learn the ins and outs of an IDE at the same time is difficult. That’s one reason this book prefers GCC, which is simple, powerful, and free.

Q. Can I ignore warning messages from my compiler?

A. Absolutely not. C++ uses the compiler to warn when you’re doing something as a programmer you might not intend. The best approach is to heed those warnings and do what is required to make them go away. Getting an error means that the compiler cannot figure out how to convert what you wrote into machine language. A warning means that it can convert it but maybe not in the way you expected.

Q. Do you only answer questions related to C++?

A. Nope. Ask anything.

Q. Groovy. Why doesn’t anyone sell grape-flavored ice cream?

A. Unlike other fruit flavors incorporated into ice cream, grapes get almost all their flavor from their skins rather than the interior of the fruit. Without the skins, they just taste sweet in an entirely nondistinct and generic way, so you wouldn’t know you were eating grape ice cream unless somebody told you.

When the skins are included to get around this problem, ice cream makers say that the resulting texture of the finished product freaks people out. So grape ice cream is extremely rare and a bit gross even when it is available.

Fans of the flavor can still enjoy grape juice, grape jelly, and grape soda. But not Grape-Nuts. That breakfast cereal contains neither grapes nor nuts.

Workshop

Now that you’ve had the chance to enter, compile, link, and execute your first program, you can answer a few questions and complete a couple of exercises to firm up your knowledge about the compiler.

Quiz

1. What tool turns C++ source code into object code?

A. A compiler

B. A linker

C. An integrated development environment

2. What filename extension is most common for source code files?

A. cpp

B. c

C. h

3. What tools can you use to edit your source code?

A. A text editor

B. A word processor

C. Either one

Answers

1. A. The compiler takes a file of C++ source code and turns it into object code. The linker links that object file and any other necessary object files to create an executable program.

2. A. Compilers can handle any source code file regardless of extension, but .cpp is in wide usage as the file extension for C++ code. Using this extension makes it easier later when you’re looking around your file folders for a program’s source code.

3. C. You can use any tool that saves the code as plain text. You can use the simple editors that come with your operating system (such as Notepad, Vi, Gedit, or Emacs.

Activities

1. Modify the Motto program to display the text “Saluton Mondo!,” the greeting “Hello world!” in the artificial language Esperanto.

2. If you don’t have a C++ IDE and you’re not comfortable using the command line, take a look at NetBeans at http://netbeans.org or Code::Blocks at http://codeblocks.org. They’re free IDEs that can be configured to work in conjunction with GCC. You might find them easier to use as you read this book.

To see solutions to these activities, visit this book’s website at http://cplusplus.cadenhead.org.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.181.66