Sunteți pe pagina 1din 20

C++ Compilation and Running

Windows
The commands and process of compiling is different for different compilers.
Borland 5.5 Compiler and command-line tools
The free Borland 5.5 Compiler and command-line tools has, so far, been a great success. At this
time of writing, less than a month after we made it available, we have had hundreds of thousands
of downloads.
I have also received hundreds of emails asking me how to install and use these tools but there is
not really an install, per se. Rather, simply unzip the contents of the package and you are almost
ready to go.
First, let's look at the directory structure. The root, by default is called BCC55. Under this
directory you will find:

Bin

Examples

Help

Include

Lib

Bin
Bin is short for binaries. Under this directory you will find all of the command-line tools (as well
as RTL and STL dynamic libraries). These are 32-bit Windows exectuable, command-line
programs, which means if you double click on one of them from Windows Explorer you are
likely to see a flashing DOS box, that comes up and immediately goes away. These applications
are meant to be run from within a DOS shell. Meaning, you need physically move to the Bin
directory and type the name of the program that you want to run (unless this directory is first in
your path).
For example, if I were to run the compiler bcc32.exe without any arguments I would get a dump
of it's version and command-line options as shown.
[f:\borland\bcc55\bin]bcc32
Borland C++ 5.5 for Win32 Copyright (c) 1993, 2000 Borland
Syntax is: BCC32 [ options ] file[s] * = default; -x- = turn switch x off

-3

* 80386 Instructions

-4

80486 Instructions

-5

Pentium Instructions

-6

Pentium Pro Instructions

-Ax

Disable extensions

-B

Compile via assembly

-C

Allow nested comments

-Dxxx

Define macro

-Exxx

Alternate Assembler name

-Hxxx

Use pre-compiled headers

-Ixxx

Include files directory

-K

Default char is unsigned

-Lxxx

Libraries directory

-M

Generate link map

-N

Check stack overflow

-Ox

Optimizations

-P

Force C++ compile

-R

Produce browser info

-RT

* Generate RTTI

-S

Produce assembly output

-Txxx

Set assembler option

-Uxxx

Undefine macro

-Vx

Virtual table control

-X

Suppress autodep. output

-aN

Align on N bytes

-b

* Treat enums as integers

-c

Compile only

-d

Merge duplicate strings

-exxx

Executable file name

-fxx

Floating point options

-gN

Stop after N warnings

-iN

Max. identifier length

-jN

Stop after N errors

-k

* Standard stack frame

-lx

Set linker option

-nxxx

Output file directory

-oxxx

Object file name

-p

Pascal calls

-tWxxx

Create Windows app

-u

* Underscores on externs

-v

Source level debugging

-wxxx

Warning control

-xxxx

Exception handling

-y

Produce line number info

-zxxx

Set segment names

Examples
The examples directory contains one directory called stdlib. In that directory are a number of
source files that use various classes and algorithms available in the STL. Also, there is a makefile
that builds all of the examples. More on that later.

Help
There is one Windows help file. It is called bcb5tool.hlp. You can double-click on it from
Windows Explorer to read it. The following is a snapshot of one of the entries in the help file
which explains what each of the command-line tools do.
File

Description

BCC32.EXE

C++ compiler (32-bit), command-line version

BPR2MAK.EXE

Converts project file from XML to MAKE file format for use with commandline tools

BRC32.EXE

Resource compiler (32-bit), command-line version

BRCC32.EXE

Resource shell (32-bit)

CPP32.EXE

C preprocessor (32-bit), command-line version

GREP.EXE

File search utility

ILINK32.EXE

Incremental linker (32-bit), command-line version

IMPDEF.EXE

Utility used when building apps with Libraries

IMPLIB.EXE

Utility used when building apps with Libraries

MAKE.EXE

Make utility

RLINK32.DLL

Resource linker (32-bit)

TDUMP.EXE

File dump utility

TLIB.EXE

Utility for maintaining static-link libraries

