| C++ User's Guide |
Using the C++ Compiler
This chapter describes how to use the C++ compiler.
The principal use of any compiler is to transform a program written in a high-level language like C++ into a data file that is executable by the target computer hardware. You can use the C++ compiler to:
- Transform source files into relocatable binary (
.o) files, to be linked later into an executable file, a static (archive) library (.a) file (using-xar), or a dynamic (shared) library (.so) file- Link or relink object files or library files (or both) into an executable file
- Compile an executable file with runtime debugging enabled (
-g)- Compile an executable file with runtime statement or procedure-level profiling (
-pg)2.1 Getting Started
This section gives you a brief overview of how to use the C++ compiler to compile and run C++ programs. See Chapter 3 for a full reference to command-line options.
Note The command-line examples in this chapter showCCusages. Printed output might be slightly different.
The basic steps for building and running a C++ program involve:
- Using an editor to create a C++ source file with one of the valid suffixes listed in TABLE 2-1
- Invoking the compiler to produce an executable file
- Launching the program into execution by typing the name of the executable file
The following program displays a message on the screen:
In this example,
CCcompiles the source filegreetings.ccand, by default, compiles the executable program onto the file,a.out. To launch the program, type the name of the executable file,a.out, at the command prompt.Traditionally, UNIX compilers name the executable file
a.out. It can be awkward to have each compilation write to the same file. Moreover, if such a file already exists, it will be overwritten the next time you run the compiler. Instead, use the-ocompiler option to specify the name of the executable output file, as in the following example:
example%CC -o greetings greetings.CIn this example, the
-ooption tells the compiler to write the executable code to the filegreetings. (It is common to give a program consisting of a single source file the name of the source file without the suffix.)Alternatively, you could rename the default
a.outfile using themvcommand after each compilation. Either way,run the program by typing the name of the executable file:
example%greetingsReal programmers write C++!example%2.2 Invoking the Compiler
The remainder of this chapter discuss the conventions used by the
CCcommand, compiler source line directives, and other issues concerning the use of the compiler.2.2.1 Command Syntax
The general syntax of a compiler command line is as follows:
CC[options] [source-files] [object-files] [libraries]An option is an option keyword prefixed by either a dash (
-) or a plus sign (+). Some options take arguments.In general, the processing of the compiler options is from left to right, allowing selective overriding of macro options (options that include other options). In most cases, if you specify the same option more than once, the rightmost assignment overrides and there is no accumulation. Note the following exceptions:
- All linker options and the
-I,-L,-pti, and-Roptions accumulate, they do not override.- All
-Uoptions are processed after all-Doptions.Source files, object files, and libraries are compiled and linked in the order in which they appear on the command line.
In the following example,
CCis used to compile two source files (growth.Candfft.C)to produce an executable file namedgrowthwith runtime debugging enabled:
example%CC -g -o growth growth.C fft.C2.2.2 File Name Conventions
The suffix attached to a file name appearing on the command line determines how the compiler processes the file. A file name with a suffix other than those listed in the following table, or without a suffix, is passed to the linker.
2.2.3 Using Multiple Source Files
The C++ compiler accepts multiple source files on the command line. A single source file compiled by the compiler, together with any files that it directly or indirectly supports, is referred to as a compilation unit. C++ treats each source as a separate compilation unit. A single source file can contain any number of procedures (main program, function, module, and so on). There are advantages to organizing an application with one procedure per file, as there are for gathering procedures that work together into a single file. Some of these are described in C++ Programming Guide.
2.2.4 Compiling With Different Compiler Versions
Beginning with the Sun WorkShop 6 C++ compiler, the compiler marks a template cache directory with a string that identifies the template cache's version.
This compiler checks the cache directory's version and issues error messages whenever it encounters cache version problems. Future Sun WorkShop C++ compilers will also check cache versions. For example, a future compiler that has a different template cache version identification and that processes a cache directory produced by this release of the compiler might issue the following error:
SunWS_cache: Error: Database version mismatch/SunWS_cache/CC_versionSimilarly, this release of the compiler will issue an error if it encounters a cache directory that was produced by a later version of the compiler.
Although the template cache directories produced by the Sun WorkShop C++ compiler 5.0 are not marked with version identifiers, the Sun WorkShop 6 C++ compiler processes the 5.0 cache directories without an error or a warning. The Sun WorkShop 6 C++ compiler converts the 5.0 cache directories to the directory format used by the Sun WorkShop 6 C++ compiler.
The Sun WorkShop C++ compiler 5.0 cannot use a cache directory that is produced by the Sun WorkShop 6 C++ compiler or by a later release. The Sun WorkShop C++ compiler 5.0 is not capable of recognizing format differences and it will issue an assertion when it encounters a cache directory that is produced by the Sun WorkShop 6 C++ compiler or by a later release.
When upgrading compilers, it is always good practice to run
CCadmin-cleanon every directory that contains a template cache directory (in most cases, a template cache directory is namedSunWS_cache). Alternately, you can userm-rf SunWS_cache.2.3 Compiling and Linking
This section describes some aspects of compiling and linking programs. In the following example,
CCis used to compile three source files and to link the object files to produce an executable file namedprgrm.
example%CC file1.cc file2.cc file3.cc -o prgrm2.3.1 Compile-Link Sequence
In the previous example, the compiler automatically generates the loader object files (
file1.o,file2.oandfile3.o) and then invokes the system linker to create the executable program for the fileprgrm.After compilation, the object files (
file1.o,file2.o,andfile3.o) remain. This convention permits you to easily relink and recompile your files.
Note If only one source file is compiled and a program is linked in the same operation, the corresponding.ofile is deleted automatically. To preserve all.ofiles, do not compile and link in the same operation unless more than one source file gets compiled.
If the compilation fails, you will receive a message for each error. No
.ofiles are generated for those source files with errors, and no executable program is written.2.3.2 Separate Compiling and Linking
You can compile and link in separate steps. The
-coption compiles source files and generates.oobject files, but does not create an executable. Without the-coption, the compiler invokes the linker. By splitting the compile and link steps, a complete recompilation is not needed just to fix one file. The following example shows how to compile one file and link with others in separate steps:
example%CC -c file1.ccMake new object fileexample%CC -o prgrm file1.o file2.o file3.oMake executable fileBe sure that the link step lists all the object files needed to make the complete program. If any object files are missing from this step, the link will fail with "undefined external reference" errors (missing routines).
2.3.3 Consistent Compiling and Linking
If you do compile and link in separate steps, consistent compiling and linking is critical when using the following compiler options:
-fast-g-g0-library-misalign-mt-p-xa-xarch=isa-xcg92and-xcg89-xpg-xprofile-xtarget=t-xvectoror-xvector=yesIf you compile any subprogram using any of these options, be sure to link using the same option as well:
- In the case of the
-library,-fast, and-xarchoptions, you must be sure to include the linker options that would have been passed if you had compiled and linked together.- With
-p,-xpgand-xprofile, including the option in one phase and excluding it from the other phase will not affect the correctness of the program, but you will not be able to do profiling.- With
-gand-g0, including the option in one phase and excluding it from the other phase will not affect the correctness of the program, but the program will not be prepared properly for debugging.In the following example, the programs are compiled using the
-xcg92compiler option. This option is a macro for-xtarget=ss1000and expands to:-xarch=v8 -xchip=super -xcache=16/64/4:1024/64/1.
example%CC -c -xcg92 sbr.ccexample%CC -c -xcg92 smain.ccexample%CC -xcg92 sbr.o smain.oIf the program uses templates, it is possible that some templates will get instantiated at link time. In that case the command line options from the last line (the link line) will be used to compile the instantiated templates.
2.3.4 Compiling for SPARC V9
The compilation, linking, and execution of 64-bit objects is supported only in a V9 SPARC, Solaris 7 or Solaris 8 environment with a 64-bit kernel running. Compilation for 64-bit is indicated by the
-xarch=v9,-xarch=v9a, and-xarch=v9boptions.2.3.5 Diagnosing the Compiler
You can use the
-verboseoption to display helpful information while compiling a program. See Chapter 3 for more information.Any arguments on the command line that the compiler does not recognize are interpreted as linker options, object program file names, or library names.
- Unrecognized options, which are preceded by a dash (
-) or a plus sign (+), generate warnings.- Unrecognized nonoptions, which are not preceded by a dash or a plus sign, generate no warnings. (However, they are passed to the linker. If the linker does not recognize them, they generate linker error messages.)
In the following example, note that
-bitis not recognized byCCand the option is passed on to the linker (ld), which tries to interpret it. Because single letterldoptions can be strung together, the linker sees-bitas-b -i -t, all of which are legitimateldoptions. This might not be what you intend or expect:
example%CC -bit move.cc<--bitis not a recognizedCCoptionCC: Warning: Option -bit passed to ld, if ld is invoked, ignored otherwiseIn the next example, the user intended to type the
CCoption-fastbut omitted the leading dash. The compiler again passes the argument to the linker, which in turn interprets it as a file name:
example%CC fast move.cc<- The user meant to type-fastmove.CC:ld: fatal: file fast: cannot open file; errno=2ld: fatal: File processing errors. No output written to a.out2.3.6 Understanding the Compiler Organization
The C++ compiler package consists of a front end, optimizer, code generator, assembler, template pre-linker, and link editor. The
CCcommand invokes each of these components automatically unless you use command-line options to specify otherwise. FIGURE 2-1 shows the order in which the components are invoked by the compiler.Because any of these components may generate an error, and the components perform different tasks, it may be helpful to identify the component that generates an error.
![]()
FIGURE 2-1 The Compilation ProcessAs shown in the following table, input files to the various compiler components have different file name suffixes. The suffix establishes the kind of compilation that is done. Refer to TABLE 2-1 for the meanings of the file suffixes.
2.4 Memory Requirements
The amount of memory a compilation requires depends on several parameters, including:
- Size of each procedure
- Level of optimization
- Limits set for virtual memory
- Size of the disk swap file
On the SPARC platform, if the optimizer runs out of memory, it tries to recover by retrying the current procedure at a lower level of optimization. The optimizer then resumes subsequent routines at the original level specified in the
-xOlevel option on the command line.If you compile a single source file that contains many routines, the compiler might run out of memory or swap space. If the compiler runs out of memory, try reducing the level of optimization. Alternately, split multiple-routine source files into files with one routine per file.
2.4.1 Swap Space Size
The
swap -scommand displays available swap space. See theswap(1M) man page for more information.The following example demonstrates the use of the
swapcommand:
example%swap -stotal: 40236k bytes allocated + 7280k reserved = 47516k used, 1058708k available2.4.2 Increasing Swap Space
Use
mkfile(1M) andswap(1M) to increase the size of the swap space on a workstation. (You must become superuser to do this.) Themkfilecommand creates a file of a specific size, andswap-aadds the file to the system swap space:
example#mkfile -v 90m /home/swapfile/home/swapfile 94317840 bytesexample#/usr/sbin/swap -a /home/swapfile2.4.3 Control of Virtual Memory
Compiling very large routines (thousands of lines of code in a single procedure) at
-xO3or higher can require an unreasonable amount of memory. In such cases, performance of the system might degrade. You can control this by limiting the amount of virtual memory available to a single process.To limit virtual memory in an
shshell, use theulimitcommand. See thesh(1) man page for more information.The following example shows how to limit virtual memory to 16 Mbytes:
example$ulimit -d 16000In a
cshshell, use thelimitcommand to limit virtual memory. See thecsh(1) man page for more information.The next example also shows how to limit virtual memory to 16 Mbytes:
example%limit datasize 16MEach of these examples causes the optimizer to try to recover at 16 Mbytes of data space.
The limit on virtual memory cannot be greater than the system's total available swap space and, in practice, must be small enough to permit normal use of the system while a large compilation is in progress.
Be sure that no compilation consumes more than half the swap space.
With 32 Mbytes of swap space, use the following commands:
In an
shshell:
example$ulimit -d 16000In a
cshshell:
example%limit datasize 16MThe best setting depends on the degree of optimization requested and the amount of real memory and virtual memory available.
2.4.4 Memory Requirements
A workstation should have at least 24 megabytes of memory; 32 Mbytes are recommended.
To determine the actual real memory, use the following command:
example%/usr/sbin/dmesg | grep memmem = 655360K (0x28000000)avail mem = 6024765442.5 Simplifying Commands
You can simplify complicated compiler commands by defining special shell aliases, using the
CCFLAGSenvironment variable, or by usingmake.2.5.1 Using Aliases Within the C Shell
The following example defines an alias for a command with frequently used options.
example%alias CCfx "CC -fast -xnolibmil"The next example uses the alias
CCfx.
example%CCfx any.CThe command
CCfxis now the same as:
example%CC -fast -xnolibmil any.C2.5.2 Using
CCFLAGSto Specify Compile OptionsYou can specify options by setting the
CCFLAGSvariable.The
CCFLAGSvariable can be used explicitly in the command line. The following example shows how to setCCFLAGS(C Shell):
example%setenv CCFLAGS '-xO2 -xsb'The next example uses
CCFLAGSexplicitly.
example%CC $CCFLAGS any.ccWhen you use
make, if theCCFLAGSvariable is set as in the preceding example and the makefile's compilation rules are implicit, then invokingmakewill result in a compilation equivalent to:2.5.3 Using
makeThe
makeutility is a very powerful program development tool that you can easily use with all Sun compilers. See themake(1S) man page for additional information.2.5.3.1 Using
CCFLAGSWithinmakeWhen you are using the implicit compilation rules of the makefile (that is, there is no C++ compile line), the
makeprogram usesCCFLAGSautomatically.2.5.3.2 Adding a Suffix to Your Makefile
You can incorporate different file suffixes into C++ by adding them to your makefile. The following example adds
.cppas a valid suffix for C++ files. Add theSUFFIXESmacro to your makefile:SUFFIXES: .cpp .cpp~(This line can be located anywhere in the makefile.)
Add the following lines to your makefile. Indented lines must start with a tab.
2.5.3.3 Using
makeWith Standard Library Header FilesThe standard library file names do not have
.hsuffixes. Instead, they are namedistream,fstream, and so forth. In addition, the template source files are namedistream.cc,fstream.cc, and so forth.If, in the Solaris 2.6 or 7 operating environment, you include a standard library header, such as
<istream>, in your program and your makefile has.KEEP_STATE, you may encounter problems. For example, if you include<istream>, themakeutility thinks thatistreamis an executable and uses the default rules to buildistreamfromistream.ccresulting in very misleading error messages. (Bothistreamand istream.ccare installed under the C++ include files directory). One solution is to usedmakein serial mode (dmake-mserial) instead of using themakeutility. An immediate work around is to usemakewith the-roption. The-roption disables the defaultmakerules. This solution may break the build process. A third solution is to not use the.KEEP_STATEtarget.
|
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |