Getting Started with C++

By: Priya Emailed: 1743 times Printed: 2434 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Should I Learn C First?

The question inevitably arises: "Since C++ is a superset of C, should I learn C first?" Stroustrup and most other C++ programmers agree. Not only is it unnecessary to learn C first, it may be advantageous not to do so.

Your Development Environment

I assume that your computer has a mode in which you can write directly to the screen, without worrying about a graphical environment, such as the ones in Windows or on the Macintosh.

Your compiler may have its own built-in text editor, or you may be using a commercial text editor or word processor that can produce text files. The important thing is that whatever you write your program in, it must save simple, plain-text files, with no word processing commands embedded in the text. Examples of safe editors include Windows Notepad, the DOS Edit command, Brief, Epsilon, EMACS, and vi. Many commercial word processors, such as WordPerfect, Word, and dozens of others, also offer a method for saving simple text files.

The files you create with your editor are called source files, and for C++ they typically are named with the extension .CPP, .CP, or .C. In this book, we'll name all the source code files with the .CPP extension, but check your compiler for what it needs.


NOTE: Most C++ compilers don't care what extension you give your source code, but if you don't specify otherwise, many will use .CPP by default.

DO use a simple text editor to create your source code, or use the built-in editor that comes with your compiler. DON'T use a word processor that saves special formatting characters. If you do use a word processor, save the file as ASCII text. DO save your files with the .C, .CP, or .CPP extension. DO check your documentation for specifics about your compiler and linker to ensure that you know how to compile and link your programs.

Compiling the Source Code

Although the source code in your file is somewhat cryptic, and anyone who doesn't know C++ will struggle to understand what it is for, it is still in what we call human-readable form. Your source code file is not a program, and it can't be executed, or run, as a program can.

To turn your source code into a program, you use a compiler. How you invoke your compiler, and how you tell it where to find your source code, will vary from compiler to compiler; check your documentation. In Borland's Turbo C++ you pick the RUN menu command or type

tc <filename>

from the command line, where <filename> is the name of your source code file (for example, test.cpp). Other compilers may do things slightly differently.


NOTE: If you compile the source code from the operating system's command line, you should type the following:

For the Borland C++ compiler: bcc <filename>

For the Borland C++ for Windows compiler: bcc <filename>

For the Borland Turbo C++ compiler: tc <filename>

For the Microsoft compilers: cl <filename>


After your source code is compiled, an object file is produced. This file is often named with the extension .OBJ. This is still not an executable program, however. To turn this into an executable program, you must run your linker.

Creating an Executable File with the Linker

C++ programs are typically created by linking together one or more OBJ files with one or more libraries. A library is a collection of linkable files that were supplied with your compiler, that you purchased separately, or that you created and compiled. All C++ compilers come with a library of useful functions (or procedures) and classes that you can include in your program. A function is a block of code that performs a service, such as adding two numbers or printing to the screen. A class is a collection of data and related functions; we'll be talking about classes a lot, starting on Day 5, "Functions."

The steps to create an executable file are

1. Create a source code file, with a .CPP extension.

Compile the source code into a file with the .OBJ extension.

Link your OBJ file with any needed libraries to produce an executable program.

The Development Cycle

If every program worked the first time you tried it, that would be the complete development cycle: Write the program, compile the source code, link the program, and run it. Unfortunately, almost every program, no matter how trivial, can and will have errors, or bugs, in the program. Some bugs will cause the compile to fail, some will cause the link to fail, and some will only show up when you run the program.

Whatever type of bug you find, you must fix it, and that involves editing your source code, recompiling and relinking, and then rerunning the program.

HELLO.CPP Your First C++ Program

Traditional programming books begin by writing the words Hello World to the screen, or a variation on that statement. This time-honored tradition is carried on here.

Type the first program directly into your editor, exactly as shown. Once you are certain it is correct, save the file, compile it, link it, and run it. It will print the words Hello World to your screen. Don't worry too much about how it works, this is really just to get you comfortable with the development cycle. Every aspect of this program will be covered over the next couple of days.


WARNING: The following listing contains line numbers on the left. These numbers are for reference within the book. They should not be typed in to your editor. For example, in line 1 of Listing 1.1, you should enter:
#include <iostream.h>

HELLO.CPP, the Hello World program.

1: #include <iostream.h>
3: int main()
4: {
5:    cout << "Hello World!\n";
6:        return 0;
7: } 

Make certain you enter this exactly as shown. Pay careful attention to the punctuation. The << in line 5 is the redirection symbol, produced on most keyboards by holding the Shift key and pressing the comma key twice. Line 5 ends with a semicolon; don't leave this off!

Also check to make sure you are following your compiler directions properly. Most compilers will link automatically, but check your documentation. If you get errors, look over your code carefully and determine how it is different from the above. If you see an error on line 1, such as cannot find file iostream.h, check your compiler documentation for directions on setting up your include path or environment variables. If you receive an error that there is no prototype for main, add the line int main(); just before line 3. You will need to add this line before the beginning of the main function in every program in this book. Most compilers don't require this, but a few do.

Your finished program will look like this:

1: #include <iostream.h>
4: int main();
5: {
6: cout <<"Hello World!\n";
7:     return 0;
8: }

Try running HELLO.EXE; it should write

Hello World!

directly to your screen. If so, congratulations! You've just entered, compiled, and run your first C++ program. It may not look like much, but almost every professional C++ programmer started out with this exact program.

Compile Errors

Compile-time errors can occur for any number of reasons. Usually they are a result of a typo or other inadvertent minor error. Good compilers will not only tell you what you did wrong, they'll point you to the exact place in your code where you made the mistake. The great ones will even suggest a remedy!

You can see this by intentionally putting an error into your program. If HELLO.CPP ran smoothly, edit it now and remove the closing brace on line 6. Your program will now look like Listing 1.2.

Demonstration of compiler error.

1: #include <iostream.h>
3: int main()
4: {
5:    cout << "Hello World!\n";
6: return 0; 

Recompile your program and you should see an error that looks similar to the following:

Hello.cpp, line 5: Compound statement missing terminating } in function main().

This error tells you the file and line number of the problem, and what the problem is (although I admit it is somewhat cryptic). Note that the error message points you to line 5. The compiler wasn't sure if you intended to put the closing brace before or after the cout statement on line 5. Sometimes the errors just get you to the general vicinity of the problem. If a compiler could perfectly identify every problem, it would fix the code itself.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

Thanks a lot.

View Tutorial          By: Manna at 2008-07-07 22:18:49
2. View Comment

thanks for providing such services...

View Tutorial          By: vara at 2008-11-18 02:07:17
3. View Comment

Hi, you put a semicolon after "int main()" on your second code...
Thanks for the great tutorial though.

View Tutorial          By: noel4037 at 2009-12-28 06:40:17

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Priya
Getting started with ASP
EJB Entity Beans
Error Handling - Stderr and Exit - sample program in C
Pointers and Arrays in C
Data Types and Sizes in C
virtual inheritance example in C++
ctime() sample program in C++
TextBox sample program in J2ME
Advantages of Java Beans
list() contents of a Directory - sample program in Java
File example program in Java
continue and break statements in C++
Use of 'throw' in Java
Passing parameters to a function by value in C++
Demonstrating global and local variables in C++

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Calculating total based on the given quantity and price in C++
Difference between Procedural, Structured, and Object-Oriented Programming
assert() example program in C++
Dot (.) vs Arrow (->) to access data members in C++
Using cout in C++
Using Comments in a C++ Program
Constructors and Destructors in C++
Demonstrating global and local variables in C++
Operator Precedence in C++
strcpy() and strncpy() sample program in C++
Using cout.fill() in C++
Sorting an array of Strings in C++
A Brief History of C++
C++ Recursion function explained using Fibonacci series
Interface Versus Implementation in C++
Most Emailed Articles (in C++)
const Member Functions in C++
Printing values in DEBUG mode in C++
continue and break statements in C++
File in C++ - Writing text to a file in C++
if in C++
Returning values from a function in C++
Public versus Private members in C++
atoi(), itoa() in C++
qsort() sample program in C++
Call by reference in C++ Functions
Pass by Reference in C++ functions
Pass by Reference vs Pass Value in C++ functions
Compute the square root of the sum of the squares of an array in C++
Demonstration of Prefix and Postfix operators in C++
Where to Put Class Declarations and Method Definitions in C++