TLIBIMP.EXE

(Type Library Import) tool. Takes existing type libraries and creates C+
+Builder Interface files. Incorporated into the Type Library editor.

TOUCH.EXE

Change files stamps to current date/time

TRIGRAPH.EXE Converts 3-character trigraph sequences into single characters


VCTOBPR.EXE

Converts Microsoft Visual C++ 5.0 and 6.0 project (.DSP) and workspace
(.DSW) files to their equivalent Borland C++Builder files

Include
This directory contains all of the header files for the Borland RTL, the STL (RW) and the
Windows SDK.

Lib
This directory contains all of the static and import library files and startup code modules.
Difference between Header files and Libraries
Generally, a header file notifies the compiler of certain things (mostly their existence or
declarations) so that the compiler can correctly build a single translation unit (such as a single C
file). A library file is the actual executable code that does the work as specified in that header
file. This is linked in by the linker to provide the actual functionality (the definitions rather than
just the declarations).
Putting it all together
So, now that you are armed with all this information you are probably wondering "How do I turn
my source code into a program?" We will start with the simplest case of a single source file,
console program. Here is the source code of a file called simple.cpp that I wrote in the text
editor, notepad:
#include <stdio.h>
int main(void)
{
printf("Output from running program");
return 0;
}
To build this into a program we only need to call the compiler. However, the compiler needs to
know what source file to build and where to find the header files and the library files. We pass
these to the compiler as command line options as shown:
bcc32 -If:\Borland\bcc55\include -Lf:\Borland\bcc55\Lib simple.cpp
The resulting program is called simple.exe and can be run by typing simple at the command-line.
Now, let's look at the case of a console program with two source modules. simple.cpp will
contain our entry point main and will call a function defined in the other module, funcs.cpp.
simple.cpp
#include "funcs.h"
int main(void)
{
return PrintSomeOutput("Output from running program");
}

funcs.h

#include <stdio.h> int PrintSomeOutput(char* output);

funcs.cpp
#include <stdio.h>
int PrintSomeOutput(char* output)
{
printf(output);
return 0;
}

To build this, simply add funcs.cpp to the previous compiler command-line as such:
bcc32 -If:\Borland\bcc55\include -Lf:\Borland\bcc55\Lib simple.cpp funcs.cpp
So what happens if you have a bunch of different include and library directories. Or hundreds of
source files. As you can imagine the command-line for this would be huge. You have two
choices. Wrap up all of these commands into a batch file or use a makefile. Makefiles are
prefferred, and next week we will delve into this. In the meantime, take a look at the makefile in
the Examples\StdLib directory as we will be dissecting it.
Console applications accept various parameters and switches that are typed in at the command
line or from a batch file. Though not as common under Windows, many operating systems, such
as UNIX or Linux use this format. Use of Borland C++ 5.5 assumes the user is comfortable
working within a console interface. Typically, the user will run an application such as edit or
Notepad to actually write their program (an editor is not supplied with the compiler). When the
user wishes to compile source code, they save the file out as "filename.cpp" and then use the
command-line tools from within DOS to compile and create an executable. Like so:
bcc32 filename.cpp
The first argument is name of the compiler tool, and the second argument contains the C++
source file. This application will attempt to compile the source code and will notify the user of
any errors in the code. If no errors are found it will create an executable. To display information
regarding the various switches, type "bcc32"
Step-by-step Instructions for Configuring your System for the Command-Line Compiler
Configuring the system environment:

Open a console box.


