This article is not about creating Windows GUI projects, but focuses on
creating simple command line projects with a main function, as well as
cout, cin, printf, and a few other basic commands. If you are trying to
write a "Hello World" project, or do some simple first year C++
programming task such as learning about recursion, finding a GCD, finding
prime numbers, and so on, then hopefully this article will be what you
need.
My target tool is C++Builder 4.0, but most of what I say here also
applies to C++Builder 3.0. Some of the things I say do not apply to
CBuilder 1.0, but perhaps users of that product will still find this
article useful.
Even under the best of circumstances, I tend to be a bit wordy, and in
this article I will explain most points in especially prolix detail, to
make the matter as clear as possible to new comers. In other words, I
will err on the side of over-explaining my point, rather than possibly
omitting some detail that might help a new comer get up and running.
I have attempted to make this article very easy to understand. It is
aimed at beginners, and will be of little use to advanced programmers. If
some of the terms I discuss in this article are new to you, then it is
likely that you are trying to do too much, too soon. In particular, you
are probably not yet ready to start becoming a C++ programmer. For
instance, if you don't understand where the Windows Start button is, or
what a directory is, then you need to learn more about computers before
you try to program in C++. Besides a basic knowledge of the Windows
environment, there are no other prerequisites for reading this article.
It is aimed at people who have never written a line of C++ before in their
life, or for those who are looking at C++Builder for the first time.
Programming from the Command vs. Programming in the IDE
When you first start C++Builder, it brings up a rich environment that
has a number of controls and buttons on it, as shown in Figure 1. This
whole environment taken as one is called the IDE, or Integrated
Development Environment.
Figure 1: The default CBuilder project is aimed at creating Windows
programs rather than the kind of program you would typically create in
Programming 101 course.
In the next few sections, I will describe how to compile a C++ project
from inside the IDE. If you wish, you can also create and compile a
C++Builder project from the command line, as described in the section
called "Creating a Command Line Project from
Scratch."
In some ways, it is simpler and easier to compile a program from the
command line. However, I believe that in the long run you will find the
IDE to be a more powerful and useful tool. The reasons for this will
become abundantly clear after you have read the sections of this paper
which reference the Online Help and the integrated Debugger.
My advice is to wade through the sections below on using the IDE,
rather than taking the seemingly simpler route of using the command line.
However, if you know something about text editors, DOS and compilers, and
want to get up to speed very quickly, then you may find the section on the
command line the shortest route to getting started. On the other hand, if
you are new to C++, and relatively unfamiliar with computers, you may
actually become productive more quickly if you take the seemingly longer
route and learn how to use the IDE.
In short, unless you have a strong preference for using the command
line, my advice is to use the IDE.
Starting Your First Project in the IDE
When you first launch CBuilder, you will be presented with an
environment designed to make GUI programming in Windows as simple as
possible. The general format for this type of Windows project is shown in
Figure 1. The type of project shown in Figure 1 differs in many ways from
the type of project your teacher probably wants you to create. In
particular, it includes advanced features such as buttons, edit controls,
and list boxes, all of which you will likely learn about only later in
your C++ programming career.
The first thing you want to do, then, is get rid of the default project
and create a new kind of project called a console application. A console
application has no forms, buttons, edit controls or list boxes. Instead,
it just outputs text to a simple console, or DOS, window. This kind of
simple console application is the type most often discussed in a beginning
level C++ programming course.
In CBuilder 3 and 4, you can create the right kind of project for a
programming 101 course by choosing File | New | Console Wizard. This will
pop up a dialog like the one shown in Figure 2. You should choose all the
default options; that is, you should set Window Type to Console and
Execution type to Exe. You do not need to include the VCL in your
project.
Figure 2: The main dialog in the CBuilder 4 Console Wizard, with all
the options set to the default settings.
Click the Finish button in the Console Wizard. At this time, you may
be prompted to save the previous project. You can usually choose the No
button in the Save dialog, since you probably have done no meaningful work
in the default project that came up automatically when you started the
environment. Needless to say, if you had been working on a project that
you want to save, then you should save your work.
Below I show three pictures, one as the environment will usually appear
immediately after you run the Console Wizard. The second shows what the
environment looks like after you close the Object Inspector, and the third
shows what it looks like after you close the Class Explorer. Tools such
as the Explorer and the Object Inspector are useful when creating certain
kinds of projects, but you might find them confusing at first, so you
might consider closing them if you feel more comfortable without them on
the screen.
Figure 3: CBuilder as it usually appears immediately after running
the Console Wizard.
Figure 4: CBuilder as it appears after you close the Object
Inspector.
Figure 5: CBuilder as it appears after you close the Class Explorer.
When taking these pictures, I have made the environment as small as
possible so that the JPGs I create will be small, and easy to download
over the web. The environment will appear slightly different on your
larger screen.
In CBuilder 1 and 3, there is no Class Explorer. In general,
do not be concerned if you don't see either the Object Inspector or the
Class Explorer. I mention them only so that you can close them and get
them out of the way. If they are already closed, or if your version of
the product does not contain a Class Explorer, then that's all the better
for your current purposes.
Saving Your Project
Once you have created your project, the next step is to save it. This
step can be a bit more difficult than you might suppose at first. In
particular, you need to save not one file, but two! Nevertheless, I don't
recommend putting this step off till a later, more convenient time. It is
definitely wisest to save your project immediately, as programmers have a
way of making mistakes that can lock up their system, causing the loss of
any unsaved work.
At this stage, there are two source files involved in your project.
One is the obvious one that contains your code, as shown in Listing 1.
Listing 1: The source for a simple, do nothing, CBuilder console
application.
#pragma hdrstop
#include <condefs.h>
//---------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
return 0;
}
The second file you can see if you choose Project | View Makefile from
the menu. (On some versions of product, this option may be on the View
menu rather than the Project menu.) I've decided not to include the full
listing of this file in this article, as it is overly long and not
particularly important. If you want, open it in your environment, and
look it over briefly, but don't dwell on it, as it is not important to you
at this stage in your programming career.
Your almost never need to make changes directly to this file. Its just
there, and will do its work for you automatically without you ever needing
to look at it, or think about it. If you need to make changes to the
file, you can choose Project | Options, from the menu, and use the easier
to understand dialogs to make changes. However, you shouldn't need to
think about this file at all until you have been programming in C++ for
quite some time. For now, you can just leave the file alone. You cannot,
however, afford to delete this file, and you must save it in the right
place or your project will not run.
The question now is how should you go about saving your files. In my
opinion, the first rule to follow is to put each project in its own
subdirectory! This is not obvious at first, but as you progress as a
programmer, you will find that your projects will become increasing
complex. In particular, they will involve more than just two files. In
fact, typical real world C++ projects involve at least 5 or 6 files, and
there is nothing at all unusual about them involving 20, 30, even 100 or
200 files. So I advise you to get in the habit of creating a directory
for each project, and to save your work in that directory.
To begin the process of creating a directory and saving your file,
choose File | Save All from the menu to bring up the Save Project As
dialog, shown in Figure 6.
Figure 6: The Save Project As dialog is the key tool used when
saving a project.
In the upper right hand corner of the dialog, there are four buttons.
The third one from the right can be used to create a new directory, as
shown in Figure 7. In particular, notice that I have created a new
directory called ProjOne.
Figure 7: Here I create a new directory where I can store my project
and its related files.
I then navigate into that directory by double clicking on it, or by
selecting it with the mouse and pressing the Enter key. Once I am in the
directory, I save my project under the name ProjOne, as shown in Figure 8.
Figure 8: Saving a project into a new directory is simple in
C++Builder.
When you are done, you might optionally want to open up the Windows
Explorer and visit the directory you have created. You should see
something like the sight presented in Figure 9, showing your new
directory, and the two files that have been saved into it.
Figure 9: Looking at your new project in the Windows Explorer can
help you understand what occurred when you saved your project.
Running Your First Project
After creating your project, then next step is to actually run the
program. You can do this in at least three ways. The simplest is to
press the green or blue run button on the Speed Bar, as shown in Figure
10. You can also choose Run | Run from the menu, or press F9. (The F9
hotkey may not be available on all versions of CBuilder, but you can
always look on the menu to see which hot-key is associated with the Run
option for your version of the product.)
Figure 10: Though the position may differ on your system, in this
picture the Run button is the green arrow on the bottom row, five icons in
from the left.
If all is set up correctly, the first time you run your project,
nothing will have appeared to happen. This is because you have written no
code for your project. Your program had no instructions to perform any
activities, so it just ran, and then quickly returned.
However, something very important did happen when you ran your "do
nothing" project. In particular, the empty default code created by the
IDE was compiled and linked into an executable, which is a program. If
you go back to the explorer, you can see that after running your program
once, there are now a slew of files in the ProjOne directory, as shown in
Figure 11.
Figure 11: When you compile a program, the BPR and CPP files from
your project usually generate files with an EXE, BPR and TDS extension.
As you contemplate this list of files, you will perhaps begin to
appreciate why I suggest creating a separate directory for each project.
C++ programs are very complicated, and it definitely pays to follow
certain clearly defined protocols to help keep your work organized. In
this case, creating a new directory for each program is one step you can
take to help you organize your work.
The most important file that is generated is the one with the EXE
extension. This is your main executable. It is a real C++ program, that
just so happens not to do anything useful. For now, you can regard the
other files as mere effluvia. If you wish, you may delete these other
files, such as the ones with an OBJ or TDS extension. Certainly you need
not hand these files into your teacher. Your professor will probably only
care about your BPR and CPP file, and possibly your EXE file.
I should perhaps add that it is a peculiarity of C++Builder to put a
BPR extension on your make file. In most programming environments this
file would have an MAK extension. Nevertheless, this is just a standard
makefile, albeit one that is tailor made to run smoothly in C++Builder.
If you want to use a simpler makefile, and compile from the command line,
then you can do that too, as explained later in this article.
Making Your Program Do Something Useful
To make your program actually do something, you can add two lines of
code to it, as shown in Listing 2.
Listing 2: A simple C++ program that writes a few words to the
screen.
#pragma hdrstop
#include <condefs.h>
#include <iostream.h>
//----------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
cout << "This is my first program.";
return 0;
}
This code differs from the code in Listing 1 because I have added the
line #include <iostream.h> and the line which reads:
cout << "This is my first program.";
C++ programmers use cout, pronounced See Out, to output data to
the screen. C programmers, however, use the printf function to achieve
the same goal. Here is the code that a C programmer would write:
#pragma hdrstop
#include <condefs.h>
#include <stdio.h>
//---------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
printf("This is my first program.");
return 0;
}
Notice that this program #includes stdio.h, rather than iostream.h,
and it uses printf instead of cout.
I will consider a description of the differences between C and C++ to
be beyond the scope of this article.
If you run either the C or C++ version of this program, it will print
the string "This is my first program" to the screen. However, you
probably will never see it display any output, because the window in which
the string is displayed will appear and disappear very quickly.
To correct this problem, you can use an old programming trick that your
teacher may or may not have mentioned to you. In particular, you can
change your code so that the program pauses before it ends, as shown in
Figure 12 and in Listing 3.
Figure 12: The output from your first program.
Listing 3: Adding a getch statement to your code will pause your
program so that you can view its output. To end the program, just press a
key.
#pragma hdrstop
#include <condefs.h>
#include <iostream.h>
#include <conio.h>
//-----------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
cout << "This is my first program.";
getch();
return 0;
}
In Listing 3 I show how to add conio.h to your program so that you can
call the getch function, which waits for the user to input a key. In
other words, it will run exactly the same as it did before, but the main
window won't close until you press a key. This gives you a chance to see
the results of your work. You can call the getch function in either a C
or C++ program.
Understanding the Auto-Generated Pragmas and Comments
Its not my intention to explain C++ or C to you in this paper. That is
your teacher's job. But there are a few comments that might be made on
the code that is automatically generated by C++Builder.
In Listing 5, I once again show the code generated by the Console
Wizard.
Listing 5: The code automatically generated by the Console Wizard.
#pragma hdrstop
#include <condefs.h>
//------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
return 0;
}
The first thing you might notice in the code is the long commented line
that consists of nothing but a bunch of dashes:
//-------------------------------------------------
This line of code serves no reasonably purpose in your application. If
you create a more complex program with lots of functions in it, then you
could use these comments to separate your various functions, thereby at
least theoretically making your code easier to read. These comments would
serve the same purpose in your code that spaces between a paragraph serve
on a printed page or on a web page: They just make it easier for the
programmer to see what is going on in the code. If they annoy you, just
delete them. They serve no purpose in your program at all other than to
make it easier for people to read it. The compiler doesn't care whether
they are there or not. The final executable generated by your program
will be exactly, to the byte, the same, whether you include the comment or
not.
The two pragma statements that are generated for you by the IDE are
also of little significance. A pragma is a command that you can give to a
particular compiler, but which will be ignored by other compilers. For
instance, both Borland and Microsoft make C++ compilers. There are
certain things you can ask the Borland compiler to do which the Microsoft
compiler might not understand. Conversely, there are things you can ask
the Microsoft compiler to do which the Borland compiler will not
understand. If you use the symbol #pragma, then you are telling the
compiler to ignore the following statement if it doesn't understand it.
It's a way of saying that what follows is some command specific to a
particular brand of compiler.
The #pragma hdrstop command tells the compiler to generate something
called a precompiled header. A precompiled header can make big, unwieldy
programs compile faster. Including this pragma can affect how fast your
code compiles, but it will not effect the speed or size of your final
executable. If you continue to study C++, you will learn all about
precompiled headers, but for now, you can ignore them. In other words, as
far as the beginning programmer is concerned, you can just delete this
pragma and your code will still run exactly the same. Just ignore it, or
if your teacher complains about having it in your assignments, then just
delete it. The command is not important at all until you start making
much larger projects that take a long time to compile.
The second #pragma statement tells the compiler not to emit a warning
if you don't use some of the parameters passed to a function. In
particular, the main function gets passed two parameters called argc and
argv:
int main(int argc, char* argv[])
In many C and C++ programs, such as the ones created in this paper, you
never use these parameters. The compiler, however, is smart enough to
notice that you don't use them, and so it politely emits a warning, saying
that you haven't used the parameters, and perhaps that is because you are
making a mistake and simply forgetting to use them. Well, it so happens
that there is no mistake in this case, as your teacher can know doubt
explain to you if you ask for some clarification on these parameters and
their purpose. By placing the argsused pragma before this statement, you
are saying, in effect, "just ignore the fact that I don't use these
parameters. Don't emit a warning, don't try to help me, I know what I'm
doing. Leave me alone."
Once again, if you delete this pragma, then no harm will be done. The
compiler will then emit warnings stating that you failed to take advantage
of the parameters, but that is not a programming error. It was just a
choice you made. The code found in final executable will be exactly, to
the byte, the same whether you include the pragma or not. Its only
purpose is to suppress compiler warnings.
The final point about the code generated by the compiler concerns the
#include condefs.h statement. The condefs.h file contains some
definitions that the Borland compiler needs in order to properly generate
a 32 bit console application of the type you are creating in this paper.
The programs that I have shown you in this paper are totally correct
C++ progams. However, if you tried to compile them on a Unix machine, for
instance, the Unix compiler would probably not know anything about the
condefs unit. So you could just comment that line out if you wanted it to
compile on another machine.
I should perhaps be a little more clear about the reasons the
condefs unit exists. When you get more experience programming in C++, you
will start to create real Windows programs with buttons, and forms and
list boxes. When you do that, you will find that C++Builder has visual
tools that make creating that kind of program remarkably easy. When
adding the visual tools to the compiler, Borland tried to make as few
changes to the C++ language as possible. However, the C++ standard knows
nothing about visual programming tools, and so we had to add some things
to the language to make it do the cool things that make Windows
programming easy. In the types of simple console applications that you
are creating, you don't want to use any of those cool features. The
condefs header file contains some macros that tell the compiler to just
act like a normal C++ compiler, and to not try to do anything special.
In any event, whether condefs is defined or not, C++Builder is a real
C++ compiler that has very advanced support of the C++ standard. You can
use it to create any program that your teacher assigns to you.
Compiling IDE Projects from the Command Line
So far, everything I have shown you involves using the IDE. That is,
you have opened up CBuilder programming environment, and programmed from
inside of it. This gives you lots of advantages, such as a good editor
with syntax highlighting, as well as the online help and debugging options
discussed later in this article. You may, however, prefer to work outside
of the IDE. This is known as programming from the command line. I don't
recommend that you program from the command line, so most readers can skip
this section and the next. I realize, however, that you may want to use
the command line, and so I will include a description of how to proceed.
You can always compile any C++Builder project from the command line
with the following simple command:
make -f projone.bpr
You can, of course, substitute the name of your program where I have
written projone.
Debugger Basics
Besides the online help, another topic you need to understand is the
debugger. All programmers, including the vast majority of professional
programmers, find the debugger to be an invaluable tool. Even if your
teacher or a friend says that the debugger is not really helpful, my
strong suggestion is that you should ignore them and learn how to use the
debugger anyway. People who disparage debuggers are a rather peculiar
breed, who are giving you, for good reasons or bad, the same kind of
advice you might get from someone who would suggest that it is better to
wash the dinner dishes by hand rather than to use a dishwasher. Okay,
that might be true from some perspectives, but most people would still
rather use the dishwasher because it is easier. There are indeed some
character building virtues which can be derived from not using a debugger,
but as a rule, debuggers make programming so much easier, that all but a
handful of developers rely on them in their daily programming practice.
Now that you know how to create and run programs in CBuilder, it is
perhaps helpful to give you a brief introduction to the debugger, so that
you can understand one of the chief reasons to use CBuilder. You don't
have to know the material I present in this section, I am simply adding it
here because I know that all developers, including those in a classroom
type situation, find a debugger to be an invaluable tool.
Consider the simple program shown in Listing 6.
Listing 6: The following simple program, called Debug1 can serve as
a test bed while you are learning the basics about the CBuilder debugger.
#pragma hdrstop
#include <condefs.h>
#include <iostreams.h>
#include <conio.h>
void SaySomething(char *S)
{
cout << "Hello " << S << ", glad to meet you.";
}
#pragma argsused
int main(int argc, char* argv[])
{
char S[1024];
cout << "Tell me your name: ";
cin >> S;
SaySomething(S);
getch();
return 0;
}
The CBuilder debugger can help you easily find any mistakes that you
might make in your program. To get started, run the Console Wizard and
type in the simple program shown in Listing 6. Save the program into its
own directory, and call it Debug1.
Press the F8 key to start the debugger. Assuming you entered the
program correctly, you should soon see something like the output found in
Figure 13.
Figure 13: The CBuilder editor as it looks when you start debugging a
simple program.
Press F8 a second time, and your program should look as it does in
Figure 14.
Figure 14: The CBuilder editor as it looks after you have stepped to
the second line in the Debug1 program.
Notice the green arrow on the left, and the blue line that runs across
a line in your program. What is happening here is that the debugger is
stepping your through the code in your program one line at a time. When
you first started the program, as shown in Figure 13, you were on the
first line of code in your program. When you pressed F8, you stepped to
the second line of code in your program. The line that says char S[1024]
was simply skipped over, since it is a simple declaration that doesn't
actually do anything. You will only step to lines of code in your
programming that actually execute code.
Press F8 a third time, and you will highlight the line that reads cin
<< S. This line of code accepts input from the user. When you press F8 a
fourth time, the blue line and green arrow will disappear. This is
happening because your program is getting the focus. It is now time for
you to enter some data, and so the focus switches away from the debugger,
and to the main window of your program, as shown in Figure 15.
Figure 15: The main window of your program, as it appears when you
are typing in your name.
It is up to you to switch from the debugger to the output window of
your program. To do this, you would typically hold down the Alt key, and
the press Tab, one or more times, till you reach your program. When you
find your program, let go of the Alt key, and your should see something
like the screen shown in Figure 15. This is not a hard thing to do. It
doesn't involve having a fast reaction time. Just hold down the Alt key,
and then tap the Tab key to iterate through the currently running programs
on your machine. At this point, there should be at least two programs
running, one of which is CBuilder, and the other of which is the Debug1
program that you created.
After you enter your name and press the enter key, you will be returned
automatically to the CBuilder debugger, as shown in Figure 16. You should
not need to press Alt - Tab to get back to the debugger.
Figure 16: The debugger as it appears after you return from the
output window.
As you can see from looking at Figure 16, your program is now about to
call the SaySomething function. To reach that function, you should press
F7, rather than F8. That is, you should step into this function, rather
than stepping over it. After you step into the function, the compiler
will look as it does in Figure 17.
Figure 17: Stepping into the SaySomething function.
If you press F8 again, you will highlight the cout function that sends
output to the screen. Take the mouse and hold it over the variable S, as
shown in Figure 18. You should literally place the mouse cursor over the
variable, and then leave it there for a second or two. You might even
want to just let go of the mouse, so that it has time to find the value of
the variable you are pointing at.
Figure 18: Using the debugger to view the value of a variable. In
this case, the variable S contains my name.
A second way to view the value of a variable is to select View | Debug
Windows | Watch from the CBuilder 4 menu, or View | Watch from the
CBuilder 3 or CBuilder 1 menu. This will pop up a special window. Double
click on this window to bring up a dialog that will let you enter the
variable S into an edit control. Press the okay button, and the watch
window will hold a copy of your variable, showing its current value. This
process is shown in Figures 19 and 20.
Figure 19: Entering the variable S into the Watch Properties dialog.
Figure 20: Viewing the value of the variable S in the debugger.
At this point you can press F8 a couple more times till you go back to
the main function and reach the getch() statement. At that point, the
focus will again switch to the main window. If you Alt - Tab over to the
main window, you will see the output shown in Figure 21.
Figure 21: The final output from your program.
There is another basic concept in debugging called setting a break
point, but I will not cover that in depth in this article. The idea
behind a breakpoint is to allow you program to run to a particular point,
and then stop, taking you automatically to the debugger so that you can
step through code line by line. The point is that there may be a part of
your program that you don't want to step through line by line, but you
want the debugger to slow down when it gets to the part of your program
that concerns you. Since this paper is aimed at beginners, I will assume
you don't need this feature yet, since the programs you are working with
are so small. However, in the long run, you should use the online help to
find out about breakpoints.
Summary
The information covered in this paper should be enough to get you up
and running with C++ Builder. This is a big product, with lots of
features, but in this paper I have focused on the features most commonly
used by beginning programmers in a Programming 101 or 102 course.
C++Builder is a great environment for creating C++ programs. It easily
adapts itself to the needs of both advanced and beginning programmers.
Take the time to learn how it works, and you will find that you can use it
to build any type of Windows program imaginable.
Connect with Us