Writing applications in C++ is a multistep process. You must first define the purpose and needs of the application. Once you know explicitly what an application should do, you can begin the actual coding. When you finish programming, you then compile the C++ code into an executable application. If the compilation process worked, you can then run the executable application to see the results of your hard work. In reality, of course, there’s an interim step of debugging, debugging, and debugging, followed by a wee bit more debugging.
In this chapter, you’ll learn how to program, compile, and run a C++ application. The information presented and the techniques described in this chapter will be the foundation for all of the book’s subsequent material, as well as the basis for your life as a C++ programmer.
This chapter begins with the basic syntax and instructions for creating a quick C++ source file. Then you’ll see how to compile and execute this application. Next up, you’ll learn how to print messages using C++ and how to momentarily pause the execution of an application. The final two coding techniques show how to use blank spaces and comments in your code. Once you are equipped with an understanding of all of these fundamentals, the chapter wraps up by demonstrating how to create basic C++ programs using two free and popular development applications.
If you have never programmed before, it may be surprising how easily you can create a simple application. C++ code is merely plain text written in any text editor. The text file is normally given a .cpp
extension and will then be compiled—as you’ll see in the next section of this chapter—in order to create an executable application.
The barebones syntax for a C++ file is
int main() {
return 0;
}
These three lines define a function called main. When a C++ program is executed, this function is automatically called. In other words, when you run an application, whatever you’ve programmed the main()
function to do is what will happen. It’s important to note that C++ is generally case-sensitive, so you have to type your code exactly as it is in the book. If you enter Int
instead of int
, Main
instead of main
, or RETURN
instead of return
, the program will not work (you’ll see errors when you go to compile the program).
The contents of a function (the stuff that actually happens) are placed between the opening and closing curly braces. This area is called the body of a function. As a matter of form, a function’s entire body is normally indented so that its relationship to the function is clear.
In this example, the function does only one thing: it returns the number 0
. In later chapters you’ll learn more about having functions return values, but for now just remember two things:
int
before main()
means that the function will return an integer.main()
function return a value of 0
indicates that no problem occurred.In order to understand the process of programming and compiling a C++ file, the first example in the book will contain just this minimal code. Before you begin, see the sidebar on the various kinds of tools you may use in developing C++ applications.
C++ applications begin as plain-text source files. These can be written in any text editor that allows you to save files as plain text (like Notepad on Windows). Obviously some choices (like BBEdit for the Mac or vi or emacs for Unix) are better than others. Some text editors, like TextEdit or WordPad, will always try to save files as Rich Text Format (.rtf
) or with an extra extension. You should avoid using these editors for that very reason.
main()
function (Script 1.1):
int main() {
Again, this line begins the definition of a user-defined function called main. It will return an integer value. The opening curly brace marks the beginning of the function’s body.
return
line to the function:
return 0;
Many functions in C++ return a value, even if it’s just the number 0
. This value is meant to reflect that no errors occurred.
Again, this line is normally indented four spaces (or one tab) to indicate that it’s part of the function.
main()
function:
}
Don’t forget the closing curly brace! This marks the end of the main()
function definition. You may also want to press Return (Mac) or Enter (PC) after the curly brace, or else you’ll see a warning (in some environments) when you go to compile the application.
first.cpp
.
Remember that C++ source files use the .cpp
extension. This one will be called first, as it’s the first—and otherwise pointless—program.
To maintain a tidy computer, you should probably create a folder in which to store all of the C++ code. Perhaps within this you would create subfolders, one for each chapter in the book. In any case, pay attention as to where you save first.cpp
, as you’ll need to remember that location for the next sequence of steps.
• You may also see alternative extensions for C++ source code files. On Unix, .C
may be used for C++ (whereas .c
represents a C file; Unix is case-sensitive). You may also come across .cc
or .cxx
. We’ll be sticking with .cpp
in this book.
• Different operating systems have various restrictions as to how long a file’s name can be. A basename (for example, first without the .cpp
extension) is limited to 8 characters in MS-DOS and 14 on some very old versions of Unix, but Windows, Mac OS X, and most contemporary operating systems allow for a reasonably long name.
• Although Windows and Mac OS X are not case-sensitive when it comes to filenames, Unix is. Treating your files as if case-sensitivity matters is a good programming habit and makes your code more portable. Hence, in this example, it’s important that you use first.cpp
as opposed to first.CPP
or First.cpp
.
• In C++ you can actually skip the return 0
line for the main()
function, as C++ will assume a return value of 0
for this function if not otherwise indicated. Regardless, proper programming style suggests that you include the return
statement. (We mention this as you may see it omitted in other resources.)
• Some programmers define their functions like so:
int main(void) {...
to explicitly indicate that the function takes no arguments. What an argument is will mean more to you in time, but know that both int main()
and int main(void)
are acceptable.
Simply put, a compiler does the critical task of taking your C++ source code and turning it into an executable program (one that can be run). It takes high-level instructions and generates the proper low-level machine code that the computer can understand. Every C++ source code file must be compiled in order to execute it, and you must recompile a file after making any changes.
There are two ways you can compile and run your C++ code:
• By using a command-line prompt with a stand-alone compiler
• By using the compiler and features built into an IDE
In the following steps, you will see how to use a command-line compiler. At the end of the chapter you’ll see how to use an IDE’s built-in compiler. Obviously, using an IDE is the easier method, but knowing how to use command-line tools is worthwhile.
Of the existing compilers, g++ is commonly used for C++. The simplest syntax for compiling a file is
g++ filename.cpp
That line tells the g++ compiler to compile the filename.cpp
file. If the compilation process worked, an object file will be created called filename.o
. If there are problems with your code, error messages will be displayed (Figure 1.1).
If the compilation succeeded, the compiler will then automatically invoke a linker, which combines all the necessary code into one nice, executable file. The result will be the oddly named a.out
on Unix systems (including Mac OS X) and a.exe
on Windows. (Most linkers will automatically delete the original .o
file at this point, too.) You can give the resulting application a specific name by using the -o
flag with g++:
g++ -o testing filename.cpp
This line will compile filename.cpp
and, if successful, will create an executable called testing
.
To try your hand at this critical step, you can compile first.cpp
. Keep in mind that you can follow these steps only if you’ve installed a compiler on your system. For instructions, see Appendix A, “C++ Tools.”
How you do this depends upon your operating system:
• On Windows, you should click the Start menu, select Run, type cmd
in the Open text box (Figure 1.2), and press Enter or click OK. This will bring up a DOS prompt (Figure 1.3).
• For Mac OS X and Unix, use the Terminal application (Figure 1.4). Open it by double-clicking its icon in the Utilities or Applications folder (depending on your OS).
(We’ve customized the look and prompts in our applications, so don’t worry if what you see looks different.)
cd /
path
/
to
/
directory
and press Return (Mac) or Enter (PC).
To compile your first.cpp
application, you’ll want to be within the directory where it was saved. The cd
command will accomplish that, but you’ll need to change /
path
/
to
/
directory
to correspond to the location of the file and the operating system being used. You might end up using something like
cd C:Documents and SettingsLarry UllmanCppCh01
(Windows)
or
cd ~/Documents/Programming/Cpp/Ch01
(Mac OS X, where ~ represents your home directory)
g++ -o first first.cpp
and press Return or Enter (Figure 1.5).
Assuming that g++ has been installed on your computer, this command will compile the first.cpp
file. If no errors occurred (which really should be the case, as there are only three lines), the result will be a file called first
(formally first.exe
on Windows).
If you do not have the g++ compiler on your computer (in which case, you’ll see an error message saying as much), you’ll need to install it per the instructions in Appendix A. Alternatively, if the command indicated that the compiler could not be found, you may need to use an absolute path to the compiler in order to use it. For example:
/usr/bin/g++ -o first first.cpp
(Unix and Mac OS X)
C:ing++ -o first first.cpp
(Windows)
You can either view the directory in the Explorer (Windows) or Finder (Mac OS X) or use the proper command-line prompt. This would be either
dir
(Windows)
or
ls
(Unix and Mac OS X, as shown in Figure 1.6)
exit
and press Enter or Return to close the console session.
This will close the console window on Windows; other users may need to close the window or quit the application as a separate step.
• To learn more about the compiler you are using, search the Internet or check out the compiler’s manual page (for example, type man g++
within a Terminal window on Unix or Mac OS X).
• As a compiler merely turns your C++ code into an executable application, the better your C++ code is, the better—in terms of performance and size—the resulting application will be. The examples in this book are oriented toward writing the most stable and efficient applications possible.
• The compiler is the key to creating applications in C++. Compilers take generic, possibly operating system–indifferent, C++ code and create an executable file for that particular platform. So the compiler on Windows will create a Windows application, and a compiler on Unix will create a Unix application.
If you were to run the successfully compiled first.cpp
program, you’d see, well, nothing (Figure 1.7). This makes perfect sense, as the main()
function only returns a value of 0
without doing anything else. To make an application that does a little something, have C++ print a message using this syntax:
int main() {
std::cout << "Testing";
return 0;
}
This construct looks rather strange to a new C++ programmer, so we’ll break it down into its parts. First of all, cout
, which stands for console out, is a stream, an avenue through which data can be transferred (the std::
also has special meaning, which you’ll learn in time). The <<
is an operator used to insert the following text (Testing) into the cout
stream. Finally, the line concludes with a semicolon, which indicates the completion of a statement. All statements in C++ must end with a semicolon, as you already saw with return
. So in short, this line of code says “take this string of text and put it in the console output.”
Unfortunately, printing messages is slightly more complicated than just that one line. The cout
stream is defined in a special library of code called a header file. In order to refer to cout
, the header file itself must be brought into this code, using a preprocessor directive (see the sidebar “Preprocessor Directives” later in this chapter). It sounds complicated, but it’s just a matter of coding
#include <iostream>
This line states that the iostream
package should be included as part of this application. Including a library has the same effect as making that file’s contents part of this document (but without the extra typing or lines of code). Note that preprocessor directives are placed outside of, and before, the main()
function.
The complete code is therefore
#include <iostream>
int main() {
std::cout << "Whew!";
return 0;
}
While all of this code may seem like a lot of work just to print a simple message, it will become second nature as you master the underlying purposes of each element. Using this new bit of code, you can modify the existing application so that it actually does something.
first.cpp
(Script 1.1) in your text editor.main()
function definition, add the following (Script 1.2):
#include <iostream>
To use cout
in your program, this library must be included.
main()
function but before the return line, add
std::cout << "Hello, World!";
You haven’t programmed until you’ve written a classic Hello, World! example. This is a staple of every programming book and tutorial.
hello.cpp
.
So as not to overwrite the first example, you should give this file a new name, one that is descriptive of what the file does.
hello.cpp
using the instructions outlined in the preceding section of this chapter (Figure 1.8).
You’ll need to access the same directory where hello.cpp
is found using a command-line interface. Then invoke the compiler with
g++ -o hello hello.cpp
• Statements in C++ can run over multiple lines, for example:
cout << "Start..."
"...End";
You can also put multiple statements on one line, as long as each is separated by a semicolon.
• All of the examples in this book will print their messages to the command prompt window, where the applications run. You can, using C++, create conventional applications that display text within the context of a proper interface, but this is beyond the scope of the book as well as standard C++, requiring a graphical user interface (GUI) builder, application programming interfaces (APIs), or other nefarious acronyms.
• The std::
code before cout
has to do with namespaces, an advanced concept that basically dictates what variables and functions are available to use. The heavy-handed alternative is to add the line
using namespace std;
after including the iostream
file. Then you can use just cout
:
cout << "Hello, World!";
We feel there are good reasons not to use this other method, which will be explained in Chapter 12, “Namespaces and Modularization.”
Now that you’ve written and compiled two C++ applications (albeit simple ones), it’s time to actually execute them to see the results of your work. Once you’ve successfully compiled an application (in other words, no errors were found), you are left with an executable file. Regardless of the operating system, you can run this application from the command line, just as you compiled it using a command-line compiler.
On Windows, you can simply type the full name of the application to run it:
first
You can also use the formal
first.exe
This will work as long as you are in the same directory as the executable. Otherwise, you could use a full path:
C:Documents and SettingsLarry UllmanCppCh01first
On Unix and Mac OS X, you can also type the full path to the executable:
/Users/larry/Cpp/Ch01/first
If you are in the same directory as the file, you’ll need to precede the executable’s name with ./
, like so:
./first
To reiterate, this means you either...
• Click the Start menu, select Run, type cmd
in the Open text box, and press Enter (for Windows users).
or
• Use the Terminal application that came with your operating system (Unix and Mac OS X).
cd /
path
/
to
/
directory
and press Return (Mac) or Enter (PC).
Again, you’ll want to be within the directory where the hello.cpp
file was saved and compiled. Change /
path
/
to
/
directory
to correspond to the location of the file and the operating system being used.
The syntax for running the file will depend on your operating system:
hello
(Windows; see Figure 1.9)
or
./hello
(Mac OS X, see Figure 1.10, and Unix)
exit
and press Enter or Return to close the console session.
This should close the DOS prompt on Windows. On other operating systems you may need to formally quit the application or close the Terminal window after exiting the session.
• Choose the name you give your resulting executable carefully so that it won’t conflict with existing programs and utilities. For example, if you were to create a program called pause on Windows, whenever you tried to run it using pause
, Windows would actually run the existing pause application, not yours. This can be quite confusing to the beginner.
• If you know that a program will compile successfully (because it has before and you just made a minor tweak), you can compile and execute in one step using
g++ -o appname filename.cpp;./appname
This works on Mac OS X and Unix.
There is, in fact, another way you can run your compiled application: simply double-click it in the Explorer (Windows) or Finder (Mac OS X). On Mac OS X, the application will open in a new Terminal window, execute the program, and then log out of that window (Figure 1.11). On Windows a new console window will open, the application will run, and the console window will close, all in the blink of an eye. Without the benefit of time-lapse photography or superhero powers, you won’t be able to see the results for yourself.
In order to give yourself the chance to see your program in action, a little trick can be used. By adding the line
std::cin.get();
to your C++ source code, you force the compiled application to wait until the user presses Enter or Return before it can continue executing. As you might infer, whereas cout
stands for console out, cin
is console in, which takes input from (in this case) the keyboard.
hello.cpp
(Script 1.2) in your text editor.return
, add the following lines (Script 1.3):
std::cout << "Press Enter or Return to continue.";
std::cin.get();
The std::cin.get()
call should be the penultimate line in the main()
function, coming after the Hello, World! message but before the return
. The end result of this is that the function will print the message, wait for the user, and then return 0
and exit.
To indicate to the user that they need to do something, an instructional message is added as well.
pause.cpp
.g++ -o wait pause.cpp
Because the -o
flag allows you to give the compiled application any name you choose, the executable can be called wait
(or trout
or doodle
or whatever). This is necessary on Windows, as there is already a built-in utility named pause
.
wait
application (Figure 1.13).
You can run this application using the command line (as shown in the preceding sequence of steps) or by double-clicking the executable file itself. Figure 1.14 shows the results of running the same application on Mac OS X.
• If you’re keen on cin.get()
, you can add another one before the first cout
, so that the application will wait for your keystroke before doing anything at all.
• In Chapter 4, “Input, Output, and Files,” cin
will be used to retrieve input from the user that will actually be used in the application.
While the functionality of the applications created so far is just dandy, there is room for improvement before getting into meatier examples. If you look at Figures 1.13 and 1.14, you’ll notice that all of the printed text appears on one line (meaning also that Press is immediately next to the exclamation mark ending Hello, World!). Furthermore, the source code itself (Script 1.3) is bunched together. By judiciously understanding and using white space—spaces, tabs, carriage returns, and newlines, both the raw code and the resulting application can be much improved.
C++, like many languages, is generally white space insensitive. This means that you can add blank lines to make your scripts easier to read and you can use spaces to indent code, as you’ve already seen. This is a critical concept in making your code more approachable.
A related issue is how to add white space to the messages printed by an application. For example, to add a newline to the outputted message, print the newline character:
std::cout << "There will be a break here:
";
An alternative is to use the special marker endl
. The endl
indicates that all of the preceding information should be sent to the output and then the cursor should be moved to the next line:
std::cout << "Some text" << std::endl;
The syntax for using endl
is different than that for using
(because endl
must also be inserted into the stream), but the end result will be the same.
To demonstrate how white space works in C++, you’ll fix the pause.cpp
example so that the source code is spaced out a little nicer and so that the result is more legible.
pause.cpp
(Script 1.3) in your text editor.#include
line, press Return or Enter once to add a blank line (Script 1.4).
This blank line will help to separate out the preprocessor directive from the main()
function itself.
main()
function to separate out unrelated blocks of code.cout
line to read as follows:
std::cout << "Hello, World!
";
The addition of
at the end of the string will create a break after that text, as if you pressed Return (or Enter). The end result will be a little bit clearer when the application is executed.
space.cpp
.space.cpp
using the methods already covered (Figure 1.15).
• Despite the fact that we highly recommend adding copious amounts of white space to your scripts, our scripts won’t be as spaced out as they should be, in an effort to save valuable book space.
• Certain characters, when escaped (preceded by a backslash), have special meanings (e.g.,
means a newline). You’ll learn about several others over the course of this book.
• When indenting sections of code, you should technically use four spaces instead of a tab. Doing so ensures compliance across all text editors.
Although they do nothing for the functionality of an application, comments are a critical part of any programming language. Comments are necessary to remind yourself—while you’re initially developing an application or when you come back months later—why you did certain things. These are some of the most common uses for comments:
• State the purpose of a file.
• Document who created a file and when.
• Note the thinking behind a function.
• Clearly indicate the meaning of variables.
• Explain why particular numbers are used.
• Mark contingencies or assumptions being made.
C++ supports two comment formats. The first and standard format uses two slashes together:
// This is a comment.
By using a double slash, you indicate that anything from that point until the end of the line is a comment, so it can even be used after some code:
return 0; // No problems.
The second format, which comes from C, uses opening and closing characters to indicate where a comment begins and ends. This format allows you to write comments over multiple lines:
/* Multiline comments have start and end delineators. */
While allowed in C++, this style of comment is less often used.
With this in mind, let’s rewrite space.cpp
so that it’s properly documented.
space.cpp
(Script 1.4) in your text editor.#include
, add comments describing this file (Script 1.5):
// comment.cpp - Script 1.5
// Created by Larry Ullman and Andreas Signer
// July 15, 2005
C++ should begin with documentation such as this, indicating the purpose of the file, who created it, when, why, etc. Throughout the rest of the book, you’ll see that the very first comment in every program indicates both the name and script number of the file.
cin.get()
line, add a comment indicating its purpose:
// Wait for the user to press Enter or Return.
This simple comment states exactly why the function is being called. It’s useful here, as nothing is ever done with the result of the function, which could be confusing when you revisit this code at a later date.
cout
line.
// std::cout << "Hello, World!
";
By inserting these characters before some code, you render that code inert. The result in this particular case will be that the Hello, World! message is never sent to the console because that cout
line is commented out.
comment.cpp
.comment.cpp
(Figure 1.16).
• Despite the fact that we highly recommend adding oodles of comments to your programs, the code in this book won’t be as documented as we’d advise, in order to save valuable book space.
• The multiline comment type (/* */
) can be a great debugging tool. You can use it to disengage sections of code while you’re attempting to solve a problem.
• While developing and inevitably altering your applications, always make sure that your comments continue to accurately reflect the code they comment on. If a comment indicates something different than what the code does, it’ll only lead to confusion.
All of the examples to this point have used the most basic of tools: a text editor and a command-line compiler. As we mentioned at the beginning of this chapter, you can also develop your C++ applications using an integrated development environment (IDE). There are many benefits to using an IDE:
• The text editor will probably have C++ syntax highlighting, indicating reserved words and structures like functions and other code blocks.
• You can often compile and run your program in one step.
• There will be a built-in debugger.
• You don’t need to use the command line at all.
• Most IDEs will create a standard C++ template for you.
To wrap up this chapter, we’ll quickly discuss how to create, compile, and execute a simple Hello, World! application using the Dev-C++ IDE on Windows and Xcode on Mac OS X. Both are free and truly excellent.
After this chapter, none of the examples will be reliant upon whether you’re using the basic tools or an IDE. Decide for yourself how you want to develop your applications. All of the remaining material focuses on the C++ code itself.
• Most IDEs will include a tutorial on basic usage, which is well worth your time to go through. Also, there are ample documentation and examples online for using both Xcode and Dev-C++ in particular.
Although using Dev-C++ is pretty straightforward, understanding how to use it with respect to the code and steps in this book merits discussion. The instructions for creating the examples in this book are somewhat generic—so that users on any computer using any text editor or IDE can follow along—but here is how we envision your going through the material, if you choose to use Dev-C++.
We like the idea of working with projects even though most of the applications in this book use only a single file at a time. Getting into the habit of creating projects will help you down the line when you’re developing larger-scale C++ tools.
Alternatively, you can select File > New Source file to begin creating a single C++ source document.
• Click the Console Application icon.
• Ensure that the C++ Project button is selected.
• Ensure that Make Default Language is selected.
• Give the project a name.
Certainly Dev-C++ has more to offer—as you can tell from the New Project window—than a plain console application, but for the purposes of this book, that’s where you’ll want to start out.
For your project name, use the basename of whatever file is being created. So if the example is making a file called hello.cpp
, name your project hello
.
We recommend using a separate directory for each project, keeping them organized by chapter, to help maintain the organization of your work.
After going through these steps, you’ll be given a C++ source template (Figure 1.19) that looks only slightly different than what you’ve seen so far.
You can now follow the particular instructions for an example, typing all of your code in the template so that it matches that in the book.
You can keep most of the templated code without a problem, in particular the int argc, char *argv[]
within the main()
function definition (you’ll learn about what these mean in Chapter 14, “Extended Topics”). The EXIT_SUCCESS
instead of 0
that is returned is also not a problem (EXIT_SUCCESS
just represents the system-specific value for successful execution of the program).
This will let you save the C++ source file itself. You can name it either hello.cpp
(a name matching the project name) or main.cpp
.
The compiler is linked to the Dev-C++ application, so you can compile your C++ code within it.
This will create a new console window (a DOS prompt) and begin running the compiled application.
Any syntax errors in your code will be listed in the Compiler tab. The specific line number where the problem occurred is listed as well.
• Steps 9 and 10 can be combined by selecting Execute > Compile and Run. Of course, you can always use the toolbar icons as well.
• On the Dev-C++ Resource Site (http://bloodshed.net/dev/), check out the Documentation page, which has links to various manuals, Web sites related to C and C++, and tutorials on using Dev-C++.
• In the New project window, if you click the Introduction tab, there’s an option to create a Hello World example (Figure 1.20). The resulting code is very similar to what you’ve learned thus far.
• You can create other templates that will appear in the New Project window by placing them in the Dev-C++Templates
directory on your hard drive.
• Selecting Execute>Run in Dev-C++ has the same effect as double-clicking on an executable in Windows Explorer. If you want to see the results of an application, you’ll need to use the std::cin.get()
trick to temporarily pause the execution.
Simply put, Apple’s Xcode is the kind of development environment programmers are used to paying hundreds of dollars for. It’s a top-notch IDE, with loads of features and support for many languages.
Xcode is part of a series of Developer Tools Apple releases with the operating system. If you have a set of Mac OS X discs, you should check for the Developer Tools CD to save yourself a large download. If you don’t already have a copy or if you want the latest version, Xcode is freely available from Apple’s Developer Connection (ADC) Web site (http://developer.apple.com/tools/xcode/). You’ll need to be an ADC member, but membership is free.
Once you’ve installed Xcode, take this quick tour to learn how to use it to create C++ applications.
As you can see in the description (at the bottom), this option is intended for building command-line tools written in C++, which is exactly what you’re doing in this book.
For your project name, use the basename of whatever file is being created. So if the example is making a file called hello.cpp
, name your project hello
.
main.cpp
in the project window (Figure 1.23).
Xcode uses these project windows to manage your projects. After you choose the project type, Xcode automatically creates some files for you. The most important in terms of this book is the main.cpp
file, which is your main C++ source code.
main.cpp
code does not appear in the bottom section of the window, click the Editor button (to the right of the stop sign).
You can edit main.cpp
by double-clicking it—which will make it appear in its own window—or by using the built-in editor. If you click Editor, the project window will be broken into three panes, with the editor at the bottom right.
The executable application itself can be found in the project_name
/build
folder.
• Even if you don’t want to use Xcode, you’ll want to install the Developer Tools, which also installs the g++ compiler on your Mac.
• Cocoa is Apple’s primary technology for creating Mac OS X applications. It uses Objective-C, a version of C that’s similar to C++. Knowing C++, after reading this book, you should be able to learn Cocoa with relative ease.
• The Developer Tools also include Interface Builder, for creating the graphical front end to an application. Search the Web for tutorials on creating applications using Xcode and Interface Builder.