1. Start | Run...
2. Type "cmd" into the field [Enter] (or 'command', if 'cmd' is not found)
* If Windows 95/98:
Navigate to the root in order to modify the PATH reference in the autoexec.bat file.
3. Type "cd" [Enter]
4. Type "edit autoexec.bat" [Enter]
5. Insert a line and type "PATH=C:\BORLAND\BCC55\BIN;%PATH%"
6. Save the changes (Alt-F then hit S).
7. Exit edit. (Alt+F then press X).
* If Windows NT:
Add a path reference to the Environment variables:
3. Using the mouse, right-click on the "My Computer" icon (on your desktop) and choose
"Properties".
4. Click on the "Environment" tab.
5. Click on "Path" in the "System Variables" field.
6. Highlight the "Path" System variable (bottom).
7. Click in the "Value" field.
8. Append the line with ";C:\BORLAND\BCC55\BIN;" (exactly 1 semi-colon between
references)
9. Click on the "Set" button.
10. Click OK (in the "System Properties" window)
* Or, if Windows 2000/XP:
Add a path reference to the Environment variables:
3. Using the mouse, right-click on the "My Computer" icon (on your desktop) and choose
"Properties".
4. Click on the "Advanced" tab.
5. Click on the "Environment Variables..." button.
6. Highlight the "Path" System variable (bottom).
7. Click on the "Edit..." button.
8. Append the line with ";C:\BORLAND\BCC55\BIN;"
9. Click OK (in the "Edit System Variables")
10. Click OK (in the "Environment Variables" window) and click OK (in the "System Properties"
window)
Now, in the console window, type the following:
cd \ [Enter]
cd borland [Enter]
cd bcc55 [Enter]
cd bin [Enter]
Creating the configuration files:

Note: The command line should read: C:\BORLAND\BCC55\BIN


Part 1: Creating BCC32.CFG.
1. Type "edit bcc32.cfg" [Enter] (This creates the file and opens a blank window in the editor).
Alternatively, you can also type, 'notepad bcc32.cfg' to edit in Windows Notepad.
2. Add these lines:
-I"c:\Borland\Bcc55\include" (here c is the drive where Borland is installed)
-L"c:\Borland\Bcc55\lib"
(here c is the drive where Borland is installed)
3. Save the changes (Alt-F then hit S if using edit).
4. Exit edit. (Alt+F then press X if using edit).
Part 2: Creating ILINK32.CFG
5. Type "edit ilink32.cfg" (This creates the file and opens a blank window in the editor).
Alternatively, you can also type, 'notepad ilink32.cfg' to edit in Windows Notepad.
6. Add these lines:
Testing the compiler:
-L"c:\Borland\Bcc55\lib"

(here c is the drive where Borland is installed)

7. Save the changes (Alt-F then hit S, if using edit).


8. Exit edit. (Alt+F then press X, if using edit).
9. Type "exit" [Enter]
10. Restart Windows.
______________________________
Open a console box.
1. Start | Run...
2. Type "command" into the field [Enter]
Create a directory or navigate to where you want to store your source, for example:
3. Type "cd"
4. Type "mkdir MySource"
5. cd Mysource
(Now in c:\MySource)
Create a new source file, for example:
6. Type "edit hello.cpp" Alternatively, you can also type, 'notepad hello.cpp' to edit in Windows
Notepad.
7. Paste or type the following code in the editor:
#include <iostream.h>
int main(void)

{
cout << "Hello." << endl;
return 0;
}
8. Save the changes (Alt-F then hit S, if using edit).
9. Exit edit. (Alt+F then press X, if using edit).
Now, compile the program to create an executable:
10. Type "bcc32 hello.cpp"
Finally, you may run the application you created.
11. Type "hello"
(The output will appear below your last command line.)
Note: The programming process begins with the creation of a text file which contains the
statements of the program in a programming language. (This source file is a text file, usually
ASCII, which can be produced with a text editor, such as Windows notepad, or in an Integrated
Design Environment.) This source file is then processed by a special program called a compiler.
Each programming language has its own compiler, and the compiler must be matched to the
hardware and operating system that the new program will run on.
On PCs, the extension of the source file conventionally matches the programming language
used; .c for c programs, .cpp for c++ programs, .pas for pascal programs, .for for FORTRAN
programs, and so on.
The compiler translates the source code into code for the target system, known as object
code. This object code contains the machine instructions for the CPU, and calls to the operating
system API (Application Programming Interface.) Object code is the same for different source
languages, but will usually contain calls to run time subroutines which match the source
language. The object file is not yet executable, however.
On PCs, the extension of the object file is conventionally .obj.
The next step is to process the object file with another special program called a link editor.
The same link editor is used for object modules regardless of the original language in which the
new program was written. Each system has its own linker, however. The output of the link editor,
or linker, is an executable, or runnable, file .
On PCs, the extension of the run file is conventionally .exe. (PCs also use .com as an
extension for run files; these are created from .exe files by an extra step, and not all .exe files can
be converted to .com files.)

For the C++ language, there are two kinds of source files, and two steps to the compile process.
In addition to the main (.cpp) source files, which contain executable statements, there are also
header (.h or .hpp) source files. Header files normally contain only declarations. Since all input
and output in C++ programs is done through library functions, almost all C++ programs use
standard header files, which are supplied with the compiler. Header files should also be written
as part of the source code for modular C++ programs (see below.)
The first step of the compile process is a special preprocessor program. The preprocessor
program reads the source file as text, and produces another text file as output. Source code lines
which begin with the octothorpe character ("#") are actually written not in C++ itself, but in
preprocessor language. Based on these statements, the preprocessor makes substitutions of one
character string for another, substitutes the text of a header file for #include statements, and even
expands some function calls into other text. The substitutions can be conditional. The output of
the preprocessor is a text file which does not contain any preprocessor statements, which is ready
to be processed by the C++ compiler itself.
The link editor also combines the object file with library routines (supplied with the compiler) to
produce the executable file.

When modular programming is used, the source code is divided into two or more source files.
These files are compiled separately, producing multiple object files. The object files can be
combined by the link editor into the same executable file.

The resource script is separately compiled by a resource compiler into a resource object file,
which is then combined with the .exe file by a resource linker.

LINUX
The commands and process of compiling is different for different compilers.
How to write and compile C++ programs
In order to run a program and see it doing wonderful things, you should first write the
program. The program can be written in any text editor, such as vi and emacs in Unix
environment and using command prompt in DOS. There are also several Integrated Development
Environment (IDE) packages available which provide a complete programming environment for
C++ in which you can write, compile, run, and debug your program. C++ programs are saved
with extensions .C, .cc, .cpp, .cxx depending on the platform you are working upon. Once you
have saved a program, next stage is compiling it using a compiler which converts your C++
program into the object code which the computer can understand.
Installing compilers is one of the easiest things there out at Linux. It may seem a bit tough and
complicated in the beginning but apt-get(Ubuntu) and Synaptic Package Manager(Ubuntu)
simplify your work a lot. In ubuntu g++ compiler (i.e build-essential package) is installed by

default. As a newbie developer you would require a C/C++ and a Java compiler. Installing them
is a matter of few commands.
The GNU C and GNU C++ Compiler:
The GNU C compiler is also called gcc and C++ is called g++. You may also require the GNU
make utility. All of them can get installed by getting the build-essential package. Just use this
command:
sudo apt-get install build-essential
if above package not available download GNU C++ compiler (from Ubuntu Software centre for
Ubuntu).
Compile using g++ compiler
If you are using UNIX environment and using g++ compiler, then compiling your C++ program
is simple. After you have saved the program file, simply type the command
g++ program.cc o program
where program is the name of the program. For example the name of our first program is first,
then save it using extension first.cc. To compile, type
g++ first.cc o first (does both compiling and linking here.)
To run the program, type first or ./first at the command prompt and your program will run.
Note:
1. If using #include <iostream.h> gives error (fatal error: iostream.h : no such file or
directory) use #include <iostream>. <iostream.h> is deprecated - it is the original
Stroustrup version, and < iostream> is the version from the standards committee.
Generally compilers point them both to the same thing, but some new compilers won't
have the older one. In some odd cases they will both exist and be different (to support
legacy code) and you then must be specific.
2. using namespace std: All the elements of the standard C++ library are declared within
what is called a namespace, the namespace with the name std. So in order to access its
functionality we declare with this expression that we will be using these entities. This line
is very frequent in C++ programs that use the standard library, and in fact it will be
included in most of the source codes included in these tutorials. If scope error is given
like 'cout' not declared in the scope add using namespace std; after
#include<iostream.h> i.e for example
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello." << endl;
return 0;
}

