C++ User'S Guide: Forte Developer 6 Update 2 (Sun Workshop 6 Update 2)
C++ User'S Guide: Forte Developer 6 Update 2 (Sun Workshop 6 Update 2)
This product or document is distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or
document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any. Third-party
software, including font technology, is copyrighted and licensed from Sun suppliers.
Parts of the product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a registered trademark in
the U.S. and other countries, exclusively licensed through X/Open Company, Ltd. For Netscape™, Netscape Navigator™, and the Netscape
Communications Corporation logo™, the following notice applies: Copyright 1995 Netscape Communications Corporation. All rights reserved.
Sun, Sun Microsystems, the Sun logo, docs.sun.com, AnswerBook2, Solaris, SunOS, JavaScript, SunExpress, Sun WorkShop, Sun WorkShop
Professional, Sun Performance Library, Sun Performance WorkShop, Sun Visual WorkShop, and Forte are trademarks, registered trademarks,
or service marks of Sun Microsystems, Inc. in the U.S. and other countries. All SPARC trademarks are used under license and are trademarks or
registered trademarks of SPARC International, Inc. in the U.S. and other countries. Products bearing SPARC trademarks are based upon an
architecture developed by Sun Microsystems, Inc.
The OPEN LOOK and Sun™ Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges
the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun
holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun’s licensees who implement OPEN
LOOK GUIs and otherwise comply with Sun’s written license agreements.
Federal Acquisitions: Commercial Software—Government Users Subject to Standard License Terms and Conditions.
DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-
INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.
Copyright 2001 Sun Microsystems, Inc., 901 San Antonio Road • Palo Alto, CA 94303-4900 Etats-Unis. Tous droits réservés.
Ce produit ou document est distribué avec des licences qui en restreignent l’utilisation, la copie, la distribution, et la décompilation. Aucune
partie de ce produit ou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et
écrite de Sun et de ses bailleurs de licence, s’il y en a. Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de
caractères, est protégé par un copyright et licencié par des fournisseurs de Sun.
Des parties de ce produit pourront être dérivées des systèmes Berkeley BSD licenciés par l’Université de Californie. UNIX est une marque
déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company, Ltd. La notice suivante est applicable à
Netscape™, Netscape Navigator™, et the Netscape Communications Corporation logo™: Copyright 1995 Netscape Communications
Corporation. Tous droits réservés.
Sun, Sun Microsystems, the Sun logo, docs.sun.com, AnswerBook2, Solaris, SunOS, JavaScript, SunExpress, Sun WorkShop, Sun WorkShop
Professional, Sun Performance Library, Sun Performance WorkShop, Sun Visual WorkShop, et Forte sont des marques de fabrique ou des
marques déposées, ou marques de service, de Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays. Toutes les marques SPARC sont
utilisées sous licence et sont des marques de fabrique ou des marques déposées de SPARC International, Inc. aux Etats-Unis et dans d’autres
pays. Les produits portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.
L’interface d’utilisation graphique OPEN LOOK et Sun™ a été développée par Sun Microsystems, Inc. pour ses utilisateurs et licenciés. Sun
reconnaît les efforts de pionniers de Xerox pour la recherche et le développement du concept des interfaces d’utilisation visuelle ou graphique
pour l’industrie de l’informatique. Sun détient une licence non exclusive de Xerox sur l’interface d’utilisation graphique Xerox, cette licence
couvrant également les licenciés de Sun qui mettent en place l’interface d’utilisation graphique OPEN LOOK et qui en outre se conforment aux
licences écrites de Sun.
Sun f90/f95 est derivé de CRAY CF90™, un produit de Cray Inc.
CETTE PUBLICATION EST FOURNIE “EN L’ETAT” ET AUCUNE GARANTIE, EXPRESSE OU IMPLICITE, N’EST ACCORDEE, Y COMPRIS
DES GARANTIES CONCERNANT LA VALEUR MARCHANDE, L’APTITUDE DE LA PUBLICATION A REPONDRE A UNE UTILISATION
PARTICULIERE, OU LE FAIT QU’ELLE NE SOIT PAS CONTREFAISANTE DE PRODUIT DE TIERS. CE DENI DE GARANTIE NE
S’APPLIQUERAIT PAS, DANS LA MESURE OU IL SERAIT TENU JURIDIQUEMENT NUL ET NON AVENU.
Please
Recycle
Important Note on New Product
Names
As part of Sun’s new developer product strategy, we have changed the names of our
development tools from Sun WorkShop™ to Forte™ Developer products. The
products, as you can see, are the same high-quality products you have come to
expect from Sun; the only thing that has changed is the name.
We believe that the Forte™ name blends the traditional quality and focus of Sun’s
core programming tools with the multi-platform, business application deployment
focus of the Forte tools, such as Forte Fusion™ and Forte™ for Java™. The new
Forte organization delivers a complete array of tools for end-to-end application
development and deployment.
For users of the Sun WorkShop tools, the following is a simple mapping of the old
product names in WorkShop 5.0 to the new names in Forte Developer 6.
In addition to the name changes, there have been major changes to two of the
products.
■ Forte for High Performance Computing contains all the tools formerly found in
Sun Performance WorkShop Fortran and now includes the C++ compiler, so High
Performance Computing users need to purchase only one product for all their
development needs.
■ Forte Fortran Desktop Edition is identical to the former Sun Performance
WorkShop Personal Edition, except that the Fortran compilers in that product no
longer support the creation of automatically parallelized or explicit, directive-
based parallel code. This capability is still supported in the Fortran compilers in
Forte for High Performance Computing.
We appreciate your continued use of our development products and hope that we
can continue to fulfill your needs into the future.
Contents
Contents v
1.6 C++ Utilities 1-5
1.7 Native-Language Support 1-5
Contents vii
5. Program Organization 5-1
5.1 Header Files 5-1
5.1.1 Language-Adaptable Header Files 5-1
5.1.2 Idempotent Header Files 5-3
5.2 Template Definitions 5-3
5.2.1 Template Definitions Included 5-3
5.2.2 Template Definitions Separate 5-4
Contents ix
7.8.3 Source File Extensions 7-9
7.8.4 Definition Source Locations 7-9
7.8.5 Template Specialization Entries 7-12
Contents xi
12.7 Replacing the C++ Standard Library 12-13
12.7.1 What Can Be Replaced 12-13
12.7.2 What Cannot Be Replaced 12-13
12.7.3 Installing the Replacement Library 12-14
12.7.4 Using the Replacement Library 12-14
12.7.5 Standard Header Implementation 12-15
Contents xiii
16.7 Building a Library That Has a C API 16-5
16.8 Using dlopen to Access a C++ Library From a C Program 16-6
Part IV Appendixes
Contents xv
A.2.54 –nolibmil A-48
A.2.55 –noqueue A-48
A.2.56 –norunpath A-48
A.2.57 –O A-49
A.2.58 –Olevel A-49
A.2.59 –o filename A-49
A.2.60 +p A-50
A.2.61 –P A-50
A.2.62 –p A-51
A.2.63 –pentium A-51
A.2.64 –pg A-51
A.2.65 -PIC A-51
A.2.66 –pic A-52
A.2.67 –pta A-52
A.2.68 –ptipath A-52
A.2.69 –pto A-52
A.2.70 –ptr A-52
A.2.71 –ptv A-53
A.2.72 –Qoption phase option[,option...] A-53
A.2.73 –qoption phase option A-54
A.2.74 –qp A-54
A.2.75 –Qproduce sourcetype A-55
A.2.76 –qproduce sourcetype A-55
A.2.77 –Rpathname[:pathname...] A-55
A.2.78 –readme A-56
A.2.79 –S A-56
A.2.80 –s A-56
A.2.81 –sb A-56
A.2.82 –sbfast A-56
A.2.83 -staticlib=l[,l...] A-57
Contents xvii
A.2.114 -xlang=language[,language] A-83
A.2.115 –xlibmieee A-84
A.2.116 –xlibmil A-84
A.2.117 –xlibmopt A-85
A.2.118 –xlic_lib=sunperf A-85
A.2.119 –xlicinfo A-86
A.2.120 –Xm A-86
A.2.121 –xM A-86
A.2.122 -xM1 A-87
A.2.123 –xMerge A-87
A.2.124 –xnolib A-87
A.2.125 –xnolibmil A-90
A.2.126 –xnolibmopt A-90
A.2.127 -xOlevel A-90
A.2.128 –xpg A-93
A.2.129 -xprefetch[=a[,a]] A-94
A.2.130 -xprofile=p A-96
A.2.131 –xregs=r[,r...] A-99
A.2.132 –xs A-100
A.2.133 –xsafe=mem A-100
A.2.134 –xsb A-101
A.2.135 –xsbfast A-101
A.2.136 –xspace A-102
A.2.137 –xtarget=t A-102
A.2.138 –xtime A-108
A.2.139 –xunroll=n A-108
A.2.140 -xtrigraphs[={yes|no}] A-109
A.2.141 –xwe A-110
A.2.142 -z[ ]arg A-110
Glossary Glossary-1
Index Index-1
Contents xix
xx C++ User’s Guide • July 2001
Tables
TABLE 2-1 File Name Suffixes Recognized by the C++ Compiler 2-4
xxi
TABLE 11-1 iostream Original Core Classes 11-7
TABLE 15-3 Complex Arithmetic Library Functions Default Error Handling 15-7
TABLE A-5 -features Options for Compatibility Mode and Standard Mode A-16
Tables xxiii
xxiv C++ User’s Guide • July 2001
Code Samples
CODE EXAMPLE 6-1 Example of Local Type as Template Argument Problem 6-13
CODE EXAMPLE 7-2 Definition of Static Data Members and Use of Simple Names 7-10
CODE EXAMPLE 7-4 Definition of Template Functions in Different Source Files 7-11
CODE EXAMPLE 7-7 Example of When special Entry Should Be Used 7-12
xxv
CODE EXAMPLE 11-8 New Class Hierarchy 11-14
CODE EXAMPLE 11-11 Making I/O Operation and Error Checking Atomic 11-19
This manual instructs you in the use of the Sun WorkShop™ 6 C++ compiler, and
provides detailed information on command-line compiler options. This manual is
intended for programmers with a working knowledge of C++ and some
understanding of the Solaris™ operating environment and UNIX® commands.
Sun WorkShop C++ Compiler. Chapter 1 provides introductory material about the
compiler, such as standards conformance and new features.Chapter 2 explains how
to use the compiler and Chapter 3 discusses how to use the compiler’s command
line options.
Writing C++ Programs. Chapter 4 discusses how to compile nonstandard code that
is commonly accepted by other C++ compilers. Chapter 5 makes suggestions for
setting up and organizing header files and template definitions. Chapter 6 discusses
how to create and use templates and Chapter 7 explains various options for
compiling templates. Exception handling is discussed in Chapter 8 and information
about cast operations is provided in Chapter 9. Chapter 10 discusses performance
techniques that strongly affect the Sun WorkShop C++ compiler. Chapter 11 provides
information about building multithreaded programs.
Libraries. Chapter 12 explains how to use the libraries that are provided with the
compiler. The C++ standard library is discussed in Chapter 13, the classic iostream
library (for compatibility mode) is discussed in Chapter 14, and the complex
arithmetic library (for compatibility mode) is discussed in Chapter 15. Chapter 16
provides information about building libraries.
xxvii
Compiler Options. Appendix A provides in-depth information about the compiler
options.
Glossary. The Glossary defines C++ and related terms that are used in this book.
Typographic Conventions
Typeface Meaning Examples
C shell %
Bourne shell and Korn shell $
C shell, Bourne shell, and Korn shell superuser #
Supported Platforms
This Sun WorkShop™ release supports versions 2.6, 7, and 8 of the Solaris™ SPARC™
Platform Edition and Solaris™ Intel Platform Edition operating environments.
For more information about the PATH variable, see the csh(1), sh(1), and ksh(1)
man pages. For more information about the MANPATH variable, see the man(1) man
page. For more information about setting your PATH and MANPATH variables to
access this release, see the Sun WorkShop 6 update 2 Installation Guide or your system
administrator.
% echo $PATH
% man workshop
http://www.fatbrain.com/documentation/sun
Title Description
c++filt Copies each file name in sequence and writes it in the standard
output after decoding symbols that look like C++ demangled
names
dem Demangles one or more C++ names that you specify
fbe Creates object files from assembly language source files
fpversion Prints information about the system CPU and FPU
gprof Produces execution profile of a program
ild Links incrementally, allowing insertion of modified object code into
a previously built executable
inline Expands assembler inline procedure calls
lex Generates lexical analysis programs
rpcgen Generates C/C++ code to implement an RPC protocol
sigfpe Allows signal handling for specific SIGFPE codes
stdarg Handles variable argument list
varargs Handles variable argument list
version Displays version identification of object file or binary
yacc Converts a context-free grammar into a set of tables for a simple
automaton that executes an LALR(1) parsing algorithm
Standard C++ IOStreams and Locales, Angelika Langer and Klaus Kreft (Addison-
Wesley, 2000).
Thinking in C++, Volume 1, Second Edition, Bruce Eckel (Prentice Hall, 2000).
The Annotated C++ Reference Manual, Margaret A. Ellis and Bjarne Stroustrup,
(Addison-Wesley, 1990).
C++ Primer, Third Edition, Stanley B. Lippman and Josee Lajoie (Addison-Wesley,
1998).
Effective C++—50 Ways to Improve Your Programs and Designs, Second Edition, Scott
Meyers (Addison-Wesley, 1998).
More Effective C++—35 Ways to Improve Your Programs and Designs, Scott Meyers
(Addison-Wesley, 1996).
Efficient C++: Performance Programming Techniques, Dov Bulka and David Mayhew
(Addison-Wesley, 2000).
docfeedback@sun.com
This chapter provides a brief conceptual overview of the Sun WorkShop™ C++
compiler.
The responsible standards bodies may revise these standards from time to time. The
versions of the applicable standards to which the C++ compiler conforms may be
revised or replaced, resulting in features in future releases of the Sun C++ compiler
that create incompatibilities with earlier releases.
1-1
1.2 C++ Readme File
The C++ compiler’s readme file highlights important information about the
compiler, including:
■ New and changed features
■ Software incompatibilities
■ Current software bugs
■ Information discovered after the manuals were printed
To view the text version of the C++ readme file, type the following at a command
prompt:
example% CC -xhelp=readme
To access the HTML version of the readme, in your Netscape Communicator 4.0 or
compatible version browser, open the following file:
/opt/SUNWspro/docs/index.html
(If your Sun WorkShop software is not installed in the /opt directory, ask your
system administrator for the equivalent path on your system.) Your browser
displays an index of Sun WorkShop 6 HTML documents. To open the readme, find
its entry in the index, then click the title.
1.4 Licensing
The C++ compiler uses network licensing, as described in the Sun WorkShop
Installation and Licensing Guide.
If you invoke the compiler, and a license is available, the compiler starts. If no
license is available, your request for a license is put in a queue, and your compiler
continues when a license becomes available. A single license can be used for any
number of simultaneous compiles by a single user on a single machine.
To run C++ and the various utilities, several licenses might be required, depending
on the package you have purchased.
The following features were introduced with Sun WorkShop 6 update 1 C++
compiler:
■ Interval arithmetic support for C++
■ Mixed-language linking
The following features were introduced in version 5.0 of the C++ compiler:
■ Implementation of the following C++ ISO standards:
■ Namespaces and Koenig lookup
■ Type bool
■ Array new and array delete
■ Extended support for templates
■ The C++ standard library
■ Covariant return types on virtual functions
■ Compatibility with C++ 4.0, 4.01, 4.1, and 4.2
■ Sun WorkShop Memory Monitor for garbage collection and identifying memory
leaks
■ SPARC V9 support on Solaris 7 and Solaris 8 operating environments
■ Binary and source compatibility features to aid a smooth transition to ISO C++
■ Multithread-safe C++ standard library
See Analyzing Program Performance With Sun WorkShop and associated man pages for
further information on these UNIX tools.
Variable names cannot be internationalized and must be in the English character set.
You can change your application from one native language to another by setting the
locale. For information on this and other native-language support features, see the
operating environment documentation.
Note – The command-line examples in this chapter show CC usages. Printed output
might be slightly different.
2-1
The basic steps for building and running a C++ program involve:
1. Using an editor to create a C++ source file with one of the valid suffixes listed in
TABLE 2-1 on page 2-4
3. Launching the program into execution by typing the name of the executable file
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 -o
compiler option to specify the name of the executable output file, as in the following
example:
In this example, the -o option tells the compiler to write the executable code to the
file greetings. (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.out file using the mv command after
each compilation. Either way, run the program by typing the name of the
executable file:
example% greetings
Real programmers write C++!
example%
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 -features, –I -l, –L, -library, –pti, –R,
-staticlib, -U, -verbose, and -xprefetch options accumulate, they do not
override.
■ All –U options are processed after all –D options.
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, CC is used to compile two source files (growth.C and
fft.C) to produce an executable file named growth with runtime debugging
enabled:
This compiler checks the cache directory’s version and issues error messages
whenever it encounters cache version problems. Future 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 an error that is similar to the following message:
Similarly, 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 C++ 5.0 compiler are not
marked with version identifiers, the C++ 5.3 compiler processes the 5.0 cache
directories without an error or a warning. The compiler converts the 5.0 cache
directories to the directory format that it uses.
The C++ 5.0 compiler cannot use a cache directory that is produced by the Sun C++
5.1 compiler or by a later release. The C++ 5.0 compiler is not capable of recognizing
format differences and it will issue an assertion when it encounters a cache directory
that is produced by the C++ 5.1 compiler or by a later release.
After compilation, the object files (file1.o, file2.o,and file3.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 .o file is deleted automatically. To preserve all .o files,
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 .o files are
generated for those source files with errors, and no executable program is written.
If 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, -xtarget, and -xarch options, you must
be sure to include the linker options that would have been passed if you had
compiled and linked together.
■ With -p, -xpg, and -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 -g and -g0, including the option in one phase and excluding it from the
other phase will not affect the correctness of the program, but it will affect the
ability to debug the program. Any module that is not compiled with either of
these options, but is linked with -g or -g0 will not be prepared properly for
debugging. Note that compiling the module that contains the function main with
the -g option or the -g0 option is usually necessary for debugging.
If 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.
Any arguments on the command line that the compiler does not recognize are
interpreted as linker options, object program file names, or library names.
In the next example, the user intended to type the CC option -fast but omitted the
leading dash. The compiler again passes the argument to the linker, which in turn
interprets it as a file name:
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.
Assembler
(fbe) (.o files)
Template
pre-linker
(CClink)
Object files and
libraries,
Link editor archive (.a) and
(ld) or (ild) shared (.so) libraries
Note – In this document, the term “IA” refers to the Intel 32-bit processor
architecture, which includes the Pentium, Pentium Pro, and Pentium II, Pentium II
Xeon, Celeron, Pentium III, and Pentium III Xeon processors and compatible
microprocessor chips made by AMD and Cyrix.
If the identifier_list in the macro definition ends with an ellipses, it means that there
will be more arguments in the invocation than there are parameters in the macro
definition, excluding the ellipsis. Use the identifier __VA_ARGS__ in the replacement
list of a #define preprocessing directive which uses the ellipsis notation inits
arguments. For more information, see the C User’s Guide.
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.
example% swap -s
total: 40236k bytes allocated + 7280k reserved = 47516k used,
1058708k available
To limit virtual memory in an sh shell, use the ulimit command. See the sh(1)
man page for more information.
In a csh shell, use the limit command to limit virtual memory. See the csh(1) man
page for more information.
The next example also shows how to limit virtual memory to 16 Mbytes:
Each 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.
In an sh shell:
In a csh shell:
The best setting depends on the degree of optimization requested and the amount of
real memory and virtual memory available.
The CCFLAGS variable can be used explicitly in the command line. The following
example shows how to set CCFLAGS (C Shell):
When you use make, if the CCFLAGS variable is set as in the preceding example and
the makefile’s compilation rules are implicit, then invoking make will result in a
compilation equivalent to:
.cpp:
$(LINK.cc) -o $@ $< $(LDLIBS)
.cpp~:
$(GET) $(GFLAGS) -p $< > $*.cpp
$(LINK.cc) -o $@ $*.cpp $(LDLIBS)
.cpp.o:
$(COMPILE.cc) $(OUTPUT_OPTION) $<
.cpp~.o:
$(GET) $(GFLAGS) -p $< > $*.cpp
$(COMPILE.cc) $(OUTPUT_OPTION) $<
.cpp.a:
$(COMPILE.cc) -o $% $<
$(COMPILE.cc) -xar $@ $%
$(RM) $%
.cpp~.a:
$(GET) $(GFLAGS) -p $< > $*.cpp
$(COMPILE.cc) -o $% $<
$(COMPILE.cc) -xar $@ $%
$(RM) $%
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>, the make
utility thinks that istream is an executable and uses the default rules to build
istream from istream.cc resulting in very misleading error messages. (Both
istream and istream.cc are installed under the C++ include files directory). One
solution is to use dmake in serial mode (dmake -m serial) instead of using the
make utility. An immediate work around is to use make with the -r option. The -r
option disables the default make rules. This solution may break the build process. A
third solution is to not use the .KEEP_STATE target.
This chapter explains how to use the command-line C++ compiler options and then
summarizes their use by function. Detailed explanations of the options are provided
in Appendix A.
3.1 Syntax
The following table shows examples of typical option syntax formats that are used in
this book.
-option –E
–optionvalue –Ipathname
–option=value –xunroll=4
–option value –o filename
Parentheses, braces, brackets, pipe characters, and ellipses are metacharacters used in
the descriptions of the options and are not part of the options themselves. See the
typographical conventions in “Before You Begin” at the front of this manual for a
detailed explanation of the usage syntax.
3-1
3.2 General Guidelines
Some general guidelines for the C++ compiler options are:
■ The –llib option links with library liblib.a (or liblib.so). It is always safer to
put –llib after the source and object files to ensure the order in which libraries are
searched.
■ In general, processing of the compiler options is from left to right (with the
exception that –U options are processed after all –D options), allowing selective
overriding of macro options (options that include other options). This rule does
not apply to linker options.
■ The -features, –I -l, –L, -library, –pti, –R, -staticlib, -U, -verbose,
and -xprefetch options accumulate, they do not override.
■ The -D option accumulates, However, multiple -D options for the same name
override each other.
Source files, object files, and libraries are compiled and linked in the order in which
they appear on the command line.
The options apply to all platforms except as noted; features that are unique to the
Solaris SPARC Platform Edition operating environment are identified as SPARC, and
the features that are unique to the Solaris Intel Platform Edition operating
environment are identified as IA.
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
Option Action
–p Prepares the object code to collect data for profiling using prof.
–xa Generates code for profiling.
–xpg Compiles for profiling with the gprof profiler.
–xprofile=tcov Collects or optimizes using runtime profiling data.
Option Action
Option Action
Option Action
Option Action
Language Extensions
This chapter describes the language extensions that the compiler supports when you
use the -features=extensions options.
Note – You can easily turn each supported instance of invalid code into valid code
that all compilers will accept. If you are allowed to make the code valid, you should
do so instead of using this option. Using the -features=extensions option
perpetuates invalid code that will be rejected by some compilers.
Suppose, for example, that you call a function through a pointer to a base class. If
the function has an exception specification, you can count on no other exceptions
being thrown. If the overriding function has a less-restrictive specification, an
unexpected exception could be thrown, which can result in bizarre program
behavior followed by a program abort. This is the reason for the rule.
4-1
When you use -features=extensions, the compiler will allow overriding
functions with less-restrictive exception specifications.
The following two lines show an example of invalid code that will compile when
you use the -features=extensions option.
Because enum definitions cannot reference one another, and no enum definition can
cross-reference another type, the forward declaration of an enumeration type is
never necessary. To make the code valid, you can always provide the full definition
of the enum before it is used.
As noted previously, you can always include the definition of an enum type before it
is used.
Note – Use of this option increases the possibility of typographical errors yielding
incorrect programs that compile without error messages.
union U {
struct {
int a;
double b;
}; // invalid: anonymous struct
struct {
char* c;
unsigned d;
}; // invalid: anonymous struct
};
The names of the struct members are visible without qualification by a struct
member name. Given the definition of U in this code example, you can write:
U u;
u.a = 1;
union U {
struct {
int a;
double b;
} A;
struct {
char* c;
unsigned d;
} B;
};
U u;
U.A.a = 1;
class C {
public:
C(int);
...
};
void f1(C*);
int main()
{
f1( &C(2) ); // invalid
}
Note that you can make this code valid by using an explicit variable.
C c(2);
f1(&c);
class A {
friend static void foo(<args>);
...
};
Because a class name has external linkage and all definitions must be identical,
friend functions must also have external linkage. However, when you use the
-features=extensions option, the compiler to accepts this code.
Presumably the programmer’s intent with this invalid code was to provide a
nonmember “helper” function in the implementation file for class A. You can get the
same effect by making foo a static member function. You can make it private if you
do not want clients to call the function.
Note – If you use this extension, your class can be “hijacked” by any client. Any
client can include the class header, then define its own static function foo, which
will automatically be a friend of the class. The effect will be as if you made all
members of the class public.
#include <stdio.h>
void myfunc(void)
{
printf("%s\n", __func__);
}
Each time the function is called, it will print the following to the standard output
stream.
myfunc
Program Organization
The file organization of a C++ program requires more care than is typical for a C
program. This chapter describes how to set up your header files and your template
definitions.
5-1
The macro __STDC__ is not defined in K&R C, but is defined in both ANSI C and
C++. Use this macro to separate K&R C code from ANSI C or C++ code. This macro
is most useful for separating prototyped from nonprototyped function definitions.
#ifdef __STDC__
int function(char*,...); // C++ & ANSI C declaration
#else
int function(); // K&R C
#endif
Use the definition of the __cplusplus macro to separate C and C++. This macro is
most useful in guarding the specification of an extern “C” interface for function
declarations, as shown in the following example. To prevent inconsistent
specification of extern “C”, never place an #include directive within the scope of
an extern “C” linkage specification.
#include “header.h”
... // ... other include files ...
#if defined(__cplusplus)
extern “C” {
#endif
int g1();
int g2();
int g3()
#if defined(__cplusplus)
}
#endif
In ARM C++, the __cplusplus macro has a value of 1. In ISO C++, the macro has
the value 199711L (the year and month of the standard expressed as a long
constant). Use the value of this macro to separate ARM C++ from ISO C++. The
macro value is most useful for guarding changes in template syntax.
#ifndef HEADER_H
#define HEADER_H
/* contents of header file */
#endif
Template definition files must not include any non-idempotent header files and often
need not include any header files at all. (See Section 5.1.2 “Idempotent Header Files”
on page 5-3.) Note that not all compilers support the definitions-separate model for
templates.
If you place template declarations in one file and template definitions in another file,
you have to be very careful how you construct the definition file, what you name it,
and where you put it. You might also need to identify explicitly to the compiler the
location of the definitions. Refer to Section 7.5 “Template Definition Searching” for
information about the template definition search rules.
Templates make it possible for you to write a single body of code that applies to a
wide range of types in a type-safe manner. This chapter introduces template
concepts and terminology in the context of function templates, discusses the more
complicated (and more powerful) class templates, and describes the composition of
templates. Also discussed are template instantiation, default template parameters,
and template specialization. The chapter concludes with a discussion of potential
problem areas for templates.
In this example, Number is a template parameter; it specifies the range of functions that
the template describes. More specifically, Number is a template type parameter, and its
use within the template definition stands for a type determined at the location where
the template is used.
6-1
6.1.2 Function Template Definition
If you declare a template, you must also define it. A definition provides enough
information to implement the template. The following example defines the template
declared in the previous example.
Sun WorkShop 6 update 2 C++ does not support expressions involving non-type
template parameters in the function parameter list, as shown in the following
example.
If a template argument cannot be inferred from the function argument types, it must
be supplied where the function is called. For example:
The following example is a template declaration for a class named Array that takes
any type as an argument.
This template is for a class named String that takes an unsigned int as an
argument.
Unlike function templates, class templates can have both type parameters (such as
class Elem) and expression parameters (such as unsigned Size). An expression
parameter can be:
■ A value that has an integral type or enumeration
■ A pointer or a reference to an object
■ A pointer or a reference to a function
■ A pointer to a class member function
#include <string.h>
template <unsigned Size> int String<Size>::length( )
{ int len = 0;
while ( len < Size && data[len] != '\0' ) len++;
return len; }
The declaration in this example creates the short_string variable using the
String template.
int x = int_array.GetSize( );
int x = short_string.length( );
Template arguments may be omitted when the compiler can infer them.
When you explicitly instantiate a class, all of its members are also instantiated.
If a template parameter has a default value, all parameters after it must also have
default values. A template parameter can have only one default value.
You can omit the template arguments if the compiler can unambiguously determine
them. For example:
#include <string.h>
template <> void sort<char*>( Array<char*> store )
{ int num_elems = store.GetSize( );
for ( int i = 0; i < num_elems-1; i++ )
for ( int j = i+1; j < num_elems; j++ )
if ( strcmp( store[j-1], store[j] ) > 0 )
{ char *temp = store[j];
store[j] = store[j-1];
store[j-1] = temp; } }
■ Example 1 provides a special template definition for cases when the first template
parameter is type int.
■ Example 2 provides a special template definition for cases when the first template
parameter is any pointer type.
■ Example 3 provides a special template definition for cases when the first template
parameter is pointer-to-pointer of any type, and the second template parameter is
type char.
#include "use_common.h"
#include "use_common.h"
A common use of nonlocal names is the use of the cin and cout streams within a
template. Few programmers really want to pass the stream as a template parameter,
so they refer to a global variable. However, cin and cout must have the same
definition everywhere.
The Foo type as registered in file1.cc is not the same as the Foo type registered
in file2.cc. Using local types in this way could lead to errors and unexpected
results.
template<class T>
std::ostream&
operator<<(std::ostream& out, const array<T>& rhs)
{ return out << ’[’ << rhs.size << ’]’; }
int main()
{
std::cout
<< "creating an array of int... " << std::flush;
array<int> foo;
std::cout << "done\n";
std::cout << foo << std::endl;
return 0;
}
#ifndef ARRAY_H
#define ARRAY_H
#include <iosfwd>
struct simple {
typedef int a_type;
static int a_datum;
};
int simple::a_datum = 0; // not a type
template <class T> struct parametric {
typedef T a_type;
static T a_datum;
};
template <class T> T parametric<T>::a_datum = 0; // not a type
template <class T> struct example {
static typename T::a_type variable1; // dependent
static typename parametric<T>::a_type variable2; // dependent
static simple::a_type variable3; // not dependent
};
template <class T> typename T::a_type // dependent
example<T>::variable1 = 0; // not a type
template <class T> typename parametric<T>::a_type // dependent
example<T>::variable2 = 0; // not a type
template <class T> simple::a_type // not dependent
example<T>::variable3 = 0; // not a type
// ill-formed statement
Array<String<10>> short_string_array(100); // >> = right-shift
If you want a single object to be shared by all template instantiations, then make the
object a nonstatic member of a named namespace. If you want a different object for
each instantiation of a template class, then make the object a static member of the
template class. If you want a different object for each instantiation of a template
function, then make the object local to the function.
Compiling Templates
Template compilation requires the C++ compiler to do more than traditional UNIX
compilers have done. The C++ compiler must generate object code for template
instances on an as-needed basis. It might share template instances among separate
compilations using a template repository. It might accept some template compilation
options. It must locate template definitions in separate source files and maintain
consistency between template instances and mainline code.
7-1
7.3 Template Instance Placement and
Linkage
You can instruct the compiler to use one of five instance placement and linkage
methods: external, static, global, explicit, and semi-explicit.
■ External instances are suitable for all development and provide the best overall
template compilation. You should use the external instances method, which is the
default, unless there is a very good reason to do otherwise.
■ Static instances are suitable for very small programs or debugging and have
restricted uses.
■ Global instances are suitable for some library construction.
■ Explicit instances are suitable for some carefully controlled application
compilation environments.
■ Semi-explicit instances require slightly less controlled compilation environments
but produce larger object files and have restricted uses.
This section discusses the five instance placement and linkage methods. Additional
information about generating instances can be found in the Section 6.3 “Template
Instantiation.”
Template instances receive global linkage in the repository. Instances are referenced
from the current compilation unit with external linkage.
Specify external linkage with the —instances=extern option (the default option).
Because instances are stored within the template repository, you must use the CC
command to link C++ objects that use external instances into programs.
If you wish to create a library that contains all template instances that it uses, use the
CC command with the —xar option. Do not use the ar command. For example:
Instances receive static linkage. These instances will not be visible or usable outside
the current compilation unit. As a result, templates might have identical
instantiations in several object files. Because multiple instances produce
unnecessarily large programs, static instance linkage is suitable only for small
programs, where templates are unlikely to be multiply instantiated.
Compilation is potentially faster with static instances, so this method might also be
suitable during Fix-and-Continue debugging. (See Debugging a Program With dbx.)
Note – If your program depends on sharing template instances (such as static data
members of template classes or template functions) across compilation units, do not
use the static instances method. Your program will not work properly.
Template instances receive global linkage. These instances are visible and usable
outside the current compilation unit. As a consequence, instantiation in more than
one compilation unit results in multiple symbol definition errors during linking. The
global instances method is therefore suitable only when you know that instances
will not be repeated.
Template instances receive global linkage. These instances are visible and usable
outside the current compilation unit. Multiple explicit instantiations within a
program result in multiple symbol definition errors during linking. The explicit
instances method is therefore suitable only when you know that instances are not
repeated, such as when you construct libraries with explicit instantiation.
Explicit instances receive global linkage. These instances are visible and usable
outside the current compilation unit. Multiple explicit instantiations within a
program result in multiple symbol definition errors during linking.The semi-explicit
instances method is therefore suitable only when you know that explicit instances
will not be repeated, such as when you construct libraries with explicit instantiation.
Implicit instances used from within the bodies of explicit instances receive static
linkage. These instances are not visible outside the current compilation unit. As a
result, templates can have identical instantiations in several object files. Because
multiple instances produce unnecessarily large programs, semi-explicit instance
linkage is suitable only for programs where template bodies do not cause multiple
instantiations.
Note – If your program depends on sharing template instances (such as static data
members of template classes or template functions) across compilation units, do not
use the semi-explicit instances method. Your program will not work properly.
The simplest, though most conservative, way to ensure the rule is not violated is to
build only one program or library within any one directory. Two unrelated programs
might use the same type name or external name to mean different things. If the
programs share a template repository, template definitions could conflict, thus
yielding unpredictable results.
Definition searching is somewhat complex and prone to error. Therefore, you should
use the definitions-included template file organization if possible. Doing so helps
you avoid definition searching altogether. See Section 5.2.1 “Template Definitions
Included.”
Note – If you use the -template=no%extdef option, the compiler will not search
for separate source files.
For example, if your source files are compiled with the –g option (debugging on),
the files you need from the database are also compiled with –g.
Note – The template options file may not be supported in future releases of the C++
compiler.
The options file is named CC_tmpl_opt and resides within the SunWS_config
directory. This directory name may be changed using the SUNWS_CONFIG_NAME
environment variable. Note that the value of the SUNWS_CONFIG_NAME variable
must be a directory name and not a path name.
The options file is an ASCII text file containing a number of entries. An entry
consists of a keyword followed by expected text and terminated with a semicolon (;).
Entries can span multiple lines, although the keywords cannot be split.
7.8.1 Comments
Comments start with a # character and extend to the end of the line. Text within a
comment is ignored.
7.8.2 Includes
You may share options files among several template databases by including the
options files. This facility is particularly useful when building libraries containing
templates. During processing, the specified options file is textually included in the
current options file. You can have more than one include statement and place them
anywhere in the options file. The options files can also be nested.
include "options-file";
extensions "ext-list";
The ext-list is a list of extensions for valid source files in a space-separated format
such as:
In the absence of this entry from the options file, the valid extensions for which the
compiler searches are .cc, .c, .cpp, .C, .cxx, and .c++.
The name field indicates the template for which the option entry is valid. Only one
definition entry per name is allowed. That name must be a simple name; qualified
names are not allowed. Parentheses, return types, and parameter lists are not
allowed. Regardless of the return type or parameters, only the name itself counts. As
a consequence, a definition entry may apply to several (possibly overloaded)
templates.
The "file-n" list field specifies the files that contain the template definitions. The
search for the files uses the definition search path. The file names must be enclosed in
quotes (" "). Multiple files are available because the simple template name may refer
to different templates defined in different files, or because a single template may
have definitions in multiple files. For example, if func is defined in three files, then
those three files must be listed in the definition entry.
The following example shows the definition of static data members and the use of
simple names.
CODE EXAMPLE 7-2 Definition of Static Data Members and Use of Simple Names
The name provided for the definition of fooref is a simple name and not a
qualified name (such as foo::fooref). The reason for the definition entry is that
the file name is not foo.cc (or some other recognizable extension) and cannot be
located using the default Cfront-style search rules.
The following example shows the definition of a template member function. As the
example shows, member functions are handled exactly like static member
initializers.
In this example, the compiler must be able to find both of the definitions of the
overloaded function func(). The definition entry tells the compiler where to find
the appropriate function definitions.
In the following example, the compiler locates the template function foo in foo.cc,
and instantiates it. If a reinstantiation check is later required, the compiler will
ignore the -g option.
The special entry tells the compiler that a given function is a specialization and
should not be instantiated when the compiler encounters the function. When using
the compile-time instantiation method, use special entries in the options file to
preregister the specializations. The syntax is:
special declaration;
The declaration is a legal C++-style declaration without return types. For example:
The preceding options file informs the compiler that the template function foo()
should not be instantiated for the type int, and that a specialized version is
provided by the user. Without that entry in the options file, the function may be
instantiated unnecessarily, resulting in errors:
To specialize a template class, include the template arguments in the special entry:
foo.h template <class T> class Foo { ... various members ... };
If a template class member is a static member, you must include the keyword
static in your specialization entry:
Exception Handling
8-1
8.2 Specifying Runtime Errors
There are five runtime error messages associated with exceptions:
■ No handler for the exception
■ Unexpected exception thrown
■ An exception can only be re-thrown in a handler
■ During stack unwinding, a destructor must handle its own exception
■ Out of memory
When errors are detected at runtime, the error message displays the type of the
current exception and one of the five error messages. By default, the predefined
function terminate() is called, which then calls abort().
Note – Because the C++ standard library, dynamic_cast, and the default operator
new require exceptions, you should not turn off exceptions when you compile in
standard mode (the default mode).
The standard class exception is the base class for all exceptions thrown by selected
language constructs or by the C++ standard library. An object of type exception
can be constructed, copied, and destroyed without generating an exception. The
virtual member function what() returns a character string that describes the
exception.
All the rules for using exceptions and setjmp/longjmp separately apply. In
addition, a longjmp from point A to point B is valid only if an exception thrown at
A and caught at B would have the same effect. In particular, you must not longjmp
into or out of a try-block or catch-block (directly or indirectly), or longjmp past the
initialization or non-trivial destruction of auto variables or temporary variables.
Note – When building shared libraries that contain exceptions, do not pass the
option –Bsymbolic to ld. Exceptions that should be caught might be missed.
Cast Operations
This chapter discusses the newer cast operators in the C++ standard: const_cast,
reinterpret_cast, static_cast, and dynamic_cast. A cast converts an object
or value from one type to another.
These cast operations provide finer control than previous cast operations. The
dynamic_cast<> operator provides a way to check the actual type of a pointer to a
polymorphic class. You can search with a text editor for all new-style casts (search
for _cast), whereas finding old-style casts required syntactic analysis.
Otherwise, the new casts all perform a subset of the casts allowed by the classic cast
notation. For example, const_cast<int*>(v) could be written (int*)v. The new
casts simply categorize the variety of operations available to express your intent
more clearly and allow the compiler to provide better checking.
9-1
9.1 const_cast
The expression const_cast<T>(v) can be used to change the const or volatile
qualifiers of pointers or references. (Among new-style casts, only const_cast<>
can remove const qualifiers.) T must be a pointer, reference, or pointer-to-member
type.
class A
{
public:
virtual void f();
int i;
};
extern const volatile int* cvip;
extern int* ip;
void use_of_const_cast( )
{
const A a1;
const_cast<A&>(a1).f( ); // remove const
ip = const_cast<int*> (cvip); // remove const and volatile
}
9.2 reinterpret_cast
The expression reinterpret_cast<T>(v)changes the interpretation of the value
of the expression v. It can be used to convert between pointer and integer types,
between unrelated pointer types, between pointer-to-member types, and between
pointer-to-function types.
class B { ... };
class C : public B { ... };
enum E { first=1, second=2, third=3 };
void use_of_static_cast(C* c1 )
{
B* bp = c1; // implicit conversion
C* c2 = static_cast<C*>(bp); // reverse implicit conversion
int i = second; // implicit conversion
E e = static_cast<E>(i); // reverse implicit conversion
}
The static_cast operator cannot be used to cast away const. You can use
static_cast to cast “down” a hierarchy (from a base to a derived pointer or
reference), but the conversion is not checked; the result might not be usable. A
static_cast cannot be used to cast down from a virtual base class.
The dynamic type cast converts a pointer (or reference) to one class T1 into a pointer
(reference) to another class T2. T1 and T2 must be part of the same hierarchy, the
classes must be accessible (via public derivation), and the conversion must not be
When casting to void*, the hierarchy must be polymorphic (have virtual functions).
The conversion from v to T is not always possible when casting down or across a
hierarchy. For example, the attempted conversion might be ambiguous, T might be
inaccessible, or v might not point (or refer) to an object of the necessary type. If the
runtime check fails and T is a pointer type, the value of the cast expression is a null
pointer of type T. If T is a reference type, nothing is returned (there are no null
references in C++), and the standard exception std::bad_cast is thrown.
#include <assert.h>
#include <stddef.h> // for NULL
void simple_dynamic_casts( )
{
AB ab;
B* bp = &ab; // no casts needed
A* ap = &ab;
AB& abr = dynamic_cast<AB&>(*bp); // succeeds
ap = dynamic_cast<A*>(bp); assert( ap != NULL );
bp = dynamic_cast<B*>(ap); assert( bp != NULL );
ap = dynamic_cast<A*>(&abr); assert( ap != NULL );
bp = dynamic_cast<B*>(&abr); assert( bp != NULL );
}
#include <assert.h>
#include <stddef.h> // for NULL
#include <typeinfo>
void attempted_casts( )
{
AB ab;
B* bp = (B*)&ab; // C-style cast needed to break protection
A* ap = dynamic_cast<A*>(bp); // fails, B is inaccessible
assert(ap == NULL);
try {
AB& abr = dynamic_cast<AB&>(*bp); // fails, B is inaccessible
}
catch(const std::bad_cast&) {
return; // failed reference cast caught here
}
assert(0); // should not get here
}
Example:
void complex_dynamic_casts( )
{
AB_B__AB ab_b__ab;
A*ap = &ab_b__ab;
// okay: finds unique A statically
AB*abp = dynamic_cast<AB*>(ap);
// fails: ambiguous
assert( abp == NULL );
// STATIC ERROR: AB_B* ab_bp = (AB_B*)ap;
// not a dynamic cast
AB_B*ab_bp = dynamic_cast<AB_B*>(ap);
// dynamic one is okay
assert( ab_bp != NULL );
}
void using_dynamic_cast( A* ap )
{
if ( AB *abp = dynamic_cast<AB*>(ap) )
{ // abp is non-null,
// so ap was a pointer to an AB object
// go ahead and use abp
process_AB( abp ); }
else
{ // abp is null,
// so ap was NOT a pointer to an AB object
// do not use abp
process_not_AB( ap );
}
}
You can improve the performance of C++ functions by writing those functions in a
manner that helps the compiler do a better job of optimizing them. Many books have
been written on software performance in general and C++ in particular. For
example, see C++ Programming Style by Tom Cargill (Addison-Wesley, 1992), Writing
Efficient Programs by Jon Louis Bentley (Prentice-Hall, 1982), Efficient C++:
Performance Programming Techniques by Dov Bulka and David Mayhew (Addison-
Wesley, 2000), and Effective C++—50 Ways to Improve Your Programs and Designs,
Second Edition, by Scott Meyers, (Addison-Wesley, 1998). This chapter does not
repeat such valuable information, but discusses only those performance techniques
that strongly affect the Sun WorkShop C++ compiler.
T x = a + b;
T x( a ); x += b;
10-1
10.2 Using Inline Functions
Calls to small and quick functions can be smaller and quicker when expanded inline
than when called normally. Conversely, calls to large or slow functions can be larger
and slower when expanded inline than when branched to. Furthermore, all calls to
an inline function must be recompiled whenever the function definition changes.
Consequently, the decision to use inline functions requires considerable care.
Do not use inline functions when you anticipate changes to the function definition
and recompiling all callers is expensive. Otherwise, use inline functions when the
code to expand the function inline is smaller than the code to call the function or the
application performs significantly faster with the function inline.
The compiler cannot inline all function calls, so making the most effective use of
function inlining may require some source changes. Use the +w option to learn when
function inlining does not occur. In the following situations, the compiler will not
inline the function:
■ The function contains difficult control constructs, such as loops, switch
statements, and try/catch statements. Many times these functions execute the
difficult control constructs infrequently. To inline such a function, split the
function into two parts, an inner part that contains the difficult control constructs
and an outer part that decides whether or not to call the inner part. This
technique of separating the infrequent part from the frequent part of a function
can improve performance even when the compiler can inline the full function.
■ The inline function body is large or complicated. Apparently simple function
bodies may be complicated because of calls to other inline functions within the
body, or because of implicit constructor and destructor calls (as often occurs in
constructors and destructors for derived classes). For such functions, inline
expansion rarely provides significant performance improvement, and the function
is best left uninlined.
■ The arguments to an inline function call are large or complicated. The compiler is
particularly sensitive when the object for an inline member function call is itself
the result of an inline function call. To inline functions with complicated
arguments, simply compute the function arguments into local variables and then
pass the variables to the function.
Default operators are inline functions, so do not use default operators when inline
functions are inappropriate (see the previous section). Otherwise, default operators
are appropriate when:
■ The user-written parameterless constructor would only call parameterless
constructors for its base objects and member variables. Primitive types effectively
have “do nothing” parameterless constructors.
■ The user-written copy constructor would simply copy all base objects and
member variables.
■ The user-written copy assignment operator would simply copy all base objects
and member variables.
■ The user-written destructor would be empty.
Some C++ programming texts suggest that class programmers always define all
operators so that any reader of the code will know that the class programmer did
not forget to consider the semantics of the default operators. Obviously, this advice
interferes with the optimization discussed above. The resolution of the conflict is to
place a comment in the code stating that the class is using the default operator.
In standard mode (the default mode), a class is passed indirectly if it has any one of
the following:
■ A user-defined copy constructor
■ A user-defined destructor
■ A base that is passed indirectly
■ A non-static data member that is passed indirectly
Architecture Description
SPARC V7/V8 Structs and unions are passed and returned by allocating storage within
the caller and passing a pointer to that storage. (That is, all structs and
unions are passed by reference.)
SPARC V9 Structs with a size no greater than 16 bytes (32 bytes) are passed
(returned) in registers. Unions and all other structs are passed and
returned by allocating storage within the caller and passing a pointer to
that storage. (That is, small structs are passed in registers; unions and
large structs are passed by reference.) As a consequence, small value
classes are passed as efficiently as primitive types.
IA platforms Structs and unions are passed by allocating space on the stack and
copying the argument onto the stack. Structs and unions are returned by
allocating a temporary object in the caller's frame and passing the address
of the temporary object as an implicit first parameter.
The compiler must often load member variables from memory through the this
pointer. Because values are being loaded through a pointer, the compiler sometimes
cannot determine when a second load must be performed or whether the value
loaded before is still valid. In these cases, the compiler must choose the safe, but
slow, approach and reload the member variable each time it is accessed.
You can avoid unnecessary memory reloads by explicitly caching the values of
member variables in local variables, as follows:
■ Declare a local variable and initialize it with the value of the member variable.
■ Use the local variable in place of the member variable throughout the function.
■ If the local variable changes, assign the final value of the local variable to the
member variable. However, this optimization may yield undesired results if the
member function calls another member function on that object.
x*=x;
This chapter explains how to build multithreaded programs. It also discusses the use
of exceptions, explains how to share C++ Standard Library objects across threads,
and describes how to use classic (old) iostreams in a multithreading environment.
Do not link your application directly with –lthread because this causes
libthread to be linked in an incorrect order.
The following example shows the correct way to build a multithreaded application
when the compilation and linking are done in separate steps:
11-1
The following example shows the wrong way to build a multithreaded application:
Each thread can set its own terminate() or unexpected() function. Calling
set_terminate() or set_unexpected() in one thread affects only the
exceptions in that thread. The default function for terminate() is abort() for the
main thread, and thr_exit() for other threads (see Section 8.2 “Specifying
Runtime Errors” on page 8-2).
For example, if you instantiate a string, then create a new thread and pass that string
to the thread by reference, then you must lock around write access to that string,
since you are explicitly sharing the one string object between threads. (The facilities
provided by the library to accomplish this task are described below.)
On the other hand, if you pass the string to the new thread by value, you do not
need to worry about locking, even though the strings in the two different threads
may be sharing a representation through Rogue Wave’s “copy on write” technology.
class _RWSTDMutex
{
public:
_RWSTDMutex ();
~_RWSTDMutex ();
void acquire ();
void release ();
};
class _RWSTDGuard
{
public:
_RWSTDGuard (_RWSTDMutex&);
~_RWSTDGuard ();
};
#include <rw/stdmutex.h>
//
// An integer shared among multiple threads.
//
int I;
//
// A mutex used to synchronize updates to I.
//
_RWSTDMutex I_mutex;
//
// Increment I by one. Uses an _RWSTDMutex directly.
//
void increment_I ()
{
I_mutex.acquire(); // Lock the mutex.
I++;
I_mutex.release(); // Unlock the mutex.
}
//
// Decrement I by one. Uses an _RWSTDGuard.
//
void decrement_I ()
{
_RWSTDGuard guard(I_mutex); // Acquire the lock on I_mutex.
--I;
//
// The lock on I is released when destructor is called on guard.
//
}
The discussion here applies only to the old iostreams (libC and libiostream) and
does not apply to libCstd, the new iostream that is part of the C++ Standard
Library.
Class Description
unsafe_ios A class that contains state variables that are common to the
various stream classes; for example, error and formatting state.
unsafe_istream A class that supports formatted and unformatted conversion
from sequences of characters retrieved from the streambufs.
unsafe_ostream A class that supports formatted and unformatted conversion to
sequences of characters stored into the streambufs.
unsafe_iostream A class that combines unsafe_istream and unsafe_ostream
classes for bidirectional operations.
Each MT-safe class is derived from the base class stream_MT. Each MT-safe class,
except streambuf, is also derived from the existing unsafe_ base class. Here are
some examples:
The class stream_MT provides the mutual exclusion (mutex) locks required to make
each iostream class MT-safe; it also provides a facility that dynamically enables
and disables the locks so that the MT-safe property can be dynamically changed. The
basic functionality for I/O conversion and buffer management are organized into
the unsafe_ classes; the MT-safe additions to the library are confined to the derived
classes. The MT-safe version of each class contains the same protected and public
member functions as the unsafe_ base class. Each member function in the
MT-safe version class acts as a wrapper that locks the object, calls the same function
in the unsafe_ base class, and unlocks the object.
Note – The class streambuf is not derived from an unsafe class. The public and
protected member functions of class streambuf are reentrant by locking. Unlocked
versions, suffixed with _unlocked, are also provided.
Function Description
char *oct_r (char *buf, Returns a pointer to the ASCII string that represents the
int buflen, number in octal. A width of nonzero is assumed to be
long num, the field width for formatting. The returned value is not
int width) guaranteed to point to the beginning of the user-
provided buffer.
char *hex_r (char *buf, Returns a pointer to the ASCII string that represents the
int buflen, number in hexadecimal. A width of nonzero is assumed
long num, to be the field width for formatting. The returned value
int width) is not guaranteed to point to the beginning of the user-
provided buffer.
char *dec_r (char *buf, Returns a pointer to the ASCII string that represents the
int buflen, number in decimal. A width of nonzero is assumed to
long num, be the field width for formatting. The returned value is
int width) not guaranteed to point to the beginning of the user-
provided buffer.
char *chr_r (char *buf, Returns a pointer to the ASCII string that contains
int buflen, character chr. If the width is nonzero, the string
long num, contains width blanks followed by chr. The returned
int width) value is not guaranteed to point to the beginning of the
user-provided buffer.
char *form_r (char *buf, Returns a pointer of the string formatted by sprintf,
int buflen, using the format string format and any remaining
long num, arguments. The buffer must have sufficient space to
int width) contain the formatted string.
Note – The public conversion routines of the iostream library (oct, hex, dec, chr,
and form) that are present to ensure compatibility with an earlier version of libC
are not MT-safe.
Note – Use -mt (rather than -lthread) to link with libC and libthread. This
option ensures proper linking order of the libraries. Using -lthread improperly
could cause your application to work incorrectly.
#include <iostream.h>
enum iostate { IOok, IOeof, IOfail };
#include <iostream.h>
#include <rlocks.h>
void fetch_line(istream& istr, char* line, int& linecount)
{
stream_locker sl(istr, stream_locker::lock_defer);
In this example, the lock and unlock member functions of class stream_locker
define a mutual exclusion region in the program.
#include <rlocks.h>
#include <iostream.h>
class mystream: public istream {
// other definitions...
int getRecord(char* name, int& id, float& gpa);
};
return this->fail() == 0;
}
The scope resolution operator can be used to execute member functions of the base
unsafe_ classes; for example:
cout.unsafe_ostream::put('4');
cin.unsafe_istream::read(buf, len);
Instead of using unsafe_ classes, you can make the cout and cin objects unsafe
and then use the normal operations. A slight performance deterioration results. The
following example shows how to use unsafe cout and cin:
#include <iostream.h>
//disable mt-safety
cout.set_safe_flag(stream_MT::unsafe_object);
//disable mt-safety
cin.set_safe_flag(stream_MT::unsafe_object);
cout.put(‘4’);
cin.read(buf, len);
You can safely use an MT-unsafe stream in code where an iostream is not shared by
threads; for example, in a program that has only one thread, or in a program where
each iostream is private to a thread.
If you explicitly insert synchronization into the program, you can also safely use
MT-unsafe iostreams in an environment where an iostream is shared by threads.
The following example illustrates the technique:
generic_lock() ;
fs.set_safe_flag(stream_MT::unsafe_object) ;
... do various i/o operations
generic_unlock() ;
Note – The stream_locker class provided by the libC library is the preferred
mechanism for this purpose.
stream_MT
stream_locker
unsafe_ios
unsafe_istream
unsafe_ostream
unsafe_iostream
unsafe_fstreambase
unsafe_strstreambase
class streambuf {
public:
int sgetc_unlocked();
void sgetn_unlocked(char *, int);
int snextc_unlocked();
int sbumpc_unlocked();
void stossc_unlocked();
int in_avail_unlocked();
int sputbackc_unlocked(char);
int sputc_unlocked(int);
int sputn_unlocked(const char *, int);
int out_waiting_unlocked();
protected:
char* base_unlocked();
char* ebuf_unlocked();
filebuf* attach_unlocked(int);
};
unsafe_ostream& endl(unsafe_ostream&);
unsafe_ostream& ends(unsafe_ostream&);
unsafe_ostream& flush(unsafe_ostream&);
unsafe_istream& ws(unsafe_istream&);
unsafe_ios& dec(unsafe_ios&);
unsafe_ios& hex(unsafe_ios&);
unsafe_ios& oct(unsafe_ios&);
char* dec_r (char* buf, int buflen, long num, int width)
char* hex_r (char* buf, int buflen, long num, int width)
char* oct_r (char* buf, int buflen, long num, int width)
char* chr_r (char* buf, int buflen, long chr, int width)
int c;
cin.get(c);
gets the next character in the get buffer and updates the buffer pointer in ThreadA.
However, if the next instruction in ThreadA is another get call, the libC library does
not guarantee to return the next character in the sequence. It is not guaranteed
because, for example, ThreadB may have also executed the get call in the intervening
period between the two get calls made in ThreadA.
See Section 11.4.5 “Object Locks” for strategies for dealing with the problems of
shared objects and multithreading.
involves the execution of three member functions of the cout stream object. Since
cout is a shared object, the sequence must be executed atomically as a critical
section to work correctly in a multithreaded environment. To perform a sequence of
operations on an iostream class object atomically, you must use some form of
locking.
The libC library now provides the stream_locker class for locking operations on
an iostream object. See Section 11.4.5 “Object Locks” for information about the
stream_locker class.
However, in many cases, such as default shared standard stream objects, it is not
possible to make the objects local to a thread, and an alternative strategy is required.
#include <fstream.h>
#include <rlocks.h>
In this example, the constructor for the stream_locker object defines the
beginning of a mutual exclusion region in which only one thread can execute at a
time. The destructor, called after the return from the function, defines the end of the
mutual exclusion region. The stream_locker object ensures that both the seek to a
particular offset in a file and the read from the file are performed together,
atomically, and that ThreadB cannot change the file offset before the original ThreadA
reads the file.
{
...
stream_locker file_lck(openfile_stream,
stream_locker::lock_defer);
....
file_lck.lock(); // lock openfile_stream
openfile_stream << "Value: " << int_value << "\n";
if(!openfile_stream) {
file_error("Output of value failed\n");
return;
}
file_lck.unlock(); // unlock openfile_stream
}
#include <fstream.h>
#include <thread.h>
fstream* fp;
void *process_rtn(void*)
{
// body of sub-threads which uses fp...
}
...
// wait for threads to finish
for (int i=0; i<numthreads; i++)
thr_join(0, 0, 0);
#include <stdlib.h>
#include <stdio.h>
#include <iostream.h>
#include <fstream.h>
#include <thread.h>
struct thread_args {
char* filename;
int thread_tag;
};
// array of thread_ids
thread_t created_threads[thread_bufsize];
// array of arguments to thread entry routine
thread_args thr_args[thread_bufsize];
int i;
for( i = 0; i < num_threads; i++) {
thr_args[i].filename = argv[1 + i];
// assign a tag to a thread - a value less than 256
thr_args[i].thread_tag = total_tags++;
// create threads
thr_create(0, 0, ThreadDuties, &thr_args[i],
THR_SUSPENDED, &created_threads[i]);
}
Using Libraries
Libraries provide a way to share code among several applications and a way to
reduce the complexity of very large applications. The Sun WorkShop C++ compiler
gives you access to a variety of libraries. This chapter explains how to use these
libraries.
The C++ compiler has its own runtime support libraries. All C++ applications are
linked to these libraries by the CC driver. The C++ compiler also comes with several
other useful libraries, as explained in the following section.
12-1
12.2 Libraries Provided With the C++
Compiler
Several libraries are shipped with the C++ compiler. Some of these libraries are
available only in compatibility mode (–compat=4), some are available only in the
standard mode (–compat=5), and some are available in both modes. The libgc and
libdemangle libraries have a C interface and can be linked to an application in
either mode.
The following table lists the libraries that are shipped with the C++ compiler and the
modes in which they are available.
file:/opt/SUNWspro/docs/index.html
If your Sun WorkShop software is not installed in the /opt directory, ask your
system administrator for the equivalent path on your system.
■ libiostream: This is the classic iostreams library built with –compat=5. If you
have existing sources that use the classic iostreams and you want to compile these
sources with the standard mode (–compat=5), you can use libiostream
without modifying your sources. Use –library=iostream to get this library.
■ libC: This is the library needed in compatibility mode (–compat=4). It contains
the C++ runtime support as well as the classic iostreams.
■ libcomplex: This library provides complex arithmetic in compatibility mode
(-compat=4). In the standard mode, the complex arithmetic functionality is
available in libCstd.
■ librwtool (Tools.h++): Tools.h++ is a C++ foundation class library from
RogueWave. Version 7 of this library is provided with this release. This library is
available in classic-iostreams form (-library=rwtools7) and standard-
iostreams form (-library=rwtools7_std). For further information about this
library, see the following online documentation.
■ Tools.h++ User’s Guide (Version 7)
■ Tools.h++ Class Library Reference (Version 7)
You can access this documentation by pointing your web browser to:
file:/opt/SUNWspro/docs/index.html
If your Sun WorkShop software is not installed in the /opt directory, ask your
system administrator for the equivalent path on your system.
■ libgc: This garbage collection library is a component of Sun WorkShop Memory
Monitor. The Sun WorkShop Memory Monitor provides facilities to automatically
report and fix memory leaks, memory fragmentation, and premature frees (the
freeing of memory that is still in use). The Sun WorkShop Memory Monitor has
three modes of operation:
■ Debugging
■ Deployment
■ Garbage collection
You can access documentation about this library by launching the Memory
Monitor or by pointing your web browser to:
file:/opt/SUNWspro/docs/index.html
If your Sun WorkShop software is not installed in the /opt directory, ask your
system administrator for the equivalent path on your system.
Note – If your Sun WorkShop software is not installed in the /opt directory, ask
your system administrator for the equivalent path on your system.
You can also access the man pages by pointing your browser to:
file:/opt/SUNWspro/docs/index.html
A library that is specified using both –library and –staticlib options will be
linked statically. Some examples:
■ The following command links the classic-iostreams form of Tools.h++ version 7
and libiostream libraries dynamically.
■ The following command excludes the libraries libCrun and libCstd, which
would otherwise be included by default.
By default, CC links various sets of system libraries depending on the command line
options. If you specify -xnolib (or -nolib), CC links only those libraries that are
specified explicitly with the -l option on the command line. (When -xnolib or
-nolib is used, the -library option is ignored, if present.)
The –R option allows you to build dynamic library search paths into the executable
file. At execution time, the runtime linker searches these paths for the shared
libraries needed by the application. The CC driver passes –R/opt/SUNWspro/lib
If you have existing C++ sources, your code might look like the following example,
which uses classic iostreams.
// file prog1.cc
#include <iostream.h>
int main() {
cout << "Hello, world!" << endl;
return 0;
}
// file prog2.cc
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
The following command compiles and links prog2.cc into an executable program
called prog2. The program is compiled in standard mode and libCstd, which
includes the standard iostream library, is linked by default.
For more information about libCstd, see Chapter 13. For more information about
libiostream, see Chapter 14.
In compatibility mode, you must explicitly ask for the complex library when linking.
In standard mode, the complex library is included in libCstd, and is linked by
default.
There is no complex.h header for standard mode. In C++ 4.2, “complex” is the
name of a class, but in standard C++, “complex” is the name of a template. It is not
possible to provide typedefs that allow old code to work unchanged. Therefore, code
written for 4.2 that uses complex numbers will need some straightforward editing to
int main()
{
complex x(3,3), y(4,4);
complex z = x * y;
cout << "x=" << x << ", y=" << y << ", z=" << z << endl;
}
The following example compiles and links ex1.cc in compatibility mode, and then
executes the program.
int main()
{
complex<double> x(3,3), y(4,4);
complex<double> z = x * y;
std::cout << "x=" << x << ", y=" << y << ", z=" << z <<
std::endl;
}
The following example compiles and links the rewritten ex2.cc in standard mode,
and then executes the program.
% CC ex2.cc
% a.out
x=(3,3), y=(4,4), z=(0,24)
If you want any of these default libraries to be linked statically, you can use the
-library option along with the –staticlib option to link a C++ library statically.
This alternative is much easier than the one described earlier. For example:
Alternately, you can use the -xnolib compiler option. With the -xnolib option,
the driver does not pass any -l options to ld; you must pass these options yourself.
The following example shows how you would link statically with libCrun, and
dynamically with libw, libm, and libc in the Solaris 2.6, Solaris 7, or Solaris 8
environment:
The order of the -l options is important. The –lCstd, –lCrun, -lm, -lw, and
-lcx options appear before -lc.
Some CC options link to other libraries. These library links are also suppressed by
-xnolib. For example, using the -mt option causes the CC driver to pass -lthread
to ld. However, if you use both –mt and –xnolib, the CC driver does not pass
-lthread to ld. See Section A.2.124 “–xnolib” for more information. See Linker and
Libraries Guide for more information about ld.
Note – To use the libCstd and libiostream shared libraries, you must follow the
steps in Section 13.1 “Shared libCstd” and Section 14.1 “Shared libiostream.”
You can still run the old binary code without recompiling it by setting the
environment variable LD_LIBRARY_PATH to the new library directory.
In a C shell:
In a Bourne shell:
example$ LD_LIBRARY_PATH=\
/opt2/SUNWspro/release/lib:${LD_LIBRARY_PATH}
example$ export LD_LIBRARY_PATH
Use the ldd command as shown in the following example to see which libraries are
linked dynamically in your executable:
This step should rarely be necessary, because the shared libraries are seldom moved.
See Linker and Libraries Guide for more information on using shared libraries.
The replaceable part of the library consists of what is loosely known as “STL”, plus
the string classes, the iostream classes, and their helper classes. Because these classes
and headers are interdependent, replacing just a portion of them is unlikely to work.
You should replace all of the headers and all of libCstd if you replace any part.
Alternatively, you can use the full path name of the library directly, and omit using
the -L and -l options. For example:
During linking, the -library=no%Cstd option prevents linking the compiler’s own
version of libCstd.
C++ also has a second version of each of the C standard headers (<cstdio>,
<cstring>, and <cstdlib>, and others) with the various declared names
appearing only in namespace std. Finally, C++ adds 32 of its own standard headers
(<string>, <utility>, <iostream>, and others).
The obvious implementation of the standard headers would use the name found in
C++ source code as the name of a text file to be included. For example, the standard
headers <string> (or <string.h>) would refer to a file named string (or
string.h) in some directory. That obvious implementation has the following
drawbacks:
■ You cannot search for just header files or create a makefile rule for the header
files if they do not have file name suffixes.
■ If you put -I/usr/include on the compiler command line, you do not get the
correct version of the standard C headers on Solaris 2.6 and Solaris 7 operating
environments because /usr/include is searched before the compiler’s own
include directory is searched.
■ If you have a directory or executable program named string, it might
erroneously be found instead of the standard header file.
■ On versions of the Solaris operating environment prior to Solaris 8, the default
dependencies for makefiles when .KEEP_STATE is enabled can result in attempts
to replace standard headers with an executable program. (A file without a suffix is
assumed by default to be a program to be built.)
To solve these problems, the compiler include directory contains a file with the
same name as the header, along with a symbolic link to it that has the unique suffix
.SUNWCCh (SUNW is the prefix for all compiler-related packages, CC is the C++
compiler, and h is the usual suffix for header files). When you specify <string>, the
compiler rewrites it to <string.SUNWCCh> and searches for that name. The suffixed
name will be found only in the compiler’s own include directory. If the file so
found is a symbolic link (which it normally is), the compiler dereferences the link
exactly once and uses the result (string in this case) as the file name for error
messages and debugger references. The compiler uses the suffixed name when
emitting file dependency information.
If the compiler does not find header.SUNWCCh, the compiler restarts the search
looking for the name as provided in the #include directive. For example, given the
directive #include <string>, the compiler attempts to find a file named
string.SUNWCCh. If that search fails, the compiler looks for a file named string.
When the compiler looks first for utility.SUNWCCh, it will find it, and not be
confused by any other file or directory called utility.
For example, suppose you have replacements for <stdio.h> and <cstdio>. Put
the files stdio.h and cstdio in directory /myproject/myhdr. In that directory,
run these commands:
Caveats:
■ If you replace any C headers, you must replace them in pairs. For example, if you
replace <time.h>, you should also replace <ctime>.
■ Replacement headers must have the same effects as the versions being replaced.
That is, the various runtime libraries such as libCrun, libC, libCstd, libc,
and librwtool are built using the definitions in the standard headers. If your
replacements do not match, your program is unlikely to work.
When compiling in default (standard) mode, the compiler has access to the complete
library specified by the C++ standard. The library components include what is
informally known as the Standard Template Library (STL), as well as the following
components.
■ string classes
■ numeric classes
■ the standard version of stream I/O classes
■ basic memory allocation
■ exception classes
■ run-time type information
The term STL does not have a formal definition, but is usually understood to include
containers, iterators, and algorithms. The following subset of the standard library
headers can be thought of as comprising the STL.
■ <algorithm>
■ <deque>
■ <iterator>
■ <list>
■ <map>
■ <memory>
■ <queue>
■ <set>
■ <stack>
■ <utility>
■ <vector>
The C++ standard library (libCstd) is based on the RogueWave™ Standard C++
Library, Version 2. This library is available only for the default mode (-compat=5) of
the compiler and is not supported with use of the -compat[=4] option.
13-1
If you need to use your own version of the C++ standard library instead of the
version that is supplied with the compiler, you can do so by specifying the
-library=no%Cstd option. Replacing the standard library that is distributed with
the compiler is risky, and good results are not guaranteed. For more information, see
Section 12.7 “Replacing the C++ Standard Library.”
For details about the standard library, see the Standard C++ Library User’s Guide and
the Standard C++ Class Library Reference. “Accessing Sun WorkShop Documentation”
in “Before You Begin” at the front of this book contains information about accessing
this documentation. For a list of available books about the C++ standard library see
“Commercially Available Books” in “Before You Begin.”
example% ln -s /usr/lib/libCstd.so.1 \
/opt/SUNWSpro/lib/libCstd.so
example% ln -s /usr/lib/libCstd.so.1 \
/opt/SUNWspro/lib/v8plus/libCstd.so
example% ln -s /usr/lib/sparcv9/libCstd.so.1 \
/opt/SUNWSpro/lib/v9/libCstd.so
Note – If the compiler is not installed in /opt, ask your system administrator for the
equivalent path.
2. Once these symbolic links are created, libCstd will be linked dynamically by
default.
C++, like C, has no built-in input or output statements. Instead, I/O facilities are
provided by a library. The C++ compiler provides both the classic implementation
and the ISO standard implementation of the iostream classes.
■ In compatibility mode (-compat[=4]), the classic iostream classes are
contained in libC.
■ In standard mode (default mode), the classic iostream classes are contained in
libiostream. Use libiostream when you have source code that uses the
classic iostream classes and you want to compile the source in standard mode.
To use the classic iostream facilities in standard mode, include the iostream.h
header file and compile using the -library=iostream option.
■ The standard iostream classes are available only in standard mode, and are
contained in the C++ standard library, libCstd.
This chapter provides an introduction to the classic iostream library and provides
examples of its use. This chapter does not provide a complete description of the
iostream library. See the iostream library man pages for more details. To access
the classic iostream man pages type:
14-1
1. As superuser, manually create the following symbolic links.
example% ln -s /usr/lib/libiostream.so.1 \
/opt/SUNWspro/lib/libiostream.so
example% ln -s /usr/lib/sparcv9/libiostream.so.1 \
/opt/SUNWSpro/lib/v9/libiostream.so
Note – If your compiler is not installed in the /opt/SUNWSpro directory, ask your
system administrator for the equivalent path on your system.
3. Once these symbolic links are created, the compiler dynamically links
libiostream by default whenever you use -library=iostream.
Note – If you are planning to distribute object files that were linked with the shared
libiostream library, you must either distribute the latest SUNWlibC patch with
your product, or require your customers to download the latest SUNWlibC patch
from a Sun web site, such as http://sunsolve.sun.com. The patch is free, and is
freely redistributable.
The predefined iostreams are fully buffered, except for cerr. See Section 14.4.1
“Output Using iostream” and Section 14.4.2 “Input Using iostream.”
A stream can be restricted to input or output, or a single stream can allow both input
and output. The iostream library implements these streams using two processing
layers.
■ The lower layer implements sequences, which are simply streams of characters.
These sequences are implemented by the streambuf class, or by classes derived
from it.
■ The upper layer performs formatting operations on sequences. These formatting
operations are implemented by the istream and ostream classes, which have as
a member an object of a type derived from class streambuf. An additional class,
iostream, is for streams on which both input and output can be performed.
Standard input, output, and error are handled by special class objects derived from
class istream or ostream.
The ifstream, ofstream, and fstream classes, which are derived from istream,
ostream, and iostream respectively, handle input and output with files.
The istrstream, ostrstream, and strstream classes, which are derived from
istream, ostream, and iostream respectively, handle input and output to and
from arrays of characters.
When you open an input or output stream, you create an object of one of these
types, and associate the streambuf member of the stream with a device or file. You
generally do this association through the stream constructor, so you don’t work with
the streambuf directly. The iostream library predefines stream objects for the
standard input, standard output, and error output, so you don’t have to create your
own objects for those streams.
You use operators or iostream member functions to insert data into a stream
(output) or extract data from a stream (input), and to control the format of data that
you insert or extract.
When you want to insert and extract a new data type—one of your classes—you
generally overload the insertion and extraction operators.
You usually do not need all of these header files in your program. Include only the
ones that contain the declarations you need. In compatibility mode (-compat[=4]),
the classic iostream library is part of libC, and is linked automatically by the CC
driver. In standard mode (the default), libiostream contains the classic iostream
library.
The iostream library does not support user-defined types. If you define types that
you want to output in your own way, you must define an inserter (that is, overload
the << operator) to handle them correctly.
The << operator can be applied repetitively. To insert two values on cout, you can
use a statement like the one in the following example:
The output from the above example will show no space between the two values. So
you may want to write the code this way:
The << operator has the precedence of the left shift operator (its built-in meaning).
As with other operators, you can always use parentheses to specify the order of
action. It is often a good idea to use parentheses to avoid problems of precedence. Of
the following four statements, the first two are equivalent, but the last two are not.
#include <stdlib.h>
#include <iostream.h>
class string {
private:
char* data;
size_t size;
public:
// (functions not relevant here)
The insertion and extraction operators must in this case be defined as friends
because the data part of the string class is private.
When an error occurs, the iostream where it occurred enters an error state. Bits in
the iostream’s state are set according to the general category of the error. The
inserters defined in iostream ignore attempts to insert data into any stream that is
in an error state, so such attempts do not change the iostream’s state.
There is another way to test for errors. The ios class defines operator void *(),
so it returns a NULL pointer when there is an error. You can use a statement like:
For details on the error functions, see the iostream man pages.
14.4.1.3 Flushing
As with most I/O libraries, iostream often accumulates output and sends it on in
larger and generally more efficient chunks. If you want to flush the buffer, you
simply insert the special value flush. For example:
cout.write((char*)&x, sizeof(x));
The previous example violates type discipline by converting &x to char*. Doing so
is normally harmless, but if the type of x is a class with pointers, virtual member
functions, or one that requires nontrivial constructor actions, the value written by
the above example cannot be read back in properly.
This statement gets two values from standard input. As with other overloaded
operators, the extractors used depend on the types of a and b (and two different
extractors are used if a and b have different types). The format of input and how
you can control it is discussed in some detail in the ios(3CC4) man page. In general,
leading whitespace characters (spaces, newlines, tabs, form-feeds, and so on) are
ignored.
The get function reads characters from the input stream istr and stores them in
holder until maxline-1 characters have been read, or a new line is encountered, or
EOF, whichever happens first. The data in holder is then null-terminated. Finally,
the characters in holder are copied into the target string.
By convention, an extractor converts characters from its first argument (in this case,
istream& istr), stores them in its second argument, which is always a reference,
and returns its first argument. The second argument must be a reference because an
extractor is meant to store the input value in its second argument.
char x[50];
cin >> x;
This extractor skips leading whitespace and extracts characters and copies them to x
until it reaches another whitespace character. It then completes the string with a
terminating null (0) character. Be careful, because input can overflow the given array.
There is no telling where the input data will be stored, and it may cause your
program to abort.
char c;
cin.get(c); // leaves c unchanged if input fails
int b;
b = cin.get(); // sets b to EOF if input fails
Note – Unlike the other extractors, the char extractor does not skip leading
whitespace.
Here is a way to skip only blanks, stopping on a tab, newline, or any other character:
int a;
do {
a = cin.get();
}
while( a == ’ ’ );
cin.read((char*)&x, sizeof(x));
if (cin.peek() != c) return 0;
You can use the iostream manipulator ws to remove leading whitespace from the
iostream, whether or not skipping is enabled. The following example shows how
to remove the leading whitespace from iostream istr:
As with output errors, you should check the error state periodically and take some
action, such as aborting, when you find a nonzero state. The ! operator tests the
error state of an iostream. For example, the following code produces an input error
if you type alphabetic characters for input:
#include <stdlib.h>
#include <iostream.h>
void error (const char* message) {
cerr << message << "\n" ;
exit(1);
}
int main() {
cout << "Enter some characters: ";
int bad;
cin >> bad;
if (!cin) error("aborted due to input error");
cout << "If you see this, not an error." << "\n";
return 0;
}
Class ios has member functions that you can use for error handling. See the man
pages for details.
To eliminate this problem with standard input, standard output and standard error,
use the following instruction before performing any input or output. It connects all
the predefined iostreams with the corresponding predefined stdio FILEs.
ios::sync_with_stdio();
Include the file fstream.h to use any of the fstreams. Use an ifstream when
you only want to perform input, an ofstream for output only, and an fstream for
a stream on which you want to perform both input and output. Use the name of the
file as the constructor argument.
For example, copy the file thisFile to the file thatFile as in the following
example:
ifstream fromFile("thisFile");
if (!fromFile)
error("unable to open ’thisFile’ for input");
ofstream toFile ("thatFile");
if ( !toFile )
error("unable to open ’thatFile’ for output");
char c ;
while (toFile && fromFile.get(c)) toFile.put(c);
Note – It is, of course, undesirable to copy a file this way, one character at a time.
This code is provided just as an example of using fstreams. You should instead
insert the streambuf associated with the input stream into the output stream. See
Section 14.11 “Streambufs” on page 14-22, and the man page sbufpub(3CC4).
Note – The binary flag is not needed on UNIX, but is provided for compatibility
with systems that do need it. Portable code should use the binary flag when
opening binary files.
You can open a file for both input and output. For example, the following code
opens file someName for both input and output, attaching it to the fstream variable
inoutFile.
ofstream toFile;
toFile.open(argv[1], ios::out);
ifstream infile;
for (char** f = &argv[1]; *f; ++f) {
infile.open(*f, ios::in);
...;
infile.close();
}
ofstream outfile;
outfile.attach(1);
When you open a file by providing its name to one of the fstream constructors or
by using the open function, the file is automatically closed when the fstream is
destroyed (by a delete or when it goes out of scope). When you attach a file to an
fstream, it is not automatically closed.
seekg (seekp) can take one or two parameters. When it has two parameters, the
first is a position relative to the position indicated by the seek_dir value given as
the second parameter. For example:
aFile.seekp(-10, ios::end);
aFile.seekp(10, ios::cur);
Note – Arbitrary seeks on text streams are not portable, but you can always return
to a previously saved streampos value.
The problem with copying a stream object is that there are then two versions of the
state information, such as a pointer to the current write position within an output
file, which can be changed independently. As a result, problems could occur.
14.8 Manipulators
Manipulators are values that you can insert into or extract from iostreams to have
special effects.
Because manipulators are ordinary identifiers, and therefore use up possible names,
iostream doesn’t define them for every possible function. A number of
manipulators are discussed with member functions in other parts of this chapter.
There are 13 predefined manipulators, as described in TABLE 14-2. When using that
table, assume the following:
■ i has type long.
■ n has type int.
■ c has type char.
■ istr is an input stream.
■ ostr is an output stream.
1 ostr << dec, istr >> dec Makes the integer conversion base 10.
5 ostr << hex, istr >> hex Makes the integer conversion base 16.
6 ostr << oct, istr >> oct Make the integer conversion base 8.
9 ostr << setw(n), istr >> setw(n) Invokes ios::width(n). Sets the
field width to n.
10 ostr << resetiosflags(i), Clears the flags bitvector according to
istr >> resetiosflags(i) the bits set in i.
To use predefined manipulators, you must include the file iomanip.h in your
program.
You can define your own manipulators. There are two basic types of manipulator:
■ Plain manipulator—Takes an istream&, ostream&, or ios& argument, operates
on the stream, and then returns its argument.
■ Parameterized manipulator—Takes an istream&, ostream&, or ios& argument,
one additional argument (the parameter), operates on the stream, and then
returns its stream argument.
The shift operators taking (a pointer to) such a function are predefined for
iostreams, so the function can be put in a sequence of input or output operators.
The shift operator calls the function rather than trying to read or write a value. An
example of a tab manipulator that inserts a tab in an ostream is:
The following code is another example, which cannot be accomplished with a simple
constant. Suppose you want to turn whitespace skipping on and off for an input
stream. You can use separate calls to ios::setf and ios::unsetf to turn the
skipws flag on and off, or you could define two manipulators.
//file setfill.cc
#include<iostream.h>
#include<iomanip.h>
Several classes are defined in the header file iomanip.h. Each class holds the
address of a manipulator function and the value of one parameter. The iomanip
classes are described in the man page manip(3CC4). The previous example uses the
smanip_int class, which works with an ios. Because it works with an ios, it also
works with an istream and an ostream. The previous example also uses a second
parameter of type int.
The applicator creates and returns a class object. In the previous code example the
class object is an smanip_int, and it contains the manipulator and the int
argument to the applicator. The iomanip.h header file defines the shift operators
for this class. When the applicator function setfill appears in a sequence of input
or output operations, the applicator function is called, and it returns a class. The
shift operator acts on the class to call the manipulator function with its parameter
value, which is stored in the class.
The class omanip_long is used because this code example is for output only, and it
operates on a long rather than an int:
#include <iostream.h>
#include <iomanip.h>
static ostream& xfield(ostream& os, long v) {
long save = os.setf(ios::hex, ios::basefield);
os << v;
os.setf(save, ios::basefield);
return os;
}
omanip_long print_hex(long v) {
return omanip_long(xfield, v);
}
14.11 Streambufs
iostreams are the formatting part of a two-part (input or output) system. The other
part of the system is made up of streambufs, which deal in input or output of
unformatted streams of characters.
You usually use streambufs through iostreams, so you don’t have to worry
about the details of streambufs. You can use streambufs directly if you choose to,
for example, if you need to improve efficiency or to get around the error handling or
formatting built into iostreams.
Apart from creating your own special kind of streambuf, you may want to access
the streambuf associated with an iostream to access the public member
functions, as described in the man pages referenced above. In addition, each
iostream has a defined inserter and extractor which takes a streambuf pointer.
When a streambuf is inserted or extracted, the entire stream is copied.
Here is another way to do the file copy discussed earlier, with the error checking
omitted for clarity:
ifstream fromFile("thisFile");
ofstream toFile ("thatFile");
toFile << fromFile.rdbuf();
We open the input and output files as before. Every iostream class has a member
function rdbuf that returns a pointer to the streambuf object associated with it. In
the case of an fstream, the streambuf object is type filebuf. The entire file
associated with fromFile is copied (inserted into) the file associated with toFile.
The last line could also be written like this:
The source file is then extracted into the destination. The two methods are entirely
equivalent.
filebuf Details the public interface for the class filebuf, which is derived from
streambuf and is specialized for use with files. See the sbufpub(3CC4)
and sbufprot(3CC4) man pages for details of features inherited from class
streambuf. Use the filebuf class through class fstream.
fstream Details specialized member functions of classes ifstream, ofstream, and
fstream, which are specialized versions of istream, ostream, and
iostream for use with files.
ios Details parts of class ios, which functions as a base class for iostreams. It
contains state data common to all streams.
ios.intro Gives an introduction to and overview of iostreams.
istream Details the following:
• Member functions for class istream, which supports interpretation of
characters fetched from a streambuf
• Input formatting
• Positioning functions described as part of class ostream.
• Some related functions
• Related manipulators
manip Describes the input and output manipulators defined in the iostream
library.
ostream Details the following:
• Member functions for class ostream, which supports interpretation of
characters written to a streambuf
• Output formatting
• Positioning functions described as part of class ostream
• Some related functions
• Related manipulators
sbufprot Describes the interface needed by programmers who are coding a class
derived from class streambuf. Also refer to the sbufpub(3CC4) man page
because some public functions are not discussed in the sbufprot(3CC4)
man page.
sbufpub Details the public interface of class streambuf, in particular, the public
member functions of streambuf. This man page contains the information
needed to manipulate a streambuf-type object directly, or to find out
about functions that classes derived from streambuf inherit from it. If you
want to derive a class from streambuf, also see the sbufprot(3CC4) man
page.
ssbuf Details the specialized public interface of class strstreambuf, which is
derived from streambuf and specialized for dealing with arrays of
characters. See the sbufpub(3CC4) man page for details of features
inherited from class streambuf.
stdiobuf Contains a minimal description of class stdiobuf, which is derived from
streambuf and specialized for dealing with stdio FILEs. See the
sbufpub(3CC4) man page for details of features inherited from class
streambuf.
strstream Details the specialized member functions of strstreams, which are
implemented by a set of classes derived from the iostream classes and
specialized for dealing with arrays of characters.
Buffer A word with two meanings, one specific to the iostream package and one
more generally applied to input and output.
Complex numbers are numbers made up of a real part and an imaginary part. For
example:
3.2 + 4i
1 + 3i
1 + 2.3i
15-1
Complex numbers can also be represented as an absolute value (or magnitude) and an
argument (or angle). The library provides functions to convert between the real and
imaginary (Cartesian) representation and the magnitude and angle (polar)
representation.
The complex conjugate of a number has the opposite sign in its imaginary part.
class complex {
double re, im;
};
The value of an object of class complex is a pair of double values. The first value
represents the real part; the second value represents the imaginary part.
complex aComp;
You can give either one or two parameters. In either case, the second constructor is
used. When you give only one parameter, that parameter is taken as the value for
the real part and the imaginary part is set to 0. For example:
complex aComp(4.533);
4.533 + 0i
If you give two values, the first value is taken as the value of the real part and the
second as the value of the imaginary part. For example:
8.999 + 2.333i
You can also create a complex number using the polar function, which is provided
in the complex arithmetic library (see Section 15.3 “Mathematical Functions”). The
polar function creates a complex value given the polar coordinates magnitude and
angle.
+ - / * =
In addition, you can use the following operators in the usual way:
■ Addition assign operator (+=)
■ Subtraction assign operator (-=)
■ Multiplication assign operator (*=)
■ Division assign operator (/=)
However, the preceding four operators do not produce values that you can use in
expressions. For example, the following expressions do not work:
complex a, b;
...
if ((a+=2)==0) {...}; // illegal
b = a *= b; // illegal
You can also use the equality operator (==) and the inequality operator (!=) in their
regular meaning.
When you mix real and complex numbers in an arithmetic expression, C++ uses the
complex operator function and converts the real values to complex values.
All of these functions produce a result for every possible argument. If a function
cannot produce a mathematically acceptable result, it calls complex_error and
returns some suitable value. In particular, the functions try to avoid actual overflow
and call complex_error with a message instead. The following tables describe the
remainder of the complex arithmetic library functions.
Note – The implementation of the sqrt and atan2 functions is aligned with the
C99 csqrt Annex G specification.
The external variable errno is the global error state from the C library. errno can
take on the values listed in the standard header errno.h (see the man page
perror(3)). No function sets errno to zero, but many functions set it to other
values.
The default version of complex_error returns zero. This return of zero means that
the default error handling takes place. You can provide your own replacement
function complex_error that performs other error handling. Error handling is
described in the man page cplxerr(3CC4).
Complex Arithmetic
Library Function Default Error Handling Summary
exp If overflow occurs, sets errno to ERANGE and returns a huge complex
number.
log, log10 If the argument is zero, sets errno to EDOM and returns a huge
complex number.
sinh, cosh If the imaginary part of the argument causes overflow, returns a
complex zero. If the real part causes overflow, returns a huge complex
number. In either case, sets errno to ERANGE.
For basic information on extractors and inserters, see Section 14.3 “Basic Structure of
iostream Interaction” on page 14-3 and Section 14.4.1 “Output Using iostream” on
page 14-4.
complex x;
cin >> x;
and the input (3.45, 5), the value of x is equivalent to 3.45 + 5.0i. The reverse
is true for inserters. Given complex x(3.45, 5), cout<<x prints (3.45, 5).
The inserter inserts the values of the real and imaginary parts enclosed in
parentheses and separated by a comma. It does not include the symbol i. The two
values are treated as doubles.
int i, j;
double x, y;
complex a, b;
a = sin((b+i)/y) + x/j;
The expression b+i is mixed-mode. Integer i is converted to type complex via the
constructor complex::complex(double,double=0), the integer first being
converted to type double. The result is to be divided by y, a double, so y is also
converted to complex and the complex divide operation is used. The quotient is
thus type complex, so the complex sine routine is called, yielding another complex
result, and so on.
complex a, b;
a == b; // OK
a != b; // OK
a < b; // error: operator < cannot be applied to type complex
a >= b; // error: operator >= cannot be applied to type complex
Similarly, there is no automatic conversion from type complex to any other type,
because the concept is not well-defined. You can specify whether you want the real
part, imaginary part, or magnitude, for example.
complex a;
double f(double);
f(abs(a)); // OK
f(a); // error: no match for f(complex)
15.7 Efficiency
The design of the complex class addresses efficiency concerns.
The simplest functions are declared inline to eliminate function call overhead.
Several overloaded versions of functions are provided when that makes a difference.
For example, the pow function has versions that take exponents of type double and
int as well as complex, since the computations for the former are much simpler.
The standard C math library header math.h is included automatically when you
include complex.h. The C++ overloading rules then result in efficient evaluation of
expressions like this:
double x;
complex x = sqrt(x);
In this example, the standard math function sqrt(double) is called, and the result
is converted to type complex, rather than converting to type complex first and then
calling sqrt(complex). This result falls right out of the overload resolution rules,
and is precisely the result you want.
Building Libraries
Building a library simply means creating .o files (by compiling your code with the
-c option) and combining the .o files into a library using the CC command. You can
build two kinds of libraries, static (archive) libraries and dynamic (shared) libraries.
With static (archive) libraries, objects within the library are linked into the program’s
executable file at link time. Only those .o files from the library that are needed by
the application are linked into the executable. The name of a static (archive) library
generally ends with a .a suffix.
With dynamic (shared) libraries, objects within the library are not linked into the
program’s executable file, but rather the linker notes in the executable that the
program depends on the library. When the program is executed, the system loads
the dynamic libraries that the program requires. If two programs that use the same
dynamic library execute at the same time, the operating system shares the library
among the programs. The name of a dynamic (shared) library ends with a .so
suffix.
16-1
Linking dynamically with shared libraries has several advantages over linking
statically with archive libraries:
■ The size of the executable is smaller.
■ Significant portions of code can be shared among programs at runtime, reducing
the amount of memory use.
■ The library can be replaced at runtime without relinking with the application.
(This is the primary mechanism that enables programs to take advantage of many
improvements in the Solaris environment without requiring relinking and
redistribution of programs.)
■ The shared library can be loaded at runtime, using the dlopen() function call.
You should build static (archive) libraries using CC -xar instead of using the ar
command directly. The C++ language generally requires that the compiler maintain
more information than can be accommodated with traditional .o files, particularly
template instances. The –xar option ensures that all necessary information,
including template instances, is included in the library. You might not be able to
accomplish this in a normal programming environment since make might not know
which template files are actually created and referenced. Without CC -xar,
referenced template instances might not be included in the library, as required. For
example:
Note – Use the -xar flag for creating or updating an existing archive only. Do not
use it to maintain an archive. The -xar option is equivalent to ar -cr.
It is a good idea to have only one function in each .o file. If you are linking with an
archive, an entire .o file from the archive is linked into your application when a
symbol is needed from that particular .o file. Having one function in each .o file
ensures that only those symbols needed by the application will be linked from the
archive.
You should not use ld directly. As with static libraries, the CC command ensures that
all the necessary template instances from the template repository are included in the
library if you are using templates. All static constructors in a dynamic library that is
linked to an application are called before main() is executed and all static
destructors are called after main() exits. If a shared library is opened using
dlopen(), all static constructors are executed at dlopen() and all static destructors
are executed at dlclose().
You should use CC -G to build a dynamic library. When you use ld (the link-editor)
or cc (the C compiler) to build a dynamic library, exceptions might not work and the
global variables that are defined in the library are not initialized.
To build a dynamic (shared) library, you must create relocatable object files by
compiling each object with the –Kpic or –KPIC option of CC. You can then build a
dynamic library with these relocatable object files. If you get any bizarre link
failures, you might have forgotten to compile some objects with –Kpic or –KPIC.
To build a C++ dynamic library named libfoo.so that contains objects from source
files lsrc1.cc and lsrc2.cc, type:
Note – The CC -G command does not pass any -l options to ld. If you want the
shared library to have a dependency on another shared library, you must pass the
necessary -l option on the command line. For example, if you want the shared
library to be dependent upon libCrun.so, you must pass -lCrun on the command
line.
Note – When building shared libraries that contain exceptions, do not pass the
option –Bsymbolic to ld. Exceptions that should be caught might be missed.
The SPARC ABI reserves some registers exclusively for applications. For V7 and V8,
these registers are %g2, %g3, and %g4. For V9, these registers are %g2 and %g3. Since
most compilations are for applications, the C++ compiler, by default, uses these
registers for scratch registers, improving program performance. However, use of
these registers in a public library is generally not compliant with the SPARC ABI.
When building a library for public use, compile all objects with the
-xregs=no%appl option to ensure that the application registers are not used.
If a C-interface library needs C++ run-time support and you are linking with cc, then
you must also link your application with either libC (compatibility mode) or
libCrun (standard mode) when you use the C-interface library. (If the C-interface
library does not need C++ run-time support, then you do not have to link with libC
or libCrun.) The steps for linking differ for archived and shared libraries.
If you want to remove any dependency on the C++ runtime libraries, you should
enforce the following coding rules in your library sources:
■ Do not use any form of new or delete unless you provide your own
corresponding versions.
■ Do not use exceptions.
■ Do not use runtime type information (RTTI).
To do this, add -lC for -compat=4 or add -lCrun for -compat=5 to the command
line when building the shared library. For example:
If the shared library uses exceptions and does not have a dependency on the C++
runtime library, your C program might behave erratically.
Note – When shared libraries are opened with dlopen(), RTLD_GLOBAL must be
used for exceptions to work.
This appendix details the command-line options for the CC compiler running under
Solaris 2.6, Solaris 7, and Solaris 8. The features described apply to all platforms
except as noted; features that are unique to the Solaris SPARC Platform Edition
operating environment are identified as SPARC, and the features that are unique to
the Solaris Intel Platform Edition operating environment are identified as IA.
-option –E
–optionvalue –Ipathname
–option=value –xunroll=4
–option value –o filename
The typographical conventions that are listed in “Before You Begin” at the front of
this manual are used in this section of the manual to describe individual options.
Parentheses, braces, brackets, pipe characters, and ellipses are metacharacters used in
the descriptions of the options and are not part of the options themselves.
A-1
A.1 How Option Information Is Organized
To help you find information, compiler option descriptions are separated into the
following subsections. If the option is one that is replaced by or identical to some
other option, see the description of the other option for full details.
Subsection Contents
If there are two options with the same general meaning and
purpose, the preferred option is referenced here. For example,
“Same as -xO” indicates that -xO is the preferred option.
A.2.1 –386
IA: Same as –xtarget=386. This option is provided for backward compatibility only.
A.2.2 –486
IA: Same as –xtarget=486. This option is provided for backward compatibility only.
A.2.3 –a
Same as –xa.
A.2.4 –Bbinding
Specifies whether a library binding for linking is symbolic, dynamic (shared), or static
(nonshared).
You can use the –B option several times on a command line. This option is passed to
the linker, ld.
Note – On the Solaris 7 and Solaris 8 platforms, not all libraries are available as
static libraries.
dynamic Directs the link editor to look for liblib.so (shared) files, and if
they are not found, to look for liblib.a (static, nonshared) files. Use
this option if you want shared library bindings for linking.
static Directs the link editor to look only for liblib.a (static, nonshared)
files. Use this option if you want nonshared library bindings for
linking.
symbolic See the ld(1) man page.
Defaults
If –B is not specified, –Bdynamic is assumed.
Interactions
To link the C++ default libraries statically, use the –staticlib option.
The -Bstatic and -Bdynamic options affect the linking of the libraries that are
provided by default. To ensure that the default libraries are linked dynamically, the
last use of –B should be –Bdynamic.
In a 64-bit environment, many system libraries are available only as shared dynamic
libraries. These include libm.so and libc.so (libm.a and libc.a are not
provided). As a result, -Bstatic and -dn may cause linking errors in 64-bit Solaris
environments. Applications must link with the dynamic libraries in these cases.
Examples
The following compiler command links libfoo.a even if libfoo.so exists; all other
libraries are linked dynamically:
See also
–nolib, –staticlib, ld(1), Section 12.5 “Statically Linking Standard Libraries,”
Linker and Libraries Guide
A.2.5 –c
Compile only; produce object .o files, but suppress linking.
This option directs the CC driver to suppress linking with ld and produce a .o file
for each source file. If you specify only one source file on the command line, then
you can explicitly name the object file with the -o option.
Examples
If you enter CC -c x.cc, the x.o object file is generated.
Warnings
When the compiler produces object code for an input file (.c, .i), the compiler
always produces a .o file in the working directory. If you suppress the linking step,
the .o files are not removed.
See also
–o filename
A.2.7 –compat[={4|5}]
Sets the major release compatibility mode of the compiler. This option controls the
__SUNPRO_CC_COMPAT and __cplusplus macros.
The C++ compiler has two principal modes. The compatibility mode accepts ARM
semantics and language defined by the 4.2 compiler. The standard mode accepts
constructs according to the ANSI/ISO standard. These two modes are incompatible
with each other because the ANSI/ISO standard forces significant, incompatible
changes in name mangling, vtable layout, and other ABI details. These two modes
are differentiated by the –compat option as shown in the following values.
Values
The -compat option can have the following values.
Value Meaning
Defaults
If the –compat option is not specified, –compat=5 is assumed.
Interactions
You cannot use the standard libraries in compatibility mode (-compat[=4]).
Warnings
When building a shared library in compatibility mode (-compat[=4]), do not use
-Bsymbolic if the library has exceptions in it. Exceptions that should be caught might
be missed.
See also
C++ Migration Guide
A.2.8 +d
Does not expand C++ inline functions.
Under the C++ language rules, a C++ inline function is a function for which one of
the following statements is true.
■ The function is defined using the inline keyword,
■ The function is defined (not just declared) inside a class definition
■ The function is a compiler-generated class member function
Examples
By default, the compiler may inline the functions f() and memf2() in the following
code example. In addition, the class has a default compiler-generated constructor
and destructor that the compiler may inline. When you use +d, the compiler will not
inline f()and C::mf2(), the constructor, and the destructor.
Interactions
This option is automatically turned on when you specify –g, the debugging option.
The +d option has no effect on the automatic inlining that is performed when you
use -xO4 or -xO5.
See also
–g0, –g
Interactions
If +p is used, sun, unix, sparc, and i386 are not defined.
See also
–U
A.2.10 –d{y|n}
Allows or disallows dynamic libraries for the entire executable.
Values
Value Meaning
Interactions
In a 64-bit environment, many system libraries are available only as shared dynamic
libraries. These include libm.so and libc.so (libm.a and libc.a are not
provided). As a result, -Bstatic and -dn may cause linking errors in 64-bit Solaris
environments. Applications must link with the dynamic libraries in these cases.
See also
ld(1), Linker and Libraries Guide
A.2.11 –dalign
SPARC: Generates double-word load and store instructions whenever possible
for improved performance.
This option assumes that all double type data are double-word aligned.
Warnings
If you compile one program unit with –dalign, compile all units of a program with
-dalign, or you might get unexpected results.
A.2.12 –dryrun
Shows the subcommands built by driver, but does not compile.
This option directs the driver CC to show, but not execute, the subcommands
constructed by the compilation driver.
Directs the CC driver to run only the preprocessor on C++ source files, and to send
the result to stdout (standard output). No compilation is done; no .o files are
generated.
Examples
This option is useful for determining the changes made by the preprocessor. For
example, the following program, foo.cc, generates the output shown in
CODE EXAMPLE A-2.
int main () {
int x;
x=power(2, 10);
}
int main ( ) {
int x ;
x = power ( 2 , 10 ) ;
}
See also
–P
A.2.14 +e{0|1}
Controls virtual table generation in compatibility mode (-compat[=4]). Invalid and
ignored when in standard mode (the default mode).
Values
The +e option can have the following values.
Value Meaning
Interactions
When you compile with this option, also use the –features=no%except option.
Otherwise, the compiler generates virtual tables for internal types used in exception
handling.
If template classes have virtual functions, ensuring that the compiler generates all
needed virtual tables, but does not duplicate these tables, might not be possible.
See also
C++ Migration Guide
Expansions
This option provides near maximum performance for many applications by
expanding to the following compilation options.
Option SPARC IA
–dalign X -
–fns X -
–fsimple=2 X -
–ftrap=%none X X
–nofstore - X
–xlibmil X X
–xlibmopt X X
–xO5 X X
–xtarget=native X X
-xbuiltin=%all X X
Interactions
The -fast macro expands into compilation options that may affect other specified
options. For example, in the following command, the expansion of the -fast macro
includes -xtarget=native which reverts -xarch to one of the 32-bit architecture
options.
Incorrect:
The code generation option, the optimization level, the optimization of built-in
functions, and the use of inline template files can be overridden by subsequent
options (see examples). The optimization level that you specify overrides a
previously set optimization level.
The –fast option includes –fns –ftrap=%none; that is, this option turns off all
trapping.
Examples
The following compiler command results in an optimization level of –xO3.
Warnings
If you compile and link in separate steps, the -fast option must appear in both the
compile command and the link command.
Code that is compiled with the -fast option is not portable. For example, using the
following command on an UltraSPARC III system generates a binary that will not
execute on an UltraSPARC II system.
Do not use this option for programs that depend on IEEE standard floating-point
arithmetic; different numerical results, premature program termination, or
unexpected SIGFPE signals can occur.
Note – In previous SPARC releases, the –fast macro option included –fnonstd;
now it does not. Nonstandard floating-point mode is not initialized by –fast. See
the Numerical Computation Guide, ieee_sun(3M).
See also
-dalign, -fns, -fsimple, -ftrap=%none, -xlibmil, -nofstore, -xO5,
-xlibmopt, -xtarget=native
A.2.16 –features=a[,a...]
Enables/disables various C++ language features named in a comma-separated list.
Values
In both compatibility mode (-compat[=4]) and standard mode (the default mode),
a can have the following values.
TABLE A-5 -features Options for Compatibility Mode and Standard Mode
Value of a Meaning
%all All the -features options that are valid for the specified mode.
[no%]altspell [Do not] Recognize alternative token spellings (for example,
“and” for “&&”). The default is no%altspell in compatibility
mode and altspell in standard mode.
[no%]anachronisms [Do not] Allow anachronistic constructs. When disabled (that is,
-features=no%anachronisms), no anachronistic constructs are
allowed. The default is anachronisms.
[no%]bool [Do not] Allow the bool type and literals. When enabled, the
macro _BOOL=1. When not enabled, the macro is not defined. The
default is no%bool in compatibility mode and bool
in standard mode.
[no%]conststrings [Do not] Put literal strings in read-only memory. The default is
no%conststrings in compatibility mode and conststrings in
standard mode.
Value of a Meaning
[no%]except [Do not] Allow C++ exceptions. When C++ exceptions are
disabled (that is, -features=no%except), a throw-specification
on a function is accepted but ignored; the compiler does not
generate exception code. Note that the keywords try, throw, and
catch are always reserved. See Section 8.3 “Disabling
Exceptions.” The default is except.
[no%]export [Do not] Recognize the keyword export. The default is
no%export in compatibility mode and export in standard mode.
[no%]extensions [Do not] allow nonstandard code that is commonly accepted by
other C++ compilers. See Chapter 4 for an explanation of the
invalid code that is accepted by the compiler when you use the
-features=extensions option. The default is
no%extensions.
[no%]iddollar [Do not] Allow a $ symbol as a noninitial identifier character. The
default is no%iddollar.
[no%]localfor [Do not] Use new local-scope rules for the for statement. The
default is no%localfor in compatibility mode and localfor in
standard mode.
[no%]mutable [Do not] Recognize the keyword mutable. The default is
no%mutable in compatibility mode and mutable in standard
mode.
[no%]split_init [Do not] Put initializers for nonlocal static objects into individual
functions. When you use -features=no%split_init, the
compiler puts all the initializers in one function. Using
-features=no%split_init minimizes code size at the possible
expense of compile time. The default is split_init.
[no%]transitions [Do not] allow ARM language constructs that are problematic in
standard C++ and that may cause the program to behave
differently than expected or that may be rejected by future
compilers. When you use -features=no%transitions, the
compiler treats these as errors. When you use
-features=transitions in standard mode, the compiler issues
warnings about these constructs instead of error messages. When
you use -features=transitions in compatibility mode
(-compat[=4]), the compiler displays the warnings about these
constructs only if +w or +w2 is specified. The following constructs
are considered to be transition errors: redefining a template after it
was used, omitting the typename directive when it is needed in a
template definition, and implicitly declaring type int. The set of
transition errors may change in a future release. The default is
transitions.
%none Turn off all the features that can be turned off for the specified
mode.
Value of a Meaning
Value of a Meaning
–features=%none,anachronisms,except,split_init,transitions
–features=%all,no%iddollar,no%extensions
Interactions
This option accumulates instead of overrides.
Use of the following in standard mode (the default) is not compatible with the
standard libraries and headers:
■ no%bool
■ no%except
■ no%mutable
■ no%explicit
Interactions
This option accumulates instead of overrides.
Warnings
The behavior of a program might change when you use the -features=tmplife
option. Testing whether the program works both with and without the
-features=tmplife option is one way to test the program’s portability.
A.2.17 -filt[=filter[,filter...]]
Suppress the filtering that the compiler normally applies to linker error messages.
Defaults
If you do not specify the -filt option, or if you specify -filt without any values,
then the compiler assumes -filt=errors,names,returns.
// filt_demo.cc
class type {
public:
virtual ~type(); // no definition provided
};
int main()
{
type t;
}
When you compile the code without the -filt option, the compiler assumes
-filt=names,returns,errors and displays the standard output.
example% CC filt_demo.cc
Undefined first referenced
symbol in file
type::~type() filt_demo.o
type::__vtbl filt_demo.o
[Hint: try checking whether the first non-inlined, non-pure
virtual function of class type is defined]
The following command suppresses the demangling of the of the C++ mangled
linker names and suppresses the C++ explanations of linker errors.
A.2.18 –flags
Same as –xhelp=flags.
A.2.19 –fnonstd
Causes hardware traps to be enabled for floating-point overflow, division by zero,
and invalid operations exceptions. These results are converted into SIGFPE signals;
if the program has no SIGFPE handler, it terminates with a memory dump (unless
you limit the core dump size to 0).
Defaults
If –fnonstd is not specified, IEEE 754 floating-point arithmetic exceptions do not
abort the program, and underflows are gradual.
Expansions
IA: -fnonstd expands to -ftrap=common.
See also
–fns, –ftrap=common, Numerical Computation Guide.
A.2.20 –fns[={yes|no}]
SPARC: Enables/disables the SPARC nonstandard floating-point mode.
-fns=yes (or -fns) causes the nonstandard floating point mode to be enabled
when a program begins execution.
On those SPARC devices that do not support gradual underflow and subnormal
numbers in hardware, -fns=yes (or -fns) can significantly improve the
performance of some programs.
Values
The -fns option can have the following values.
Value Meaning
Defaults
If -fns is not specified, the nonstandard floating point mode is not enabled
automatically. Standard IEEE 754 floating-point computation takes place—that is,
underflows are gradual.
Examples
In the following example, -fast expands to several options, one of which is
-fns=yes which selects nonstandard floating-point mode. The subsequent
-fns=no option overrides the initial setting and selects floating-point mode.
If you compile one routine with the -fns option, then compile all routines of the
program with the –fns option; otherwise, you might get unexpected results.
This option is effective only on SPARC devices, and only if used when compiling the
main program. On IA devices, the option is ignored.
Use of the –fns=yes (or -fns) option might generate the following message if your
program experiences a floating-point error normally managed by the IEEE floating-
point trap handlers:
See also
Numerical Computation Guide, ieee_sun(3M)
A.2.21 –fprecision=p
IA: Sets the non-default floating-point precision mode.
The –fprecision option sets the rounding precision mode bits in the Floating
Point Control Word. These bits control the precision to which the results of basic
arithmetic operations (add, subtract, multiply, divide, and square root) are rounded.
Values
p must be one of the following values.
Value of p Meaning
If p is single or double, this option causes the rounding precision mode to be set
to single or double precision, respectively, when a program begins execution. If p
is extended or the –fprecision option is not used, the rounding precision mode
remains at the extended precision.
The nominal precision of the float type is single. The nominal precision of the
long double type is extended.
Defaults
When the –fprecision option is not specified, the rounding precision mode
defaults to extended.
Warnings
This option is effective only on IA devices and only if used when compiling the
main program. On SPARC devices, this option is ignored.
A.2.22 –fround=r
Sets the IEEE rounding mode in effect at startup.
The meanings are the same as those for the ieee_flags subroutine, which can be
used to change the mode at runtime.
Value of r Meaning
nearest Rounds towards the nearest number and breaks ties to even numbers.
tozero Rounds to zero.
negative Rounds to negative infinity.
positive Rounds to positive infinity.
Defaults
When the –fround option is not specified, the rounding mode defaults to
-fround=nearest.
Warnings
If you compile one routine with –fround=r, compile all routines of the program
with the same –fround=r option; otherwise, you might get unexpected results.
This option is effective only if used when compiling the main program.
A.2.23 –fsimple[=n]
Selects floating-point optimization preferences.
Value of n Meaning
Defaults
If –fsimple is not designated, the compiler uses -fsimple=0.
Interactions
-fast implies –fsimple=2.
Warnings
This option can break IEEE 754 conformance.
A.2.24 –fstore
IA: This option causes the compiler to convert the value of a floating-point
expression or function to the type on the left side of an assignment rather than leave
the value in a register when the following is true:
■ The expression or function is assigned to a variable.
■ The expression is cast to a shorter floating-point type.
Warnings
Due to roundoffs and truncation, the results can be different from those that are
generated from the register values.
See also
–nofstore
A.2.25 -ftrap=t[,t...]
Sets the IEEE trapping mode in effect at startup.
This option sets the IEEE 754 trapping modes that are established at program
initialization, but does not install a SIGFPE handler. You can use ieee_handler to
simultaneously enable traps and install a SIGFPE handler. When more than one
value is used, the list is processed sequentially from left to right.
Value of t Meaning
Note that the [no%] form of the option is used only to modify the meaning of the
%all and common values, and must be used with one of these values, as shown in
the example. The [no%] form of the option by itself does not explicitly cause a
particular trap to be disabled.
If you want to enable the IEEE traps, -ftrap=common is the recommended setting.
Defaults
If –ftrap is not specified, the –ftrap=%none value is assumed. (Traps are not
enabled automatically.)
Examples
When one or more terms are given, the list is processed sequentially from left to
right, thus –ftrap=%all,no%inexact means to set all traps except inexact.
Interactions
The mode can be changed at runtime with ieee_handler(3M).
Use the -ftrap=inexact trap with caution. Use of –ftrap=inexact results in the
trap being issued whenever a floating-point value cannot be represented exactly. For
example, the following statement generates this condition:
x = 1.0 / 3.0;
This option is effective only if used when compiling the main program. Be cautious
when using this option. If you wish to enable the IEEE traps, use –ftrap=common.
See also
ieee_handler(3M) man page
A.2.26 –G
Build a dynamic shared library instead of an executable file.
All source files specified in the command line are compiled with -Kpic by default.
When building a shared library that uses templates, it is necessary in most cases to
include in the shared library those template functions that are instantiated in the
template data base. Using this option automatically adds those templates to the
shared library as needed.
Interactions
The following options are passed to ld if –c (the compile-only option) is not
specified:
■ –dy
■ –G
■ –R
Warnings
Do not use ld -G to build shared libraries; use CC -G. The CC driver automatically
passes several options to ld that are needed for C++.
See also
-dy, -Kpic, -xcode=pic13, -xildoff, –ztext, ld(1) man page, Section 16.3
“Building Dynamic (Shared) Libraries”
A.2.27 –g
Instructs both the compiler and the linker to prepare the file or program for
debugging and for performance analysis.
Interactions
If you use this option with –xOlevel (or its equivalent options, such as -O), you will
get limited debugging information. For more information, see Section A.2.127
“-xOlevel.”
If you use this option and the optimization level is -xO3 or lower, the compiler
provides best-effort symbolic information with almost full optimization. Tail-call
optimization and back-end inlining are disabled.
If you use this option and the optimization level is -xO4 or higher, the compiler
provides best-effort symbolic information with full optimization.
This option makes –xildon the default incremental linker option in order to speed
up the compile-edit-debug cycle.
To use the full capabilities of the Sun WorkShop 6 Performance Analyzer, compile
with the -g option. While some performance analysis features do not require -g,
you must compile with -g to view annotated source, some function level
information, and compiler commentary messages. See the analyzer(1) man page
and “Compiling Your Program for Data Collection and Analysis” in Analyzing
Program Performance With Sun WorkShop for more information.
The commentary messages that are generated with -g describe the optimizations
and transformations that the compiler made while compiling your program. Use the
er_src(1) command to display the messages, which are interleaved with the source
code.
Warnings
If you compile and link your program in separate steps, then including the -g
option in one step and excluding it from the other step will not affect the correctness
of the program, but it will affect the ability to debug the program. Any module that
is not compiled with -g (or -g0), but is linked with -g (or -g0) will not be prepared
properly for debugging. Note that compiling the module that contains the function
main with the -g option (or the -g0 option) is usually necessary for debugging.
See also
+d, –g0, –xildoff, –xildon, –xs, analyzer(1) man page, er_src(1) man
page, ld(1) man page, Debugging a Program With dbx (for details about stabs),
Analyzing Program Performance With Sun WorkShop
A.2.28 –g0
Compiles and links for debugging, but does not disable inlining.
See also
+d, –g, –xildon, Debugging a Program With dbx
On the standard error output (stderr), this option prints, one per line, the path
name of each #include file contained in the current compilation.
The compile-time loader assigns the specified name to the shared dynamic library
you are creating. It records the name in the library file as the intrinsic name of the
library. If there is no –hname option, then no intrinsic name is recorded in the library
file.
Every executable file has a list of shared library files that are needed. When the
runtime linker links the library into an executable file, the linker copies the intrinsic
name from the library into that list of needed shared library files. If there is no
intrinsic name of a shared library, then the linker copies the path of the shared
library file instead.
Examples
A.2.31 –help
Same as -xhelp=flags.
A.2.32 -Ipathname
Add pathname to the #include file search path.
This option adds pathname to the list of directories that are searched for #include
files with relative file names (those that do not begin with a slash).
The compiler searches for bracket-included files (of the form #include <foo.h>) in
this order.
Note – If the spelling matches the name of a standard header file, also refer to
Section 12.7.5 “Standard Header Implementation” on page 12-15.
Interactions
The -I- option allows you to override the default search rules.
If you specify -library=no%Cstd, then the compiler does not include in its search
path the compiler-provided header files that are associated with the C++ standard
libraries. See Section 12.7 “Replacing the C++ Standard Library.”
If –ptipath is not used, the compiler looks for template files in –Ipathname.
See also
-I-
For include files of the form #include "foo.h", search the directories in the
following order.
1. The directories named with -I options (both before and after -I-)
2. The directories for compiler-provided C++ header files, ANSI C header files, and
special-purpose files
For include files of the form #include <foo.h>, search the directories in the
following order.
2. The directories for compiler-provided C++ header files, ANSI C header files, and
special-purpose files
Note – If the name of the include file matches the name of a standard header, also
refer to Section 12.7.5 “Standard Header Implementation.”
Examples
The following example shows the results of using -I- when compiling prog.cc.
The following command shows the default behavior of searching the current
directory (the directory of the including file) for include statements of the form
#include "foo.h". When processing the #include "c.h" statement in inc/a.h,
the compiler includes the c.h header file from the inc subdirectory. When
processing the #include "c.h" statement in prog.cc, the compiler includes the
c.h file from the directory containing prog.cc. Note that the -H option instructs
the compiler to print the paths of the included files.
The next command shows the effect of the -I- option. The compiler does not look in
the including directory first when it processes statements of the form #include
"foo.h". Instead, it searches the directories named by the -I options in the order
Interactions
When -I- appears in the command line, the compiler never searches the current
directory, unless the directory is listed explicitly in a -I directive. This effect applies
even for include statements of the form #include "foo.h".
Warnings
Only the first -I- in a command line causes the described behavior.
A.2.34 –i
Tells the linker, ld, to ignore any LD_LIBRARY_PATH setting.
A.2.35 -inline
Same as -xinline.
A.2.36 –instances=a
Controls the placement and linkage of template instances.
Value of a Meaning
explicit Places explicitly instantiated instances into the current object file and
gives them global linkage. Does not generate any other needed
instances.
extern Places all needed instances into the template repository and gives
them global linkage. (If an instance in the repository is out of date, it
is reinstantiated.)
global Places all needed instances into the current object file and gives them
global linkage.
semiexplicit Places explicitly instantiated instances into the current object file and
gives them global linkage. Places all instances needed by the explicit
instances into the current object file and gives them static linkage.
Does not generate any other needed instances.
static Places all needed instances into the current object file and gives them
static linkage.
Defaults
If –instances is not specified, –instances=extern is assumed.
See also
Section 7.3 “Template Instance Placement and Linkage”
A.2.37 –keeptmp
Retains temporary files created during compilation.
See also
–v, –verbose
Use this option to compile source files when building a shared library. Each
reference to a global datum is generated as a dereference of a pointer in the global
offset table. Each function call is generated in pc-relative addressing mode through a
procedure linkage table.
A.2.39 –Kpic
SPARC: Same as –xcode=pic13.
Use this option to compile source files when building a shared library. Each
reference to a global datum is generated as a dereference of a pointer in the global
offset table. Each function call is generated in pc-relative addressing mode through a
procedure linkage table.
A.2.40 –Lpath
Adds path to list of directories to search for libraries.
This option is passed to ld. The directory that is named by path is searched before
compiler-provided directories.
Interactions
This option accumulates instead of overrides.
A.2.41 –llib
Adds library liblib.a or liblib.so to the linker’s list of search libraries.
This option is passed to ld. Normal libraries have names such as liblib.a or
liblib.so, where the lib and .a or .so parts are required. You should specify the
lib part with this option. Put as many libraries as you want on a single command
line; they are searched in the order specified with –Ldir.
Interactions
This option accumulates instead of overrides.
It is always safer to put –lx after the list of sources and objects to insure that libraries
are searched in the correct order.
Warnings
To ensure proper library linking order, you must use -mt, rather than -lthread, to
link with libthread.
If you are using POSIX threads, you must link with the -mt and -lpthread
options. The -mt option is necessary because libCrun (standard mode) and libC
(compatibility mode) need libthread for a multithreaded application.
See also
–Ldir, -mt, Chapter 12, and Tools.h++ Class Library Reference
A.2.42 –libmieee
Same as –xlibmieee.
A.2.43 –libmil
Same as –xlibmil.
A.2.44 -library=l[,l...]
Incorporates specified CC-provided libraries into compilation and linking.
Value of l Meaning
For standard mode (the default mode), l must be one of the following:
Value of l Meaning
Value of l Meaning
Defaults
■ Compatibility mode (–compat[=4])
■ If –library is not specified, -library=libC is assumed.
■ The libC library always is included unless it is specifically excluded using
-library=no%libC.
■ Standard mode (the default mode)
■ If –library is not specified, -library=libCrun,Cstd is assumed.
■ The libCstd library always is included unless it is specifically excluded using
-library=%none or -library=no%Cstd.
■ The libCrun library always is included unless it is specifically excluded using
-library=no%Crun.
example% CC -library=%none
example% CC –library=rwtools7,iostream
example% CC -library=rwtools7_std
Interactions
If a library is specified with -library, the proper –I paths are set during
compilation. The proper –L,–Y P, –R paths and –l options are set during linking.
When you use the interval arithmetic libraries, you must include one of the
following libraries: libC, libCstd, or libiostream.
Use of the -library option ensures that the -l options for the specified libraries
are emitted in the right order. For example, the -l options are passed to ld in the
order -lrwtool -liostream for both -library=rwtools7,iostream and
-library=iostream,rwtools7.
The specified libraries are linked before the system support libraries are linked.
If you include both libCstd and libiostream, you must be careful to not use the
old and new forms of iostreams (for example, cout and std::cout) within a
program to access the same file. Mixing standard iostreams and classic iostreams in
the same program is likely to cause problems if the same file is accessed from both
classic and standard iostream code.
Programs linking neither libC nor libCrun might not use all features of the C++
language.
Warnings
If you compile and link in separate steps, the set of -library options that appear in
the compile command must appear in the link command.
The set of libraries is not stable and might change from release to release.
For information on using the -library=no%cstd option to enable use of your own
C++ standard library, see Section 12.7 “Replacing the C++ Standard Library” on
page 12-13.
A.2.45 -mc
Removes duplicate strings from the .comment section of the object file. When you
use the -mc option, the mcs -c command is invoked.
A.2.46 –migration
Explains where to get information about migrating source code that was built for
earlier versions of the compiler.
A.2.47 –misalign
SPARC: Permits misaligned data, which would otherwise generate an error, in
memory. This is shown in the following code:
char b[100];
int f(int * ar) {
return *(int *) (b +2) + *ar;
}
This option informs the compiler that some data in your program is not properly
aligned. Thus, very conservative loads and stores must be used for any data that
might be misaligned, that is, one byte at a time. Using this option may cause
significant degradation in runtime performance. The amount of degradation is
application dependent.
Warnings
If possible, do not link aligned and misaligned parts of the program.
If compilation and linking are performed in separate steps, the –misalign option
must appear in both the compile and link commands.
A.2.48 -mr[,string]
Removes all strings from the .comment section of the object file and, if string is
supplied, places string in that section. When you use this option, the command
mcs -d [-a string] is invoked.
Interactions
This option is not valid when either -S, -xsbfast, or -sbfast is specified.
A.2.49 –mt
Compiles and links for multithreaded code.
This option:
■ Passes -D_REENTRANT to the preprocessor
■ Passes -lthread in the correct order to ld
■ Ensures that, for standard mode (the default mode), libthread is linked before
libCrun
■ Ensures that, for compatibility mode (-compat), libthread is linked before
libC
Warnings
To ensure proper library linking order, you must use this option, rather than
-lthread, to link with libthread.
If you are using POSIX threads, you must link with the -mt and -lpthread
options. The -mt option is necessary because libCrun (standard mode) and libC
(compatibility mode) need libthread for a multithreaded application.
If you compile and link in separate steps and you compile with -mt, be sure to link
with -mt, as shown in the following example, or you might get unexpected results.
If you are mixing parallel Fortran objects with C++ objects, the link line must specify
the -mt option.
See also
–xnolib, Chapter 11, Multithreaded Programming Guide, Linker and Libraries Guide
A.2.50 –native
Same as –xtarget=native.
A.2.51 –noex
Same as –features=no%except.
This option does not force the value of a floating-point expression or function to the
type on the left side of an assignment, but leaves the value in a register when either
of the following are true:
■ The expression or function is assigned to a variable
or
■ The expression or function is cast to a shorter floating-point type
See also
–fstore
A.2.53 –nolib
Same as –xnolib.
A.2.54 –nolibmil
Same as –xnolibmil.
A.2.55 –noqueue
Disables license queueing.
If no license is available, this option returns without queuing your request and
without compiling. A nonzero status is returned for testing makefiles.
A.2.56 –norunpath
Does not build a runtime search path for shared libraries into the executable.
If an executable file uses shared libraries, then the compiler normally builds in a
path that points the runtime linker to those shared libraries. To do so, the compiler
passes the –R option to ld. The path depends on the directory where you have
installed the compiler.
Interactions
If you use any shared libraries under the compiler installed area (the default location
is /opt/SUNWspro/lib) and you also use –norunpath, then you should either use
the –R option at link time or set the environment variable LD_LIBRARY_PATH at
runtime to specify the location of the shared libraries. Doing so allows the runtime
linker to find the shared libraries.
A.2.57 –O
Same as –xO2.
A.2.58 –Olevel
Same as –xOlevel.
A.2.59 –o filename
Sets the name of the output file or the executable file to filename.
Interactions
When the compiler must store template instances, it stores them in the template
repository in the output file’s directory. For example, the following command writes
the object file to ./sub/a.o and writes template instances into the repository
contained within ./sub/SunWS_cache.
Warnings
The filename must have the appropriate suffix for the type of file to be produced by
the compilation. It cannot be the same file as the source file, since the CC driver does
not overwrite the source file.
A.2.60 +p
Ignore nonstandard preprocessor asserts.
Defaults
If +p is not present, the compiler recognizes nonstandard preprocessor asserts.
Interactions
If +p is used, the following macros are not defined:
■ sun
■ unix
■ sparc
■ i386
A.2.61 –P
Only preprocesses source; does not compile. (Outputs a file with a .i suffix)
This option does not include preprocessor-type line number information in the
output.
A.2.62 –p
Prepares object code to collect data for profiling with prof.
This option invokes a runtime recording mechanism that produces a mon.out file at
normal termination.
Warnings
If you compile and link in separate steps, the -p option must appear in both the
compile command and the link command. Including -p in one step and excluding it
from the other step will not affect the correctness of the program, but you will not be
able to do profiling.
See also
–xpg, -xprofile, analyzer(1) man page, Analyzing Program Performance With Sun
WorkShop.
A.2.63 –pentium
IA: Replace with –xtarget=pentium.
A.2.64 –pg
Same as –xpg.
A.2.65 -PIC
SPARC: Same as –xcode=pic32.
A.2.67 –pta
Same as –template=wholeclass.
A.2.68 –ptipath
Specifies an additional search directory for template source.
This option is an alternative to the normal search path set by –Ipathname. If the
-ptipath option is used, the compiler looks for template definition files on this path
and ignores the –Ipathname option.
Interactions
This option accumulates instead of overrides.
See also
–Ipathname
A.2.69 –pto
Same as –instances=static.
A.2.70 –ptr
This option is obsolete and is ignored by the compiler.
See also
For information about repository directories, see Section 7.4 “The Template
Repository.”
A.2.71 –ptv
Same as –verbose=template.
Values
phase must have one of the following values.
SPARC IA
ccfe ccfe
iropt cg386
cg codegen
CClink CClink
ld ld
Warnings
Be careful to avoid unintended effects. For example,
is interpreted as
A.2.74 –qp
Same as –p.
Suffix Meaning
A.2.77 –Rpathname[:pathname...]
Builds dynamic library search paths into the executable file.
Defaults
If the -R option is not present, the library search path that is recorded in the output
object and passed to the runtime linker depends upon the target architecture
instruction specified by the -xarch option (when -xarch is not present,
-xarch=generic is assumed).
See also
–norunpath, Linker and Libraries Guide
A.2.78 –readme
Same as -xhelp=readme.
A.2.79 –S
Compiles and generates only assembly code.
This option causes the CC driver to compile the program and output an assembly
source file, without assembling the program. The assembly source file is named with
a .s suffix.
A.2.80 –s
Strips the symbol table from the executable file.
This option removes all symbol information from output executable files. This
option is passed to ld.
A.2.81 –sb
Replace with –xsb.
A.2.82 –sbfast
Same as –xsbfast.
Values
l must be one of the following values.
Value of l Meaning
[no%]library [Do not] link library statically. The valid values for library are all the valid
values for -library (except %all and %none), all the valid values for
-xlang, and interval (to be used in conjunction with -xia).
%all Statically link all the libraries specified in the -library option, all the
libraries specified in the -xlang option, and, if -xia is specified in the
command line, the interval libraries.
%none Link no libraries specified in the -library option and the -xlang
option statically. If -xia is specified in the command line, link no
interval libraries statically.
Defaults
If –staticlib is not specified, –staticlib=%none is assumed.
Examples
The following command line links libCrun statically because Crun is a default
value for –library:
However, the following command line does not link libgc because libgc is not
linked unless explicitly specified with the -library option:
With the following command, the librwtool library is linked dynamically. Because
librwtool is not a default library and is not selected using the -library option,
-staticlib has no effect:
This command will link the Sun Performance Libraries dynamically because
-library=sunperf must be used in conjunction with -staticlib=sunperf in
order for the -staticlib option to have an effect on the linking of these libraries:
Interactions
This option accumulates instead of overrides.
The -staticlib option only works for the C++ libraries that are selected explicitly
with the -xia option, the -xlang option, and the -library option, in addition to
the C++ libraries that are selected implicitly by default. In compatibility mode
(-compat=[4]), libC is selected by default. In standard mode (the default mode),
Cstd and Crun are selected by default.
See also
-library, Section 12.5 “Statically Linking Standard Libraries”
A.2.84 –temp=path
Defines the directory for temporary files.
This option sets the path name of the directory for storing the temporary files that
are generated during the compilation process.
See also
–keeptmp
A.2.85 –template=opt[,opt...]
Enables/disables various template options.
Values
opt must be one of the following values.
Value of w Meaning
[no%]wholeclass [Do not] Instantiate a whole template class, rather than only those
functions that are used. You must reference at least one member of
the class; otherwise, the compiler does not instantiate any members
for the class.
[no%]extdef [Do not] Search for template definitions in separate source files.
See also
Section 6.3.2 “Whole-Class Instantiation”, Section 7.5 “Template Definition
Searching”
A.2.86 –time
Same as –xtime.
A.2.87 –Uname
Deletes initial definition of the preprocessor symbol name.
This option removes any initial definition of the macro symbol name created by -D
on the command line including those implicitly placed there by the CC driver. This
option has no effect on any other predefined macros, nor on macro definitions in
source files.
To see the -D options that are placed on the command line by the CC driver, add the
-dryrun option to your command line.
Examples
The following command undefines the predefined symbol __sun. Preprocessor
statements in foo.cc such as #ifdef(__sun) will sense that the symbol is
undefined.
Interactions
You can specify multiple -U options on the command line.
See also
-D
A.2.88 –unroll=n
Same as –xunroll=n.
A.2.89 –V
Same as –verbose=version.
A.2.90 –v
Same as –verbose=diags.
A.2.91 –vdelx
Compatibility mode only (–compat[=4]):
For expressions using delete[], this option generates a call to the runtime library
function _vector_deletex_ instead of generating a call to _vector_delete_.
The function _vector_delete_ takes two arguments: the pointer to be deleted and
the size of each array element.
Default
The compiler generates a call to _vector_delete_ for expressions using
delete[].
A.2.92 –verbose=v[,v...]
Controls compiler verbosity.
Values
v must be one of the following values.
Value of v Meaning
[no%]diags [Do not] Print the command line for each compilation pass.
[no%]template [Do not] Turn on the template instantiation verbose mode
(sometimes called the “verify” mode). The verbose mode displays
each phase of instantiation as it occurs during compilation.
[no%]version [Do not] Direct the CC driver to print the names and version
numbers of the programs it invokes.
%all Invokes all of the above.
%none -verbose=%none is the same as
-verbose=no%template,no%diags,no%version.
Defaults
If –verbose is not specified, –verbose=%none is assumed.
Interactions
This option accumulates instead of overrides.
This option generates additional warnings about questionable constructs that are:
■ Nonportable
■ Likely to be mistakes
■ Inefficient
Defaults
If +w is not specified, the compiler warns about constructs that are almost certainly
problems.
Interactions
Some C++ standard headers result in warnings when compiled with +w.
See also
–w, +w2
A.2.94 +w2
Emits all the warnings emitted by +w plus warnings about technical violations that
are probably harmless, but that might reduce the maximum portability of your
program.
Warnings
Some Solaris and C++ standard header files result in warnings when compiled with
+w2.
See also
+w
This option causes the compiler not to print warning messages. However, some
warnings, particularly warnings regarding serious anachronisms, cannot be
suppressed.
See also
+w
A.2.96 –xa
Generates code for profiling.
If set at compile time, the TCOVDIR environment variable specifies the directory
where the coverage (.d) files are located. If this variable is not set, then the coverage
(.d) files remain in the same directory as the source files.
Use this option only for backward compatibility with old coverage files.
Interactions
The –xprofile=tcov option and the –xa option are compatible in a single
executable. That is, you can link a program that contains some files that have been
compiled with –xprofile=tcov, and others that have been compiled with –xa.
You cannot compile a single file with both options.
Warnings
If you compile and link in separate steps and you compile with -xa, be sure to link
with –xa, or you might get unexpected results.
See also
–xprofile=tcov, tcov(1) man page, Analyzing Program Performance With Sun
WorkShop
When building a C++ archive that uses templates, it is necessary in most cases to
include in the archive those template functions that are instantiated in the template
database. Using this option automatically adds those templates to the archive as
needed.
Examples
The following command line archives the template functions contained in the library
and object files.
Warnings
Do not add .o files from the template database on the command line.
Do not use the ar command directly for building archives. Use CC –xar to ensure
that template instantiations are automatically included in the archive.
See also
Chapter 16
A.2.98 –xarch=isa
Specifies the target instruction set architecture (ISA).
This option limits the code generated by the compiler to the instructions of the
specified instruction set architecture by allowing only the specified set of
instructions. This option does not guarantee use of any target–specific instructions.
However, use of this option may affect the portability of a binary program.
TABLE A-11 gives the details for each of the -xarch keywords on SPARC platforms.
Example: SPARCstation 10
• This option enables the compiler to generate code for good performance
on the V8plus ISA.
• The resulting object code is in SPARC-V8+ ELF32 format and only
executes in a Solaris UltraSPARC environment—it does not run on a V7 or
V8 processor.
• This option enables the compiler to generate code for good performance
on the UltraSPARC architecture, but limited to the 32–bit subset defined
by the V8plus specification.
• The resulting object code is in SPARC-V8+ ELF32 format and only
executes in a Solaris UltraSPARC environment—it does not run on a V7 or
V8 processor.
• The resulting .o object files are in ELF64 format and can only be linked
with other SPARC-V9 object files in the same format.
• The resulting executable can only be run on an UltraSPARC processor
running a 64–bit enabled Solaris operating environment with the 64–bit
kernel.
• –xarch=v9 is only available when compiling in a 64–bit enabled Solaris
environment.
• The resulting .o object files are in ELF64 format and can only be linked
with other SPARC-V9 object files in the same format.
• The resulting executable can only be run on an UltraSPARC processor
running a 64–bit enabled Solaris operating environment with the 64–bit
kernel.
• –xarch=v9a is only available when compiling in a 64–bit enabled Solaris
operating environment.
v9b Compile for the SPARC-V9 ISA with UltraSPARC III extensions.
Adds UltraSPARC III extensions and VIS version 2.0 to the V9a version of
the SPARC-V9 ISA. Compiling with this option uses the best instruction set
for good performance in a Solaris UltraSPARC III environment.
• The resulting object code is in SPARC-V9 ELF64 format and can only be
linked with other SPARC-V9 object files in the same format.
• The resulting executable can only be run on an UltraSPARC III processor
running a 64–bit enabled Solaris operating environment with the 64–bit
kernel.
• –xarch=v9b is only available when compiling in a 64–bit enabled Solaris
operating environment.
For IA platforms:
TABLE A-12 gives the details for each of the -xarch keywords on IA platforms.
generic Compile for good performance on most systems. This is the default.
This option uses the best instruction set for good performance on most
processors without major performance degradation on any of them.
With each new release, the definition of “best” instruction set may be
adjusted, if appropriate.
386 generic and 386 are equivalent in this release.
pentium_pro 486 and pentium_pro are equivalent in this release.
Defaults
If –xarch=isa is not specified, –xarch=generic is assumed.
Interactions
Although this option can be used alone, it is part of the expansion of the -xtarget
option and may be used to override the –xarch value that is set by a specific
-xtarget option. For example, -xtarget=ultra2 expands to -xarch=v8plusa
-xchip=ultra2 -xcache=16/32/1:512/64/1. In the following command
-xarch=v8plusb overrides the -xarch=v8plusa that is set by the expansion of
-xtarget=ultra2.
A.2.99 -xbuiltin[={%all|%none}]
Enables or disables better optimization of standard library calls.
By default, the functions declared in standard library headers are treated as ordinary
functions by the compiler. However, some of those functions can be recognized as
“intrinsic” or “built-in” by the compiler. When treated as a built-in, the compiler can
generate more efficient code. For example, the compiler can recognize that some
functions have no side effects, and always return the same output given the same
input. Some functions can be generated inline directly by the compiler.
The -xbuiltin=%all option asks the compiler to recognize as many of the built-in
standard functions as possible. The exact list of recognized functions varies with the
version of the compiler code generator.
The -xbuiltin=%none option results in the default compiler behavior, and the
compiler does not do any special optimizations for built-in functions.
Defaults
If the -xbuiltin option is not specified, then the compiler assumes
-xbuiltin=%none.
Interactions
The expansion of the macro -fast includes -xbuiltin=%all.
Examples
The following compiler command requests special handling of the standard library
calls.
A.2.100 –xcache=c
SPARC: Defines cache properties for use by the optimizer.
This option specifies the cache properties that the optimizer can use. It does not
guarantee that any particular cache property is used.
Note – Although this option can be used alone, it is part of the expansion of the
-xtarget option; its primary use is to override a value supplied by the -xtarget
option.
Values
c must be one of the following values.
Value of c Meaning
Property Definition
Examples
–xcache=16/32/4:1024/32/1 specifies the following:
See also
–xtarget=t
A.2.101 -xcg89
Same as -xtarget=ss2.
Warnings
If you compile and link in separate steps and you compile with -xcg89, be sure to
link with the same option, or you might get unexpected results.
A.2.102 –xcg92
Same as -xtarget=ss1000.
Warnings
If you compile and link in separate steps and you compile with -xcg92, be sure to
link with the same option, or you might get unexpected results.
The –xchip option specifies timing properties by specifying the target processor.
This option affects:
■ The ordering of instructions—that is, scheduling
■ The way the compiler uses branches
■ The instructions to use in cases where semantically equivalent alternatives are
available
Note – Although this option can be used alone, it is part of the expansion of the
-xtarget option; its primary use is to override a value supplied by the -xtarget
option.
Values
c must be one of the following values.
Defaults
On most SPARC processors, generic is the default value that directs the compiler
to use the best timing properties for good performance without major performance
degradation on any of the processors.
A.2.104 –xcode=a
SPARC: Specifies the code address space.
Values
a must be one of the following values.
Value of a Meaning
abs32 Generates 32-bit absolute addresses, which are fast, but have limited
range. Code + data + bss size is limited to 2**32 bytes.
abs44 SPARC: Generates 44-bit absolute addresses, which have moderate
speed and moderate range. Code + data + bss size is limited to 2**44
bytes. Available only on 64-bit architectures:
–xarch={v9|v9a|v9b}
Value of a Meaning
abs64 SPARC: Generates 64-bit absolute addresses, which are slow, but
have full range. Available only on 64-bit architectures:
–xarch={v9|v9a|v9|generic64|native64}
pic13 Generates position-independent code (small model), which is fast,
but has limited range. Equivalent to –Kpic. Permits references to at
most 2**11 unique external symbols on 32-bit architectures; 2**10 on
64-bit.
pic32 Generates position-independent code (large model), which is slow,
but has full range. Equivalent to –KPIC. Permits references to at
most 2**30 unique external symbols on 32-bit architectures; 2**29 on
64-bit.
Defaults
For SPARC V8 and V7 processors, the default is –xcode=abs32.
Warnings
When you compile and link in separate steps, you must use the same -xarch option
in the compile step and the link step.
A.2.105 -xcrossfile[=n]
SPARC: Enables optimization and inlining across source files.
Values
n must be one of the following values.
Value of n Meaning
With -xcrossfile or -xcrossfile=1, the compiler analyzes all the files named
on the command line as if they had been concatenated into a single source file.
Defaults
If -xcrossfile is not specified, -xcrossfile=0 is assumed and no cross-file
optimizations or inlining are performed.
Interactions
The -xcrossfile option is effective only when it is used with -xO4 or -xO5.
Warnings
The files produced from this compilation are interdependent due to possible
inlining, and must be used as a unit when they are linked into a program. If any one
routine is changed and the files recompiled, they must all be recompiled. As a result,
using this option affects the construction of makefiles.
A.2.106 –xF
If you compile with the -xF option and then run the Analyzer, you can generate a
map file that shows an optimized order for the functions. A subsequent link to build
the executable file can be directed to use that map by using the linker –Mmapfile
option. It places each function from the executable file into a separate section.
Reordering the subprograms in memory is useful only when the application text
page fault time is consuming a large percentage of the application time. Otherwise,
reordering might not improve the overall performance of the application.
Interactions
The –xF option is only supported with –features=no%except (–noex).
A.2.107 –xhelp=flags
Displays a brief description of each compiler option.
A.2.108 –xhelp=readme
Displays contents of the online readme file.
The readme file is paged by the command specified in the environment variable,
PAGER. If PAGER is not set, the default paging command is more.
A.2.109 -xia
SPARC: Links the appropriate interval arithmetic libraries and sets a suitable
floating-point environment.
Note – The C++ interval arithmetic library is compatible with interval arithmetic as
implemented in the Fortran compiler.
Expansions
The -xia option is a macro that expands to -fsimple=0 -ftrap=%none -fns=no
-library=interval.
Interactions
To use the interval arithmetic libraries, include <suninterval.h>.
When you use the interval arithmetic libraries, you must include one of the
following libraries: libC, Cstd, or iostreams. See -library for information on
including these libraries.
C++ interval arithmetic is experimental and evolving. The specifics may change
from release to release.
See also
C++ Interval Arithmetic Programming Reference, Interval Arithmetic Solves Nonlinear
Problems While Providing Guaranteed Results
(http://www.sun.com/forte/info/features/intervals.html), -library
A.2.110 –xildoff
Turns off the incremental linker.
Defaults
This option is assumed if you do not use the –g option. It is also assumed if you do
use the –G option, or name any source file on the command line. Override this
default by using the -xildon option.
See also
–xildon, ild(1) man page, ld(1) man page, “Incremental Link Editor” in the C
User’s Guide
A.2.111 –xildon
Turns on the incremental linker.
This option is assumed if you use –g and not –G, and you do not name any source
file on the command line. Override this default by using the -xildoff option.
A.2.112 -xinline[=func_spec[,func_spec...]]
Specifies which user-written routines can be inlined by the optimizer at -xO3 levels
or higher.
Values
func_spec must be one of the following values.
Only routines in the file being compiled are considered for inlining unless you use
-xcrossfile[=1]. The optimizer decides which of these routines are appropriate
for inlining.
Defaults
If the -xinline option is not specified, the compiler assumes -xinline=%auto.
To strongly request the inlining of the function declared as int foo(), and to make
all other functions as the candidates for inlining, use
To strongly request the inlining of the function declared as int foo(), and to not allow
inlining of any other functions, use
Interactions
The -xinline option has no effect for optimization levels below -xO3. At -xO4 and
higher, the optimizer decides which functions should be inlined, and does so
without the -xinline option being specified. At -xO4 and higher, the compiler also
attempts to determine which functions will improve performance if they are inlined.
A routine is not inlined if any of the following conditions apply. No warnings will be
omitted.
■ Optimization is less than -xO3
■ The routine cannot be found
■ Inlining it is not profitable or safe
■ The source is not in the file being compiled, or, if you use -xcrossfile[=1], the
source is not in the files named on the command line
Warnings
If you force the inlining of a function with -xinline, you might actually diminish
performance.
The -xipo option is particularly useful when compiling and linking large multifile
applications. Object files compiled with this flag have analysis information compiled
within them that enables interprocedural analysis across source and precompiled
program files. However, analysis and optimization is limited to the object files
compiled with -xipo, and does not extend to object files on libraries.
Values
The -xipo option can have the following values.
Value Meaning
Defaults
If -xipo is not specified, -xipo=0 is assumed.
Examples
The following example compiles and links in the same step.
The optimizer performs crossfile inlining across all three source files. This is done in
the final link step, so the compilation of the source files need not all take place in a
single compilation and could be over a number of separate compilations, each
specifying the -xipo option.
The object files created in the compile steps have additional analysis information
compiled within them to permit crossfile optimizations to take place at the link step.
Interactions
The -xipo option requires at least optimization level -xO4.
You cannot use both the -xipo option and the -xcrossfile option in the same
compiler command line.
Warnings
When compiling and linking are performed in separate steps, -xipo must be
specified in both steps to be effective.
Objects that are compiled without -xipo can be linked freely with objects that are
compiled with -xipo.
Libraries do not participate in crossfile interprocedural analysis, even when they are
compiled with -xipo, as shown in this example.
The -xipo option generates significantly larger object files due to the additional
information needed to perform optimizations across files. However, this additional
information does not become part of the final executable binary file. Any increase in
the size of the executable program will be due to the additional optimizations
performed.
Values
language must be either f77, f90, or f95.
Interactions
The -xlang=f90 and -xlang=f95 options imply -library=f90, and the
-xlang=f77 option implies -library=f77. However, the -library=f77 and
-library=f90 options are not sufficient for mixed-language linking because only
the -xlang option ensures the proper runtime environment.
To determine which driver to use for mixed-language linking, use the following
language hierarchy:
1. C++
3. Fortran 77
When linking Fortran 95, Fortran 77, and C++ object files together, use the driver of
the highest language. For example, use the following C++ compiler command to link
C++ and Fortran 95 object files.
To link Fortran 95 and Fortran 77 object files, use the Fortran 95 driver, as follows.
You cannot use the -xlang option and the -xlic_lib option in the same compiler
command. If you are using -xlang and you need to link in the Sun Performance
Libraries, use -library=sunperf instead.
If you are mixing parallel Fortran objects with C++ objects, the link line must specify
the -mt flag.
See also
-library, -staticlib
A.2.115 –xlibmieee
Causes libm to return IEEE 754 values for math routines in exceptional cases.
See also
Numerical Computation Guide
A.2.116 –xlibmil
Inlines selected libm library routines for optimization.
There are inline templates for some of the libm library routines. This option selects
those inline templates that produce the fastest executables for the floating-point
option and platform currently being used.
Interactions
This option is implied by the –fast option.
See also
-fast, Numerical Computation Guide
This option uses a math routine library optimized for performance and usually
generates faster code. The results might be slightly different from those produced by
the normal math library; if so, they usually differ in the last bit.
The order on the command line for this library option is not significant.
Interactions
This option is implied by the –fast option.
See also
–fast, –xnolibmopt
A.2.118 –xlic_lib=sunperf
SPARC: Links in the Sun Performance Library™.
This option, like –l, should appear at the end of the command line, after source or
object files.
Interactions
You cannot use the -xlang option and the -xlic_lib option in the same compiler
command. If you are using -xlang and you need to link in the Sun Performance
Library, use -library=sunperf instead.
See also
-library and the performance_library readme
A.2.119 –xlicinfo
Shows license server information.
This option returns the license-server name and the user ID for each user who has a
license checked out.
A.2.120 –Xm
Same as –features=iddollar.
A.2.121 –xM
Outputs makefile dependency information.
#include "foo.h"
When foo.c is compiled with the -xM, the output includes the following line:
foo.o : foo.h
See also
make(1S) (for details about makefiles and dependencies)
A.2.122 -xM1
This option is the same as –xM, except that it does not report dependencies for the
/usr/include header files, and it does not report dependencies for compiler-
supplied header files.
A.2.123 –xMerge
SPARC: Merges the data segment with the text segment.
The data in the object file is read-only and is shared between processes, unless you
link with ld -N.
See also
ld(1) man page
A.2.124 –xnolib
Disables linking with default system libraries.
Normally, the compiler links with the system support libraries in the following
order:
■ Standard mode (default mode):
The order of the -l options is significant. The -lm, -lw, and -lcx options must
appear before -lc.
Note – If the -mt compiler option is specified, the compiler normally links with
-lthread just before it links with -lm.
To determine which system support libraries will be linked by default, compile with
the -dryrun option. For example, the output from the following command:
Examples
For minimal compilation to meet the C application binary interface (that is, a C++
program with only C support required), use:
■ Compatibility mode:
Interactions
Some static system libraries, such as libm.a and libc.a, are not available when
linking with -xarch=v9, -xarch=v9a or -xarch=v9b.
If you specify –xnolib, you must manually link all required system support
libraries in the given order. You must link the system support libraries last.
Warnings
Many C++ language features require the use of libC (compatibility mode) or
libCrun (standard mode).
This set of system support libraries is not stable and might change from release to
release.
See also
–library, –staticlib, –l
Use this option with –fast to override linking with the optimized math library.
A.2.126 –xnolibmopt
Does not use the math routine library.
Examples
Use this option after the –fast option on the command line, as in this example:
A.2.127 -xOlevel
Specifies optimization level. In general, program execution speed depends on the
level of optimization. The higher the level of optimization, the faster the speed.
If -xOlevel is not specified, only a very basic level of optimization (limited to local
common subexpression elimination and dead code analysis) is performed. A
program’s performance might improve significantly when it is compiled with an
optimization level. The use of –xO2 (or the equivalent options -O and -O2) is
recommended for most programs.
Generally, the higher the level of optimization with which a program is compiled,
the better the runtime performance. However, higher optimization levels can result
in increased compilation time and larger executable files.
In a few cases, –xO2 might perform better than the others, and –xO3 might
outperform –xO4. Try compiling with each level to see if you have one of these rare
cases.
If the optimizer runs out of memory, it tries to recover by retrying the current
procedure at a lower level of optimization. The optimizer resumes subsequent
procedures at the original level specified in the –xOlevel option.
There are five levels that you can use with –xO. The following sections describe how
they operate on the SPARC platform and the IA platform.
This level does not optimize references or definitions for external or indirect
variables.
Interactions
If you use -g or -g0 and the optimization level is -xO3 or lower, the compiler
provides best-effort symbolic information with almost full optimization. Tail-call
optimization and back-end inlining are disabled.
If you use -g or -g0 and the optimization level is -xO4 or higher, the compiler
provides best-effort symbolic information with full optimization.
Debugging with -g does not suppress –xOlevel, but –xOlevel limits –g in certain
ways. For example, the –xOlevel options reduce the utility of debugging so that you
cannot display variables from dbx, but you can still use the dbx where command to
get a symbolic traceback. For more information, see Debugging a Program With dbx.
The -xinline option has no effect for optimization levels below -xO3. At -xO4, the
optimizer decides which functions should be inlined, and does so regardless of
whether you specify the -xinline option. At -xO4, the compiler also attempts to
determine which functions will improve performance if they are inlined. If you force
the inlining of a function with -xinline, you might actually diminish performance.
To prevent this degradation from taking place, use the limit command to limit the
amount of virtual memory available to a single process (see the csh(1) man page).
For example, to limit virtual memory to 16 megabytes:
The limit cannot be greater than the total available swap space of the machine, and
should be small enough to permit normal use of the machine while a large
compilation is in progress.
The best setting for data size depends on the degree of optimization requested, the
amount of real memory, and virtual memory available.
See also
–fast, -xcrossfile=n, –xprofile=p, csh(1) man page
A.2.128 –xpg
The –xpg option compiles self-profiling code to collect data for profiling with gprof.
This option invokes a runtime recording mechanism that produces a gmon.out file
when the program normally terminates.
Warnings
If you compile and link separately, and you compile with –xpg, be sure to link with
–xpg.
A.2.129 -xprefetch[=a[,a]]
SPARC: Enable prefetch instructions on those architectures that support prefetch,
such as UltraSPARC II (-xarch=v8plus, v8plusa, v9plusb, v9, v9a, or v9b)
Value Meaning
The prefetch latency is the hardware delay between the execution of a prefetch
instruction and the time the data being prefetched is available in the cache. The
compiler assumes a prefetch latency value when determining how far apart to place
a prefetch instruction and the load or store instruction that uses the prefetched data.
The compiler tunes the prefetch mechanism for optimal performance across a wide
range of machines and applications. This tuning may not always be optimal. For
memory-intensive applications, especially applications intended to run on large
multiprocessors, you may be able to obtain better performance by increasing the
prefetch latency values. To increase the values, use a factor that is greater than 1
(one). A value between .5 and 2.0 will most likely provide the maximum
performance.
For applications with datasets that reside entirely within the external cache, you may
be able to obtain better performance by decreasing the prefetch latency values. To
decrease the values, use a factor that is less than 1 (one).
To use the -xprefetch=latx:factor option, start with a factor value near 1.0 and
run performance tests against the application. Then increase or decrease the factor,
as appropriate, and run the performance tests again. Continue adjusting the factor
and running the performance tests until you achieve optimum performance. When
you increase or decrease the factor in small steps, you will see no performance
difference for a few steps, then a sudden difference, then it will level off again.
Defaults
If -xprefetch is not specified, -xprefetch=no%auto,explicit is assumed.
The default of no%auto is assumed unless explicitly overridden with the use of
-xprefetch without any arguments or with an argument of auto or yes. For
example, -xprefetch=explicit is the same as
-xprefetch=explicit,no%auto.
The sun_prefetch.h header file provides the macros for specifying explicit
prefetch instructions. The prefetches will be approximately at the place in the
executable that corresponds to where the macros appear.
To use the explicit prefetch instructions, you must be on the correct architecture,
include sun_prefetch.h, and either exclude -xprefetch from the compiler
command or use -xprefetch, -xprefetch=auto,explicit,
-xprefetch=explicit or -xprefetch=yes.
If you call the macros and include the sun_prefetch.h header file, but pass
-xprefetch=no%explicit or -xprefetch=no, the explicit prefetches will not
appear in your executable.
The use of latx:factor is valid only when automatic prefetching is enabled. That is,
latx:factor is ignored unless you use it in conjunction with yes or auto, as in
-xprefetch=yes,latx:factor.
Warnings
Explicit prefetching should only be used under special circumstances that are
supported by measurements.
Because the compiler tunes the prefetch mechanism for optimal performance across
a wide range of machines and applications, you should only use
-xprefetch=latx:factor when the performance tests indicate there is a clear
benefit. The assumed prefetch latencies may change from release to release.
Therefore, retesting the effect of the latency factor on performance whenever
switching to a different release is highly recommended.
A.2.130 -xprofile=p
Collects or optimizes with runtime profiling data.
This option causes execution frequency data to be collected and saved during the
execution. The data can then be used in subsequent runs to improve performance.
This option is valid only when a level of optimization is specified.
Value of p Meaning
collect[:name] Collects and saves execution frequency for later use by the optimizer
with –xprofile=use. The compiler generates code to measure
statement execution frequency. The name is the name of the program
that is being analyzed. The name is optional and, if not specified, is
assumed to be a.out.
If you run the program several times, the execution frequency data
accumulates in the feedback file; that is, output from prior runs is
not lost.
use[:name] Uses execution frequency data to optimize strategically. The name is
the name of the executable that is being analyzed. The name is
optional and, if not specified, is assumed to be a.out.
The source files and other compiler options must be exactly the same
as those used for the compilation that created the compiled program
that generated the feedback file. The same version of the compiler
must be used for both the collect build and the use build as well. If
compiled with -xprofile=collect:name, the same program
name, name, must appear in the optimizing compilation:
-xprofile=use:name.
Value of p Meaning
tcov Basic block coverage analysis using the new style tcov.
This option is the new style of basic block profiling for tcov. It has
similar functionality to the –xa option, but correctly collects data for
programs that have source code in header files or make use of C++
templates. Code instrumentation is similar to that of the -xa option,
but .d files are no longer generated. Instead, a single file is
generated, the name of which is based on the final executable. For
example, if the program is run out of /foo/bar/myprog.profile,
then the data file is stored in
/foo/bar/myprog.profile/myprog.tcovd.
When running tcov, you must pass it the –x option to force it to use
the new style of data. If you do not pass -x, tcov uses the old .d
files by default, and produces unexpected output.
Interactions
The –xprofile=tcov and the -xa options are compatible in a single executable. That
is, you can link a program that contains some files that have been compiled with
-xprofile=tcov and other files compiled with -xa. You cannot compile a single file
with both options.
See also
-xa, tcov(1) man page, Analyzing Program Performance With Sun WorkShop
A.2.131 –xregs=r[,r...]
SPARC: Controls scratch register usage.
The compiler can generate faster code if it has more registers available for temporary
storage (scratch registers). This option makes available additional scratch registers
that might not always be appropriate.
Values
r must be one of the following values. The meaning of each value depends upon the
-xarch setting.
Value of r Meaning
[no%]appl [Does not] Allow use of registers g2, g3, and g4 (v8, v8a)
[Does not] Allow use of registers g2, g3, and g4 (v8plus, v8plusa,
v8plusb)
[Does not] Allow use of registers g2, g3 (v9, v9a, v9b)
You can use the floating-point registers even if the program contains
no floating point code.
Examples
To compile an application program using all available scratch registers, use
-xregs=appl,float.
See also
SPARC V7/V8 ABI, SPARC V9 ABI
A.2.132 –xs
Allows debugging by dbx without object (.o) files.
This option disables Auto-Read for dbx. Use this option if you cannot keep the .o
files. This option passes the -s option to the assembler.
No Auto-Read is the older way of loading symbol tables. It places all symbol tables
for dbx in the executable file. The linker links more slowly, and dbx initializes more
slowly.
Auto-Read is the newer and default way of loading symbol tables. With Auto-Read
the information is placed in the .o files, so that dbx loads the symbol table
information only if it is needed. Hence the linker links faster, and dbx initializes
faster.
With –xs, if you move executables to another directory, you do not have to move the
object (.o) files to use dbx.
Without –xs, if you move the executables to another directory, you must move both
the source files and the object (.o) files to use dbx.
A.2.133 –xsafe=mem
SPARC: Allows the compiler to assume that no memory protection violations occur.
Interactions
This option is effective only when it is used with –xO5 optimization and
-xarch=v8plus, v8plusa, v8plusb, v9, v9a, or v9b is specified.
Warnings
Because nonfaulting loads do not cause a trap when a fault such as address
misalignment or segmentation violation occurs, you should use this option only for
programs in which such faults cannot occur. Because few programs incur memory-
based traps, you can safely use this option for most programs. Do not use this option
for programs that explicitly depend on memory-based traps to handle exceptional
conditions.
A.2.134 –xsb
Produces information for the Sun WorkShop source browser.
This option causes the CC driver to generate extra symbol table information in the
SunWS_cache subdirectory for the source browser.
See also
–xsbfast
A.2.135 –xsbfast
Produces only source browser information, no compilation.
This option runs only the ccfe phase to generate extra symbol table information in
the SunWS_cache subdirectory for the source browser. No object file is generated.
See also
–xsb
A.2.137 –xtarget=t
Specifies the target platform for instruction set and optimization.
The performance of some programs can benefit by providing the compiler with an
accurate description of the target computer hardware. When program performance
is critical, the proper specification of the target hardware could be very important.
This is especially true when running on the newer SPARC processors. However, for
most programs and older SPARC processors, the performance gain is negligible and
a generic specification is sufficient.
Values
For SPARC platforms:
Value of t Meaning
native Gets the best performance on the host system. The compiler
generates code optimized for the host system. It determines the
available architecture, chip, and cache properties of the machine on
which the compiler is running.
native64 Gets the best performance for 64-bit object binaries on the host
system. The compiler generates 64-bit object binaries optimized for
the host system. It determines the available 64-bit architecture, chip,
and cache properties of the machine on which the compiler is
running.
generic Gets the best performance for generic architecture, chip, and cache.
The compiler expands –xtarget=generic to:
–xarch=generic –xchip=generic –xcache=generic.
This is the default value.
generic64 Sets the parameters for the best performance of 64-bit object binaries
over most 64-bit platform architectures.
platform-name Gets the best performance for the specified platform. Select a SPARC
platform name from TABLE A-19.
Value of t Meaning
generic Gets the best performance for generic architecture, chip, and cache.
This is the default value.
native Gets the best performance on the host system.
386 Directs the compiler to generate code for the best performance on the
Intel 80386 microprocessor.
486 Directs the compiler to generate code for the best performance on the
Intel 80486 microprocessor.
pentium Directs the compiler to generate code for the best performance on the
Pentium microprocessor.
pentium_pro Directs the compiler to generate code for the best performance on the
Pentium Pro microprocessor.
Defaults
On both SPARC and IA devices, if –xtarget is not specified, –xtarget=generic is
assumed.
Expansions
The –xtarget option is a macro that permits a quick and easy specification of the
-xarch, –xchip, and –xcache combinations that occur on commercially purchased
platforms. The only meaning of –xtarget is in its expansion.
Examples
-xtarget=sun4/15 means -xarch=v8a -xchip=micro -xcache=2/16/1.
-xarch=v9 -xtarget=ultra
–xtarget=ultra –xarch=v9
Warnings
When you compile and link in separate steps, you must use the same -xtarget
settings in the compile step and the link step.
A.2.138 –xtime
Causes the CC driver to report execution time for the various compilation passes.
A.2.139 –xunroll=n
Enables unrolling of loops where possible.
This option specifies whether or not the compiler optimizes (unrolls) loops.
Values
When n is 1, it is a suggestion to the compiler to not unroll loops.
When n is an integer greater than 1, –unroll=n causes the compiler to unroll loops n
times.
If your source code has a literal string containing question marks (?) that the
compiler is interpreting as a trigraph sequence, you can use the -xtrigraph=no
suboption to turn off the recognition of trigraph sequences.
Values
Value Meaning
Defaults
When you do not include the -xtrigraphs option on the command line, the
compiler assumes -xtrigraphs=yes.
Examples
Consider the following example source file named trigraphs_demo.cc.
#include <stdio.h>
int main ()
{
(void) printf("(\?\?) in a string appears as (??)\n");
return 0;
}
See also
For information on trigraphs, see the C User’s Guide chapter about transitioning to
ANSI/ISO C.
A.2.141 –xwe
Converts all warnings to errors by returning nonzero exit status.
Pragmas
This appendix describes the Sun WorkShop C++ compiler pragmas. A pragma is a
compiler directive that allows you to provide additional information to the compiler.
This information can change compilation details that are not otherwise under your
control. For example, the pack pragma affects the layout of data within a structure.
Compiler pragmas are also called directives.
The preprocessor keyword pragma is part of the C++ standard, but the form,
content, and meaning of pragmas is different for every compiler. No pragmas are
defined by the C++ standard.
#pragma keyword
#pragma keyword ( a [ , a ] ...) [ , keyword ( a [ , a ] ...) ] ,...
#pragma sun keyword
The pragma keywords that are recognized by the C++ compiler are:
■ align—Makes the parameter variables memory-aligned to a specified number of
bytes, overriding the default.
■ init—Marks a specified function as an initialization function.
■ fini—Marks a specified function as a finalization function.
B-1
■ ident—Places a specified string in the .comment section of the executable.
■ pack (n)—Controls the layout of structure offsets. The value of n is a number—
0, 1, 2, 4, or 8—that specifies the worst-case alignment desired for any structure
member.
■ unknown_control_flow—Specifies a list of routines that violate the usual
control flow properties of procedure calls.
■ weak—Defines weak symbol bindings.
Use align to make the listed variables memory-aligned to integer bytes, overriding
the default. The following limitations apply:
■ integer must be a power of 2 between 1 and 128; valid values are 1, 2, 4, 8, 16, 32,
64, and 128.
■ variable is a global or static variable; it cannot be a local variable or a class
member variable.
■ If the specified alignment is smaller than the default, the default is used.
■ The pragma line must appear before the declaration of the variables that it
mentions; otherwise, it is ignored.
■ Any variable mentioned on the pragma line but not declared in the code
following the pragma line is ignored. Variables in the following example are
properly declared.
namespace foo {
#pragma align 8 (a, b, c)
static char a;
static char b;
static char c;
}
Use init to mark identifier as an initialization function. Such functions are expected
to be of type void, to accept no arguments, and to be called while constructing the
memory image of the program at the start of execution. Initializers in a shared object
are executed during the operation that brings the shared object into memory, either
at program start up or during some dynamic loading operation, such as dlopen().
The only ordering of calls to initialization functions is the order in which they are
processed by the link editors, both static and dynamic.
Within a source file, the functions specified in #pragma init are executed after the
static constructors in that file. You must declare the identifiers before using them in
the pragma.
Use fini to mark identifier as a finalization function. Such functions are expected to
be of type void, to accept no arguments, and to be called either when a program
terminates under program control or when the containing shared object is removed
from memory. As with initialization functions, finalization functions are executed in
the order processed by the link editor.
Use no_side_effect to indicate that a function does not change any persistent
state. The pragma declares that the named functions have no side effects of any kind.
This means that the functions return result values that depend on the passed
arguments only. In addition, the functions and their called descendants:
■ Do not access for reading or writing any part of the program state visible in the
caller at the point of the call.
■ Do not perform I/O.
■ Do not change any part of the program state not visible at the point of the call.
If the function does have side effects, the results of executing a program which calls
this function are undefined.
The name argument specifies the name of a function within the current translation
unit. The pragma must be in the same scope as the function and must appear after
the function declaration. The pragma must be before the function definition.
If the function is overloaded, the pragma applies to the last function that is defined.
If the last function that is defined does not have the same identifier, the program is
in error.
#pragma pack(2)
If the value of n is the same as or greater than the strictest alignment on the
platform, the directive has the effect of natural alignment. The following table shows
the strictest alignment for each platform.
IA 4
SPARC generic, V7, V8, V8a, V8plus, V8plusa, V8plusb 8
SPARC V9, V9a, V9b 16
A pack directive applies to all structure definitions which follow it, until the next
pack directive. If the same structure is defined in different translation units with
different packing, your program may fail in unpredictable ways. In particular, you
should not use a pack directive prior to including a header defining the interface of
a precompiled library. The recommended usage is to place the pack directive in
your program code, immediately before the structure to be packed, and to place
#pragma pack() immediately after the structure.
SPARC V8 SPARC V9 IA
Type Size, Alignment Size, Alignment Size, Alignment
bool 1, 1 1, 1 1, 1
char 1, 1 1, 1 1, 1
short 2, 2 2, 2 2, 2
wchar_t 4, 4 4, 4 4, 4
int 4, 4 4, 4 4, 4
long 4, 4 8, 8 4, 4
float 4, 4 4, 4 4, 4
double 8, 8 8, 8 8, 4
long double 16, 8 16, 16 12, 4
pointer to data 4, 4 8, 8 4, 4
pointer to function 4, 4 8, 8 4, 4
pointer to member data 4, 4 8, 8 4, 4
pointer to member function 8, 4 16, 8 8, 4
This pragma asserts that each named function returns the address of newly allocated
memory and that the pointer does not alias with any other pointer. This information
allows the optimizer to better track pointer values and to clarify memory location.
This results in improved scheduling and pipelining.
If the assertion is false, the results of executing a program which calls this function
are undefined.
The name argument specifies the name of a function within the current translation
unit. The pragma must be in the same scope as the function and must appear after
the function declaration. The pragma must be before the function definition.
Because such routines render standard flowgraph analysis invalid, routines that call
them cannot be safely optimized; hence, they are compiled with the optimizer
disabled.
Use weak to define a weak global symbol. This pragma is used mainly in source files
for building libraries. The linker does not warn you if it cannot resolve a weak
symbol.
If another compilation unit has a strong definition for the function or variable, name
will be linked to that. If there is no strong definition for name, the linker symbol will
have a value of 0.
The following directive defines ping to be a weak symbol. No error messages are
generated if the linker cannot find a definition for a symbol named ping.
In the identifier form, name2 must be declared and defined within the current
compilation unit. For example:
When you use the string form, the symbol does not need to be previously declared.
If both _bar and bar in the following example are extern "C", the functions do
not need to be declared. However, bar must be defined in the same object.
int bar(int);
float bar(float);
#pragma weak bar // error, ambiguous function name
To avoid the error, use the string form, as shown in the following example.
int bar(int);
float bar(float);
#pragma weak "__1cDbar6Fi_i_" // make float bar(int) weak
See the Solaris Linker and Libraries Guide for more information.
abstract class A class that contains one or more abstract methods, and therefore can never be
instantiated. Abstract classes are defined so that other classes can extend them
and make them concrete by implementing the abstract methods.
ANSI/ISO C++ The American National Standards Institute and the ISO standard for the C++
programming language. See ISO.
application binary
interface The binary system interface between compiled applications and the operating
system on which they run.
array A data structure that stores a collection of values of a single data type
consecutively in memory. Each value is accessed by its position in the array.
binary compatibility The ability to link object files that are compiled by one release while using a
compiler of a different release.
binding Associating a function call with a specific function definition. More generally,
associating a name with a particular entity.
cfront A C++ to C compiler program that translates C++ to C source code, which in
turn can be compiled by a standard C compiler.
class A user-defined data type consisting of named data elements (which may be of
different types), and a set of operations that can be performed with the data.
class template A template that describes a set of classes or related data types.
Glossary-1
class variable A data item associated with a particular class as a whole, not with particular
instances of the class. Class variables are defined in class definitions. Also
called static field. See also instance variable.
compiler option An instruction to the compiler that changes its behavior. For example, the -g
option tells the compiler to generate data for the debugger. Synonyms: flag,
switch.
constructor A special class member function that is automatically called by the compiler
whenever a class object is created to ensure the initialization of that object’s
instance variables. The constructor must always have the same name as the
class to which it belongs. See destructor.
data member An element of a class that is data, as opposed to a function or type definition.
data type The mechanism that allows the representation of, for example, characters,
integers, or floating-point numbers. The type determines the storage that is
allocated to a variable and the operations that can be performed on the
variable.
destructor A special class member function that is automatically called by the compiler
whenever a class object is destroyed or the operator delete is applied to a
class pointer. The destructor must always have the same name as the class to
which it belongs, preceded by a tilde (~). See constructor.
dynamic binding Connection of the function call to the function body at runtime. Occurs only
with virtual functions. Also called late binding, runtime binding.
dynamic cast A safe method of converting a pointer or reference from its declared type to
any type that is consistent with the dynamic type to which it refers.
dynamic type The actual type of an object that is accessed by a pointer or reference that
might have a different declared type.
ELF file Executable and Linking Format file, which is produced by the compiler.
exception An error occurring in the normal flow of a program that prevents the program
from continuing. Some reasons for errors include memory exhaustion or
division by zero.
exception handler Code specifically written to deal with errors, and that is invoked automatically
when an exception occurs for which the handler has been registered.
exception handling An error recovery process that is designed to intercept and prevent errors.
During the execution of a program, if a synchronous error is detected, control
of the program returns to an exception handler that was registered at an earlier
point in the execution, and the code containing the error is bypassed.
functional
polymorphism See function overloading.
function prototype A declaration that describes the function’s interface with the rest of the
program.
function template A mechanism that allows you to write a single function that you can then use
as a model, or pattern, for writing related functions.
idempotent The property of a header file that including it many times in one translation
unit has the same effect as including it once.
incremental linker A linker that creates a new executable file by linking only the changed .o files
to the previous executable.
inline function A function that replaces the function call with the actual function code.
instantiation The process by which a C++ compiler creates a usable function or object
(instance) from a template.
instance variable Any item of data that is associated with a particular object. Each instance of a
class has its own copy of the instance variables defined in the class. Also called
field. See also class variable.
K&R C The de facto C programming language standard that was developed by Brian
Kernighan and Dennis Ritchie before ANSI C.
keyword A word that has unique meaning in a programming language, and that can be
used only in a specialized context in that language.
linker The tool that connects object code and libraries to form a complete, executable
program.
local variable A data item known within a block, but inaccessible to code outside the block.
For example, any variable defined within a method is a local variable and
cannot be used outside the method.
locale A set of conventions that are unique to a geographical area and/or language,
such as date, time, and monetary format.
Glossary-3
lvalue An expression that designates a location in memory at which a variable’s data
value is stored. Also, the instance of a variable that appears to the left of the
assignment operator.
member function An element of a class that is a function, as opposed to a data definition or type
definition.
multiple inheritance Inheritance of a derived class directly from more than one base class.
multithreading The software technology that enables the development of parallel applications,
whether on single- or multiple-processor systems.
name mangling In C++, many functions can share the same name, so name alone is not
sufficient to distinguish different functions. The compiler solves this problem
by name mangling—creating a unique name for the function that consists of
some combination of the function name and its parameters—to enable type-
safe linkage. Also called name decoration.
namespace A mechanism that controls the scope of global names by allowing the global
space to be divided into uniquely named scopes.
operator overloading The ability to use the same operator notation to produce different outcomes. A
special form of function overloading.
optimization The process of improving the efficiency of the object code that is generated by
the compiler.
overloading To give the same name to more than one function or operator.
polymorphism The ability of a pointer or reference to refer to objects whose dynamic type is
different from the declared pointer or reference type.
runtime type
identification (RTTI) A mechanism that provides a standard method for a program to determine an
object type during runtime.
rvalue The variable that is located to the right of an assignment operator. The rvalue
can be read but not altered.
stab A symbol table entry that is generated in the object code. The same format is
used in both a.out files and ELF files to contain debugging information.
static binding Connection of a function call to a function body at compile time. Also called
early binding.
symbol table A list of all identifiers that are present when a program is compiled, their
locations in the program, and their attributes. The compiler uses this table to
interpret uses of identifiers.
template database A directory containing all configuration files that are needed to handle and
instantiate the templates that are required by a program.
template options file A user-provided file containing options for the compilation of templates, as
well as source location and other information. The template options file is
deprecated and should not be used.
template
specialization A specialized instance of a class template member function that overrides the
default instantiation when the default cannot handle a given type adequately.
type A description of the ways in which a symbol can be used. The basic types are
integer and float. All other types are constructed from these basic types by
collecting them into arrays or structures, or by adding modifiers such as
pointer-to or constant attributes.
variable An item of data named by an identifier. Each variable has a type, such as int
or void, and a scope. See also class variable, instance variable, local variable.
VTABLE A table that is created by the compiler for each class that contains virtual
functions.
Glossary-5
Glossary-6 C++ User’s Guide • July 2001
Index
A
-a, compiler option, A-3
.a, file name suffix, 16-1, 2-4 C
absolute value, complex numbers, 15-2 C API (application programming interface)
aliases, simplifying commands with, 2-15 creating libraries, 16-5
alignments removing dependency on C++ runtime
default, B-6 libraries, 16-5
strictest, B-5 C standard library header files, replacing, 12-17
anachronisms, disallowing, A-16 C++ man pages, accessing, xxxiii, 12-4, 12-5
angle, complex numbers, 15-2 C++ standard library, 12-2 to 12-3
anonymous class instance, passing, 4-5 components, 13-1 to 13-17
applications man pages, 12-4, 13-4 to 13-17
linking multithreaded, 11-1, 11-9 replacing, 12-13 to 12-17
MT-safe, 11-6 RogueWave version, 13-1
using MT-safe iostream objects, 11-20 to 11-22 shared version, 13-2
applicator, parameterized manipulators, 14-21 .c++, file name suffixes, 2-4
Index-1
-c, compiler option, 2-6, A-5 -compat
.C, file name suffixes, 2-4 compiler option, A-6
.c, file name suffixes, 2-4 default linked libraries, affect on, 12-5
c_exception, complex class, 15-6 -features option, value restrictions, A-16
cache libraries, available modes for, 12-2
directory, template, 2-5 -library option, value restrictions, A-41
used by optimizer, A-71 linking C++ libraries, modes for, 12-10
cast compatibility mode
const and volatile, 9-2 See also -compat
dynamic, 9-4 iostream, 14-1
casting down, 9-5 libC, 14-1, 14-4
casting to void*, 9-5 libcomplex, 15-1
casting up, 9-5 Tools.h++, 12-3
reinterpret_cast, 9-2 compilation, memory requirements, 2-12 to 2-15
static_cast, 9-4 compiler
CC pragma directives, B-1 accessing, xxix
.cc, file name suffixes, 2-4 component invocation order, 2-9 to 2-11
CC_tmpl_opt, options file, 7-8 diagnosing, 2-8 to 2-9
CCadmin command, 7-1 new features, 1-4
CCFLAGS, environment variable, 2-15 versions, incompatibility, 2-5
cerr standard stream, 11-16, 14-2 compiling and linking, 2-6 to 2-7
-cg, compiler option, A-6 complex
char* extractor, 14-9 to 14-11 compatibility mode, 15-1
characters, reading single, 14-10 constructors, 15-2 to 15-3
cin standard stream, 11-16, 14-2 efficiency, 15-9
class instance, anonymous, 4-5 error handling, 15-6 to 15-7
class libraries, using, 12-7 to 12-10 header file, 15-2
class templates, 6-3 to 6-6 input/output, 15-7 to 15-8
See also templates library, 12-2 to 12-3, 12-8 to 12-10, 15-1 to 15-10
declaration, 6-3 library, linking, 15-2
definition, 6-3, 6-4 man pages, 15-10
incomplete, 6-3 mathematical functions, 15-4 to 15-6
member, definition, 6-4 mixed-mode, 15-8 to 15-9
parameter, default, 6-9 operators, 15-3 to 15-4
static data members, 6-5 standard mode and libCstd, 15-1
using, 6-5 trigonometric functions, 15-5 to 15-6
classes complex number data type, 15-1
passing directly, 10-5 complex_error
passing indirectly, 10-4 definition, 15-6
clog standard stream, 11-16, 14-2 message, 15-4
code generation conjugate of a number, 15-2
inliner and assembler, compilation const_cast operator, 9-2
component, 2-11 constant strings in read-only memory, A-16
options, 3-3 constructors
code optimizer, compilation component, 2-11 complex class, 15-2
command line iostream, 14-3
options, unrecognized, 2-8 static, 16-3
recognized file suffixes, 2-4
Index-3
external -fsimple=n, compiler option, A-26 to A-28
instances, 7-2 -fstore, compiler option, A-28
linkage, 7-2 fstream, defined, 14-3, 14-26
extraction fstream.h
char*, 14-9 to 14-11 iostream header file, 14-4
defined, 14-26 using, 14-13
operators, 14-8 -ftrap, compiler option, A-28
user-defined iostream, 14-8 to 14-9 __func__, identifier, 4-7
whitespace, 14-11 function templates, 6-1 to 6-7
See also templates
declaration, 6-1
definition, 6-2
F using, 6-2
-fast, compiler option, A-14 to A-16 functions
-features, compiler option, 4-1 to 4-7, 8-2, 9-4, in dynamic (shared) libraries, 16-3
A-16 to A-20 inlining by optimizer, A-79
file descriptors, using, 14-15 MT-safe public, 11-8
file names overriding, 4-1
.SUNWCCh file name suffix, 12-15 to 12-16 static, as class friend, 4-6
suffixes, 2-4 streambuf public virtual, 11-19
template definition files, 7-6 functions, name in __func__, 4-7
__FILE__, predefined macro, A-9
files
See also source files
C standard header files, 12-15 G
copying, 14-14, 14-23 -G
executable program, 2-6 dynamic library command, 16-3
multiple source, using, 2-5 option description, A-30 to A-31
object, 2-6, 3-2, 16-3 -g
opening and closing, 14-15 option description, A-31
repositioning, 14-16 compiling templates using, 7-7
standard library, 12-15 garbage collection
template options, 7-8 debug, compiler option, 12-10
using fstreams with, 14-13 libraries, 12-3, 12-10
-filt, compiler option, A-20 gcmonitor, daemon in memory debugging
finalization functions, B-3 mode, 12-4
-flags, compiler option, A-22 get pointer, streambuf, 14-22
float inserter, iostream output, 14-5 get, char extractor, 14-10
floating point global
invalid, A-28 data, in a multithreaded application, 11-16
options, 3-4 instances, 7-2 to 7-3
flush, iostream manipulator, 14-7, 14-18 linkage, 7-2 to 7-4
-fnonstd, compiler option, A-22 shared objects in MT application, 11-16
-fns, compiler option, A-22 -gO option description, A-32
format control, iostreams, 14-17 gprof, C++ utilities, 1-5
Fortran runtime libraries, linking, A-83
-fprecision=p, compiler option, A-24 to A-25
front end, compilation component, 2-11
-fround=r, compiler option, A-25 to A-26
Index-5
output errors, 14-6 to 14-7 libc library, 12-1
output to, 14-4 libcomplex, See complex
predefined, 14-2 libCrun library, 11-1, 11-2, 12-2, 12-5, 16-4
shared version, 14-1 libCstd library, See C++ standard library
single-threaded applications, 11-9 libdemangle library, 12-2 to 12-4
standard iostreams, 12-2, 12-7, A-44 libgc library, 12-2
standard mode, 14-1, 14-4, A-44 libgc_dbg library, 12-2
stdio, 14-12, 14-22 libiostream, See iostream
stream assignment, 14-17 libm
structure, 14-3 inline templates, A-84
terminology, 14-26 library, 12-1
using, 14-4 optimized version, A-85
iostream.h, iostream header file, 11-16, 14-4 -libmieee, compiler option, A-40
ISO C++ standard -libmil, compiler option, A-40
conformance, 1-1 libraries
one-definition rule, 6-17, 7-6 C interface, 12-1
istream class, defined, 14-3 C++ compiler, provided with, 12-2
istrstream class, defined, 14-3 C++ standard, 13-1 to 13-17
class, using, 12-7
classic iostream, 14-1 to 14-26
dynamically linked, 12-12
K interval arithmetic, A-77
.KEEP_STATE, using with standard library header linking options, 3-5, 12-10
files, 2-17 linking order, 3-2
-keeptmp, compiler option, A-38 linking with -mt, 12-1
-KPIC, compiler option, 16-3, A-39 naming a shared library, A-33
-Kpic, compiler option, 16-3, A-39 optimized math, A-85
replacing, C++ standard library, 12-13 to 12-17
shared, 12-11 to 12-13, A-10
static, A-3
L suffixes, 16-1
-L, compiler option, 12-5, A-39 Sun Performance Library, linking, A-41, A-85
-l, compiler option, 3-2, 12-1, 12-5, A-39 to A-40 understanding, 16-1 to 16-2
languages using, 12-1 to 12-13
options, 3-5 libraries, building
support for native, 1-5 dynamic (shared), 16-1 to 16-4
LD_LIBRARY_PATH environment variable, 12-12, for private use, 16-4
16-2 for public use, 16-5
ldd command, 12-12 linking options, A-30
left-shift operator shared with exceptions, 16-4
complex, 15-7 static (archive), 16-1 to 16-3
iostream, 14-4 with C API, 16-5
lex, C++ utilities, 1-5 -library, compiler option, 12-5 to 12-7, 12-10,
libC A-40 to A-45
compatibility mode, 14-1, 14-4 librwtool, See Tools.h++
compiling and linking MT-safety, 11-9 libthread library, 12-1
library, 12-2 to 12-3 libw library, 12-1
MT environment, using in, 11-6
new MT classes, 11-13
Index-7
-nofstore, compiler option, A-48 options
-nolib, compiler option, 12-6, A-48 See also individual options under alphabetical listings
-nolibmil, compiler option, A-48 code generation, 3-3
nonincremental link editor, compilation debugging, 3-3
component, 2-11 description subsections, A-2
nonstandard features, 4-1 to 4-7 expansion compilation, A-14
allowing nonstandard code, A-17 floating point, 3-4
defined, 1-1 language, 3-5
-noqueue, compiler option, A-48 library, 12-5 to 12-7
-norunpath, compiler option, 12-7, A-48 library linking, 3-5
numbers, complex, 15-1 to 15-4 licensing, 3-6
obsolete, 3-7, A-52
optimization, 3-8
output, 3-7, 3-8
O performance, 3-8, 3-9
.o files preprocessor, 3-9
option suffixes, 2-4 processing order, 2-3, 3-2
preserving, 2-6 profiling, 3-10
-O, compiler option, A-49 reference, 3-10
-o, compiler option, A-49 source, 3-10
object files subprogram compilation, 2-7 to 2-8
linking order, 3-2 syntax format, 3-1, A-1
relocatable, 16-3 template, 3-11, 7-8
object thread, private, 11-17 template compilation, 7-2
objects thread, 3-11
destruction of shared, 11-20 unrecognized, 2-8
destruction order, A-18 ostream class, defined, 14-3
global shared, 11-16 ostrstream class, defined, 14-3
strategies for dealing with shared, 11-17 output, 14-1
stream_locker, 11-19 binary, 14-8
temporary, 10-1 buffer flushing, 14-7
temporary, lifetime of, A-18 cout, 14-4
within library, when linked, 16-1 flushing, 14-7
oct, iostream manipulator, 14-18 handling errors, 14-6
ofstream class, 14-13 options, 3-7
-Olevel, compiler option, A-49 overflow function, streambuf, 11-19
operators overhead, MT-safe class performance, 11-11, 11-13
basic arithmetic, 15-3 to 15-4
complex, 15-7
iostream, 14-4, 14-6, 14-8 to 14-9
scope resolution, 11-11 P
optimization -P, compiler option, A-50
levels, A-90 -p, compiler option, A-51
math library, A-85 +p, compiler option, A-50
options for, 3-8 parameterized manipulators, iostreams, 14-20 to
target hardware, A-102 14-21
optimizer out of memory, 2-14 PATH environment variable, setting, xxx
peeking at input, 14-11
-pentium, compiler option, A-51
Index-9
setioflags, iostream manipulator, 14-18 standard streams, iostream.h, 11-16
setprecision, iostream manipulator, 14-18 Standard Template Library (STL), 13-1
setw, iostream manipulator, 14-18 standards, conformance, 1-1
shared libraries static
accessing from a C program, 16-6 functions, referencing, 6-17
building, 16-3, A-30 objects, initializers for nonlocal, A-17
building, with exceptions, 8-5 variables, referencing, 6-17
containing exceptions, 16-4 static (archive) libraries, 16-1
disallowing linking of, A-10 static data, in a multithreaded application, 11-16
naming, A-33 static instances, 7-2 to 7-3
shared objects, 11-17, 11-20 static linking
shell prompts, xxix compiler provided libraries, 12-6, A-57 to A-59
shell, limiting virtual memory in, 2-13 default libraries, 12-10
shift operators, iostreams, 14-19 library binding, A-3
signal handlers template instances, 7-3
and exceptions, 8-1 static template class member, 7-13
and multithreading, 11-2 static_cast operator, 9-4
sizes, storage, B-6 -staticlib, compiler option, 12-6, 12-10, A-57 to
skip flag, iostream, 14-11 A-59
.so, file name suffix, 2-4, 16-1 __STDC__, predefined macro, 5-1, A-9
.so.n, file name suffix, 2-4 stdio
Solaris operating environment libraries, 12-1 stdiobuf man pages, 14-22
Solaris versions supported, xxix with iostreams, 14-12
source compiler options, 3-10 stdiostream.h, iostream header file, 14-4
source files STL (Standard Template Library),
linking order, 3-2 components, 13-1
location conventions, 7-6 storage sizes, B-6
location definition, 7-9 to 7-11 stream, defined, 14-26
template definition, 7-9 stream.h, iostream header file, 14-4
__sparc, predefined macro, A-10 stream_locker
sparc, predefined macro, A-10 man pages, 11-19
__sparcv9, predefined macro, A-10 synchronization with MT-safe objects, 11-13
special, template compilation option, 7-12 to streambuf
7-13 defined, 14-22, 14-26
Standard C++ Class Library Reference, 13-2 get pointer, 14-22
Standard C++ Library User’s Guide, 13-2 locking, 11-7
standard error, iostreams, 14-2 man pages, 14-23
standard headers new functions, 11-14
implementing, 12-15 public virtual functions, 11-19
replacing, 12-16 put pointer, 14-22
standard input, iostreams, 14-2 queue-like versus file-like, 14-23
standard iostream classes, 14-1 using, 14-23
standard mode streampos, 14-16
See also -compat strstream, defined, 14-3, 14-26
iostream, 14-1, 14-4 strstream.h, iostream header file, 14-4
libCstd, 15-1 struct, anonymous declarations, 4-4
Tools.h++, 12-3 subprograms, compilation options, 2-7 to 2-8
standard output, iostreams, 14-2
Index-11
__’uname-s’_’uname-r’, predefined macro, A-9 workstations, memory requirements, 2-14
unexpected() function, 11-3 ws, iostream manipulator, 14-11, 14-18
UNIX tools, 1-5
__unix, predefined macro, A-9
unix, predefined macro, A-10
-unroll=n, compiler option, A-61 X
user-defined types X inserter, iostream, 14-5
iostream, 14-5 -xa, compiler option, A-64
MT-safe, 11-11 -xar, compiler option, 7-2, 16-2 to 16-3, A-65
-xarch=isa, compiler option, A-65 to A-70
-xbuiltin, compiler option, A-70
-xcache=c, compiler option, A-71 to A-72
V -xcg89, compiler option, A-72
-V, compiler option, A-61 -xcg92, compiler option, A-72
-v, compiler option, A-61 -xchip=c, compiler option, A-73 to A-74
__VA_ARGS__ identifier, 2-12 -xcode=a, compiler option, A-74 to A-75
value classes, using, 10-3 -xcrossfile, compiler option, A-75
values -xF, compiler option, A-76 to A-77
double, 15-2 -xhelp=flags, compiler option, A-77
float, 14-5 -xhelp=readme, compiler option, A-77
flush, 14-7 -xia, compiler option, A-77
inserting on cout, 14-5 -xildoff, compiler option, A-78
long, 14-21 -xildon, compiler option, A-78
manipulator, 14-4, 14-21 -xinline, compiler option, A-79
variable argument lists, 2-12 -xipo, compiler option, A-81
-vdelx, compiler option, A-61 -xlang, compiler option, A-83
-verbose, compiler option, 2-8, 7-1, A-62 -xlibmieee, compiler option, A-84
virtual memory, limits, 2-13 to 2-14 -xlibmil, compiler option, A-84
-xlibmopt, compiler option, A-85
-xlic_lib, compiler option, A-85
-xlicinfo, compiler option, A-86
W -Xm, compiler option, A-86
+w, compiler option, 7-1, A-63 -xM, compiler option, A-86 to A-87
+w2, compiler option, A-63 -xM1, compiler option, A-87
-w, compiler option, A-64 -xMerge, compiler option, A-87
warnings -xnolib, compiler option, 12-6, 12-11, A-87 to
anachronisms, A-64 A-89
C header replacement, 12-17 -xnolibmil, compiler option, A-90
inefficient code, A-63 -xnolibmopt, compiler option, A-90
nonportable code, A-63 -xOlevel, compiler option, A-90 to A-93
problematic ARM language constructs, A-17 -xpg, compiler option, A-93
suppressing, A-64 -xprefetch, compiler option, A-94
technical violations reducing portability, A-63 -xprofile, compiler option, A-96 to A-99
unrecognized arguments, 2-8 -xregs, compiler option, 16-5, A-99
_WCHAR_T, predefined UNIX symbol, A-10 -xs, compiler option, A-100
whitespace -xsafe=mem, compiler option, A-100 to A-101
extractors, 14-11 -xsb, compiler option, A-101
leading, 14-10 -xsbfast, compiler option, A-101
skipping, 14-11, 14-19 -xspace, compiler option, A-102
Index-13
Index-14 C++ User’s Guide • July 2001