This explanation is going to be targeted at using g++ (its generally the default compiler on Linux
system and it is the default compiler underneath Mac OS X's xCode). Microsoft's Visual Studio
also has a C++ compiler that you can access, called cl.exe, and it provides many of the same
options that g++ provides albeit via different command switches. To start with, you run g++
simply by typing g++ at a command prompt (for Mac OS X that normally involves starting
Terminal.app and on Linux you can start up a similar terminal program, Gnome and KDE both
provide one). When you run g++ on its own with no arguments you should get something similar
to this as a response:
g++: no input files.
To actually compile a C++ file, you need to call g++ with the filename containing the C++ code.
So if your code is contained in a file called main.cpp, to compile it, just type 'g++ main.cpp'.
Assuming you have no errors, this will produce an executable file called '\1 (on Linux and Mac
OS X). To run your resulting executable, just type './a.out'. This is about the most basic thing
you can do to produce an executable from your C++ code. Since the number of options provided
by g++ is vast, only a few basic options will be covered here and you can look into other options
as you see fit.
The first option to look at is the -o switch that g++ provides. In the example above, the
compiler extracted the code from your file and created a new file called 'a.out'. If you want to
override this default name and instead call the output executable file main, you would execute
the following command 'g++ main.cpp -o main'. When g++ finishes, it will have created an
output file called 'main' instead of 'a.out' and to run it, you just type './main'. You should try
some different examples to get familiar with how this works.
The second option that is worth looking at is the -Wall switch. C++ is complex language
and it can often be unforgiving. So C++ compiler writers often look for ways to help
programmers avoid writing bugs. The -Wall switch that g++ provides is one such way. What the
-Wall flag does is tell g++ to generate warnings for any code that it encounters that is
syntactically correct but looks suspicious semantically. In many cases -Wall can uncover bugs
before you even run the program because they are common mistakes and g++ can know to look
for them. Here are some useful examples.
#include <iostream>
using namespace std;
int main (void)
{
int a = 3;
cout << "++a is: " ++a << " and a++ is: " << a++ << endl;
return 0;
}
At first glance, this looks ok but this actually contains the worst type of bug possible in C++, the
dreaded "undefined behavior"! Assuming the code above is in a file called main.cpp, the
command 'g++ main.cpp -o main' returns with no complaints. However, compiling with
'g++ -Wall main.cpp -o main' gives the following output:
main.cpp: In function
'int main()':

main.cpp:8: warning: operation on 'a' may be undefined


On finding something suspicious, g++ gives you the file and the line number of the offending
code. Pretty useful. Admittedly, this is a relatively new warning heuristic in g++ and if you have
an earlier version of g++ it may remain silent. However, it shows you that the compiler
can really help you track down bugs if you take advantage of its abilities. There are many more
examples of options that your compiler provides that you should try to take advantage of.
However, it should be noted that sometimes g++ gives false positives when using -Wall but in
general, you should be wary of code that generates warnings.
Compiling and linking
Figure 1 illustrates the relationship between the various files (indicated by oval boxes) that are
needed to construct an executable program.

Figure 1: Compiling and linking

The source files, in the example the files hello.C and message.C, contain C++ source
code instructions written in the source language, in this case C++. Such instructions can be
divided into two kinds:
o
definitions, which, roughly, cause the compiler to "output" something, e.g.
assembler instructions or memory reservation for variables. E.g. the following C++ statements
are definitions.

int v;
int f() { ... }
o

declarations, which only inform the compiler of the existence or properties of


functions, variables, types etc., without causing any (immediate) output.
extern int v;
int f();
Definitions should only appear in .C files. Header files such
as message.h should only contain declarations, never definitions. In the
example, message.h contains a declaration of a symbol ("message") that is used but not defined
in hello.C. On the other hand, message.C contains the definition of "message".
The object files, in the example the file hello.o and message.o contain machine
language instructions, possibly (very likely) with unresolved references. E.g. in the example, the
file hello.o refers to an external variable symbol "message" that was declared but not defined in
the source file hello.C1. Any reference to the "message" symbol in hello.o is unresolved.
The executable file, also called program, contains fully linked machine language
instructions where all references to function and variable symbols have been resolved by
the linker. The linker combines several object files into one executable file and fills in all
unresolved references in all these files, using information on what is available in the other files
(or in libraries, see Section 2 below).
The various C++ source files are shown below.
// $Id: hello.C,v 1.2 1999/08/02 10:47:11 dvermeir Exp $
#include <iostream>
#include "message.h"
int
main(int argc,char *argv[]) {
std::cout << message << std::endl;
}
In hello.C, the "#include" directive on message.h ensures that "message" is declared so that the
compiler knows its type etc.
// $Id: message.C,v 1.2 1999/08/02 10:47:11 dvermeir Exp $
#include "message.h"
const std::string message("hello world");
Also message.C uses the "#include" directive on message.h. This is useful because, when
compiling message.C, the compiler first sees a declaration (from message.h) and then a
definition of "message" which allows it to check the consistency of one with the other. Chaos
would ensue if message.C would not include message.h and e.g. "message" was declared as an
integer in message.h and defined as a string in message.C).
#ifndef MESSAGE_H
#define MESSAGE_H
// $Id: message.h,v 1.3 1999/08/07 08:54:50 dvermeir Exp $
#include <string>

extern const std::string message;


#endif
Note that the entire file message.h is conditionally included, using a
preprocessor #ifndef...#endif directive. Together with the #define MESSAGE_H on the second
line, this ensures that message.h will be included at most once in any compilation.
2 Using libraries
Looking at hello.C, we notice that it also includes (and uses) iostream. This file contains
declarations of various standard library classes dealing with input/output. Thus, hello.o will also
contain unresolved references to e.g. output functions. The linker resolves these references by
consulting the standard C++ library, as shown in Figure 2.

Figure 2: Compiling and linking with a library

Static libraries
In the example, the linker looked at the standard library in
/usr/lib/libstdc++.a. (by convention, files with a ".a" suffix are static libraries). This means that
the linker will copy the code (or data) corresponding to the unresolved references from the

library file, and add them to the executable file. Simply put, the linker will extract those object
files from the library (a library can be thought of as a collection of object files) that are
(recursively) needed by the other files and add them to the resulting executable file. This process
is called static linking (with libraries).
If, after linking, we were to remove the library file /usr/lib/libstdc++.a, the executable
file hello would still work.
It is possible to create your own libraries, see Section 3.3.

2.2 Dynamic libraries

1.
2.

3.
4.

Static linking has the disadvantage that it increases the size of the executable file. E.g. almost
every statically linked executable file contains its own copy of the C++ iostream code, which
may use a considerable amount of disk space. Also, if a new version of the library is available,
statically linked executable files will need to be linked again in order to use the new version of
the library.
An alternative way to link with libraries is to use so-called dynamic (also called shared) libraries.
Conventionally, dynamic library files have names ending with ".so", like /usr/lib/libstdc++.so.
When linking with a dynamic library, the linker does not copy any objects; it just remembers
which parts of which library are needed by the executable file. Thus, dynamically linked
executable files tend to be smaller. At run time, i.e. when the program2 is actually executed,
the dynamic loader will step in and add the missing parts of the dynamic library to the program.
To find, at run time, the appropriate library, the dynamic loader (called ld.so under Linux)
proceeds as follows:
First, it is possible to store a runpath in the executable file. This runpath is a list (much
like the PATH shell variable) of directories, separated by colons (":"). If such a runpath exists,
the dynamic loader will try to find any needed shared libraries in each of the runpath directories.
If the previous step fails, the dynamic loader will try to find the libraries in the directories
mentioned in the LD_LIBRARY_PATH shell variable, if it exists. Also
the LD_LIBRARY_PATH variable contains a list of directories, separated by colons (":"). Note
that the value of LD_LIBRARY_PATH is ignored for setuid/setgid programs.
Under Linux, try to find the libraries in /etc/ld.so.cache which contains a compiled list of
candidate libraries. See also the ldconfig command.
If any libraries remain to be found, the dynamic loader will look for them in the
directories /lib and /usr/lib.
The procedure above is very flexible: e.g. if the runpath is not used, it is possible, by simply
redefining LD_LIBRARY_PATH, to run the same program with a different version of a shared
library.
You can used the ldd command to find out which shared libraries are needed by an executable
file and where they would be found (using the current definition of LD_LIBRARY_PATH).
tinf2% ldd hello
libstdc++.so.2.9.0 => /usr/lib/libstdc++.so.2.9.0
libm.so.1 => /usr/lib/libm.so.1
libc.so.1 => /usr/lib/libc.so.1
libdl.so.1 => /usr/lib/libdl.so.1

tinf2% echo $LD_LIBRARY_PATH


/usr/lib:/usr/openwin/lib:
tinf2%
Using g++
G++ is used both for compiling and linking3 In this section, we explain the most common
options that are useful for compiling, linking (dynamic and static) and for producing libraries.

Compiling with g++


To produce an object file from a source file, use the -c option.(compile only) E.g.
g++ -c hello.C message.C
will produce both hello.o and message.o.
Finding #include files
The -I option can be used to tell g++ where it may look for include files. E.g. if the source file
contains
#include <tbcc/err.h>
where the full pathname of the file to be included is /usr/local/include/tbcc/err.h, one would use
g++ -c -I/usr/local/include hello.C
Warnings, debugging
It is good practice to use the -Wall option to tell g++ to warn about all suspicious or non-standard
constructs. Strangely, to warn about suspicious conversions, you need to use, in addition, the Wconversion option.
g++ -c -Wall -Wconversion hello.C
The -g option tells g++ to include in the object file extra debug information that is needed by
run-time debuggers such as gdb or ddd.
g++ -c -g hello.C
Optimization
If necessary (and only then), the -O, -O2 or -O3 options can be used to trigger code optimization
(-O3 will optimize more than -O2 which is itself "stronger" than -O). Of course, using these
options will slow down compilations.
g++ -c -O2 hello.C

Linking with g++


To produce an executable file from some object files, use the -o option to tell g++ the name of
the resulting program. E.g.
g++ -o hello hello.o message.o

will produce the executable file "hello".


If you need to link with libraries4, use the -L and -l options. The -L option is followed by the
directory of the library file while the -l option is followed by the identification of the library: use
"-labc" to link with the library "libabc.a" (for static linking) or "libabc.so" (for dynamic linking).

Dynamic linking with g++


By default, g++ will use dynamic linking. E.g.
g++ -o hello hello.o -L/usr/local/lib -ltbcc -L/usr/local/lib/mysql -lmysql
will produce the executable file hello, which will be dynamically linked
with libtbcc.so and libmysql.so.
Note that, since we did not specify any runpath, at run time, the dynamic loader will attempt to
find libtbcc.so and libmysql.so in a directory from the LD_LIBRARY_PATH variable.
To set the runpath:
Under Linux, use the -Wl,-rpath -Wl,dirs option5:
g++ -o hello hello.o -Wl,-rpath
-Wl,$HOME/mylib:/usr/local/lib -L/usr/local/lib -ltbcc
will ensure that, at run time, the dynamic loader will try to
find libtbcc.so in $HOME/mylib or /usr/local/lib (note that $HOME is expanded before it is
stored in the runpath).
Under Solaris, use the -R option:
g++ -o hello hello.o -R$HOME/mylib:/usr/local/lib -L/usr/local/lib -ltbcc
will ensure that, at run time, the dynamic loader will try to
find libtbcc.so in $HOME/mylib or /usr/local/lib.
3.2.2 Static linking with g++
G++ can be forced to link all libraries statically by using the -static flag in front of the library
specifications.
E.g.
g++ -o hello hello.o message.o -static -L/usr/local/lib -ltbcc
will result in a "stand-alone" executable file.
To statically link some static libraries, just list them as you would any object file:
g++ -o hello hello.o message.o mylibs/mylib.a
mylibs/junk.a L/usr/local/lib -ltbcc
will include the needed objects from the static libraries mylibs/mylib.a and mylibs/junk.a into the
resulting executable.

The Tools
We'll start the discussion with a look at the Linux programming tools g++, ar, make, and gdb:

g++ is the C++ compiler on most Linux distributions.


ar is a utility to create static libraries, for code re-use.
make is a utility to help manage projects that are made of several source files.
gdb is the debugger for the gcc and g++ compilers.

Compiling C and C++ Programs


gcc is the "GNU" C Compiler, and g++ is the "GNU C++ compiler, while cc and CC are the Sun
C and C++ compilers also available on Sun workstations. Below are several examples that show
how to use g++ to compile C++ programs, although much of the information applies to C
programs as well as compiling with the other compilers.
Example 1: Compiling a simple program
Consider the following example: Let "hello.C" be a file that contains the following C++ code.
#include "iostream.h"
int main()
{
cout << "Hello\n";
}
The standard way to compile this program is with the command
g++ hello.C -o hello
This command compiles hello.C into an executable program named "hello" that you run by
typing 'hello' at the command line. It does nothing more than print the word "hello" on the
screen.
Alternatively, the above program could be compiled using the following two commands.
g++ -c hello.C
g++ hello.o -o hello
The end result is the same, but this two-step method first compiles hello.C into a machine code
file named "hello.o" and then links hello.o with some system libraries to produce the final
program "hello". In fact the first method also does this two-stage process of compiling and
linking, but the stages are done transparently, and the intermediate file "hello.o" is deleted in the
process.
Specifying a different executable output filename
Ok, so a.out isn't the best name for an executable. And it's the name always used by the g++
compiler, unless you specify an alternative name. To specify an alternative output name, use the
o option of g++. For example:
g++ -o hello hello.cxx
Now, instead of getting a file called a.out, the compiler will create an executable called hello.
Unlike DOS and Windows, Linux executables do not have a specific extension like EXE or
COM. Instead, a file has it's 'execute' status set, which is done automatically by g++. If you get a
list of the files now, using the command ls l, you will see that hello is the only file that has an 'x'
in it's left most column, meaning it is an executable.

Example 2: Compiling a program with multiple source files


If the source code is in several files, say "file1.C" and "file2.C", then they can be compiled into
an executable program named "myprog" using the following command:
g++ file1.C file2.C -o myprog
The same result can be achieved using the following three commands:
g++ -c file1.C
g++ -c file2.C
g++ file1.o file2.o -o myprog
The advantage of the second method is that it compiles each of the source files separately. If, for
instance, the above commands were used to create "myprog", and "file1.C" was subsequently
modified, then the following commands would correctly update "myprog".
g++ -c file1.C
g++ file1.o file2.o -o myprog
Note that file2.C does not need to be recompiled, so the time required to rebuild myprog is
shorter than if the first method for compiling myprog were used. When there are numerous
source file, and a change is only made to one of them, the time savings can be significant. This
process, though somewhat complicated, is generally handled automatically by a makefile.
Reference:
http://www.cppreference.com/
http://en.wikipedia.org/wiki/C++_standard_library
http://www.cplusplus.com/
http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html

S-ar putea să vă placă și