SS12U1C Guide
SS12U1C Guide
User's Guide
Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without
limitation, these intellectual property rights may include one or more U.S. patents or pending patent applications in the U.S. and in other countries.
U.S. Government Rights – Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions
of the FAR and its supplements.
This distribution may include materials developed by third parties.
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.
Sun, Sun Microsystems, the Sun logo, the Solaris logo, the Java Coffee Cup logo, docs.sun.com, Java, and Solaris are trademarks or registered trademarks of Sun
Microsystems, Inc. or its subsidiaries in the U.S. and other countries. All SPARCTM 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 SunTM 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.
Products covered by and information contained in this publication are controlled by U.S. Export Control laws and may be subject to the export or import laws in
other countries. Nuclear, missile, chemical or biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export
or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially
designated nationals lists is strictly prohibited.
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 2009 Sun Microsystems, Inc. 4150 Network Circle, Santa Clara, CA 95054 U.S.A. Tous droits réservés.
Sun Microsystems, Inc. détient les droits de propriété intellectuelle relatifs à la technologie incorporée dans le produit qui est décrit dans ce document. En particulier,
et ce sans limitation, ces droits de propriété intellectuelle peuvent inclure un ou plusieurs brevets américains ou des applications de brevet en attente aux Etats-Unis
et dans d'autres pays.
Cette distribution peut comprendre des composants développés par des tierces personnes.
Certaines composants de ce produit peuvent être dérivées du logiciel Berkeley BSD, licenciés par l'Université de Californie. UNIX est une marque déposée aux
Etats-Unis et dans d'autres pays; elle est licenciée exclusivement par X/Open Company, Ltd.
Sun, Sun Microsystems, le logo Sun, le logo Solaris, le logo Java Coffee Cup, docs.sun.com, Java et Solaris sont des marques de fabrique ou des marques déposées de
Sun Microsystems, Inc., ou ses filiales, 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.
Les produits qui font l'objet de cette publication et les informations qu'il contient sont régis par la legislation américaine en matière de contrôle des exportations et
peuvent être soumis au droit d'autres pays dans le domaine des exportations et importations. Les utilisations finales, ou utilisateurs finaux, pour des armes nucléaires,
des missiles, des armes chimiques ou biologiques ou pour le nucléaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou
réexportations vers des pays sous embargo des Etats-Unis, ou vers des entités figurant sur les listes d'exclusion d'exportation américaines, y compris, mais de manière
non exclusive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une façon directe ou indirecte, aux exportations des produits ou des services qui
sont régis par la legislation américaine en matière de contrôle des exportations et la liste de ressortissants spécifiquement designés, sont rigoureusement interdites.
LA DOCUMENTATION EST FOURNIE "EN L'ETAT" ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSES OU TACITES
SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE
IMPLICITE RELATIVE A LA QUALITE MARCHANDE, A L'APTITUDE A UNE UTILISATION PARTICULIERE OU A L'ABSENCE DE CONTREFACON.
090611@22510
Contents
Preface ...................................................................................................................................................21
3
Contents
5
Contents
7
Contents
9
Contents
11
Contents
13
Contents
15
Contents
17
18
Examples
19
20
Preface
The Sun Studio 12 Update 1 C++ User's Guide guide describes the environment and
command-line options for the Sun Studio C++ compiler, CC.
This guide is intended for application developers with a working knowledge of the C++
language and Solaris or Linux operating environments who want to learn how to use the Sun
Studio C++ compiler effectively.
Typographic Conventions
The following table describes the typographic conventions that are used in this book.
AaBbCc123 The names of commands, files, and directories, Edit your .login file.
and onscreen computer output
Use ls -a to list all files.
machine_name% you have mail.
aabbcc123 Placeholder: replace with a real name or value The command to remove a file is rm
filename.
AaBbCc123 Book titles, new terms, and terms to be Read Chapter 6 in the User's Guide.
emphasized
A cache is a copy that is stored
locally.
Do not save the file.
Note: Some emphasized items
appear bold online.
21
Preface
Shell Prompt
C shell machine_name%
Supported Platforms
This SunTM Studio release supports systems that use the SPARC and x86 families of processor
architectures: UltraSPARC®, SPARC64, AMD64, Pentium, and Xeon EM64T. The supported
systems for the version of the Solaris Operating System you are running are available in the
hardware compatibility lists at http://www.sun.com/bigadmin/hcl. These documents cite any
implementation differences between the platform types.
In this document, these x86 related terms mean the following:
■ “x86” refers to the larger family of 64–bit and 32–bit x86 compatible products.
■ “x64” points out specific 64–bit information about AMD64 or EM64T systems.
■ “32–bit x86” points out specific 32–bit information about x86 based systems.
For supported systems, see the hardware compatibility lists.
Note – Sun is not responsible for the availability of third-party Web sites mentioned in this
document. Sun does not endorse and is not responsible or liable for any content, advertising,
products, or other materials that are available on or through such sites or resources. Sun will not
be responsible or liable for any actual or alleged damage or loss caused by or in connection with
the use of or reliance on any such content, goods, or services that are available on or through
such sites or resources.
Online help HTML available through the Help menu and Help buttons in the
IDE
23
Preface
The Sun Studio portal is one of a number of additional resources for developers at the Sun
Developer Network web site, http://developers.sun.com.
Please include the part number of the document in the subject line of your email. For example,
the part number for this document is 820-7599–10.
C++ Compiler
25
26
1
C H A P T E R
This chapter provides general information about the current Sun Studio C++ compiler.:
27
1.1 New Features and Functionality of the Sun Studio 12 Update 1 C++ 5.10 Compiler
The legacy Sun-style parallelization pragmas are not available on x86. Use OpenMP instead. See
the Sun Studio 12:Update 1 OpenMP API User’s Guide for information on converting legacy
parallelization directives to OpenMP.
Programs compiled with -xarch set to sse, sse2, sse2a, sse3, or beyond must be run only on
platforms that provide these extensions and features.
Solaris OS releases starting with Solaris 9 4/04 are SSE/SSE2-enabled on Pentium 4-compatible
platforms. Earlier versions of Solaris OS are not SSE/SSE2-enabled. If an instruction set selected
by -xarch is not enabled in the running Solaris OS, the compiler will not be able to generate or
link code for that instruction set.
If you compile and link in separate steps, always link using the compiler and with same -xarch
setting to ensure that the correct startup routine is linked.
Numerical results on x86 might differ from results on SPARC due to the x86 80-bit
floating-point registers. To minimize these differences, use the -fstore option or compile with
-xarch=sse2 if the hardware supports SSE2.
Numerical results can also differ between Solaris and Linux because the intrinsic math libraries
(for example, sin(x)) are not the same.
The ILP32 model specifies that C++-language int, long, and pointer data types are all 32-bits
wide. The LP64 model specifies that long and pointer data types are all 64-bits wide. The Solaris
and Linux OS also support large files and large arrays under the LP64 memory model.
When you compile with —m64, the resulting executable works only on 64-bit UltraSPARC or x86
processors under Solaris OS or Linux OS running a 64-bit kernel. Compilation, linking, and
execution of 64-bit objects can only take place in a Solaris or Linux OS that supports 64-bit
execution.
If a program does not contain these architecture hardware flags, or if the platform does not
enable the appropriate features or instruction set extensions, running the program could result
in segmentation faults or incorrect results without any explicit warning messages.
This warning extends also to programs that employ .il inline assembly language functions or
__asm() assembler code that utilize SSE, SSE2, SSE2a, and SSE3 and newer instructions and
extensions.
On SPARCTM platforms, the compiler provides support for the optimization-exploiting features
of SPARC V8 and SPARC V9, including the UltraSPARC implementation. These features are
defined in the SPARC Architecture Manuals, Version 8 (ISBN 0-13-825001-4), and Version 9
(ISBN 0-13-099227-5), published by Prentice-Hall for SPARC International.
In this document, “Standard” means conforming to the versions of the standards listed above.
“Nonstandard” or “Extension” refers to features that go beyond these versions of these
standards.
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.
Throughout the C++ documentation, man page references appear with the topic name and
man section number: CC(1) is accessed with man CC. Other sections, denoted by
ieee_flags(3M) for example, are accessed using the -s option on the man command:
The principal use of any compiler is to transform a program written in a high-level language
like C++ into a data file that is executable by the target computer hardware. You can use the
C++ compiler to:
■ Transform source files into relocatable binary (.o) files, to be linked later into an executable
file, a static (archive) library (.a) file (using– xar), or a dynamic (shared) library (.so) file
■ Link or relink object files or library files (or both) into an executable file
■ Compile an executable file with runtime debugging enabled (-g)
■ Compile an executable file with runtime statement or procedure-level profiling (-pg)
Note – The command-line examples in this chapter show CC usages. Printed output might be
slightly different.
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
2. Invoking the compiler to produce an executable file
3. Launching the program into execution by typing the name of the executable file
33
2.2 Invoking the Compiler
In this example, CC compiles the source file greetings.cc and, by default, compiles the
executable program onto the file, a.out. To launch the program, type the name of the
executable file, a.out, at the command prompt.
Traditionally, UNIX compilers name the executable file a.out. It can be awkward to have each
compilation write to the same file. Moreover, if such a file already exists, it will be overwritten
the next time you run the compiler. Instead, use the -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, -xdumpmacros, 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:
TABLE 2–1 File Name Suffixes Recognized by the C++ Compiler (Continued)
Suffix Language Action
.so Dynamic (shared) library Pass names of shared objects to the linker.
.so.n
Similarly, the compiler issues an error if it encounters a cache directory that was produced by a
later version of the compiler.
When you upgrade your compiler, it is always good practice to clean the cache. Run CCadmin
-clean on every directory that contains a template cache directory (in most cases, a template
cache directory is named SunWS_cache). Alternatively, you can use rm -rf SunWS_cache.
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.
Be sure that the link step lists all the object files needed to make the complete program. If any
object files are missing from this step, the link will fail with “undefined external reference”
errors (missing routines).
If you compile a subprogram using any of these options, you must 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. Use —dryrun to see the expansion of these options to determine the options needed
on the link step.
■ 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.
In the following example, the programs are compiled using the -library=stlport4 compiler
option.
If you do not use -library=stlport4 consistently, some parts of the program will use the
deafult libCstd, and others will use the optional replacement STlport library. The resulting
program might not link, and would not in any case run correctly.
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 following example, note that -bit is not recognized by CC and the option is passed on to
the linker (ld), which tries to interpret it. Because single letter ld options can be strung
together, the linker sees -bit as -b -i -t, all of which are legitimate ld options. This might not
be what you intend or expect:
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. Use the -v and
-dryrun options to help with this.
As shown in the following table, input files to the various compiler components have different
file name suffixes. The suffix establishes the kind of compilation that is done. Refer to Table 2–1
for the meanings of the file suffixes.
fbe Assembler
ld link editor
2.5.1 Pragmas
The preprocessor directive pragma is part of the C++ standard, but the form, content, and
meaning of pragmas is different for every compiler. See Appendix B, “Pragmas,” for details on
the pragmas that the C++ compiler recognizes.
Sun C++ also supports the C99 keyword _Pragma. The two invocations
#pragma dumpmacros(defs)
_Pragma("dumpmacros(defs)")
are equivalent. To use _Pragma instead of #pragma, write the pragma text as a literal string,
enclosed in parentheses as the one argument of the _Pragma keyword.
If the macro parameter list ends with an ellipsis, an invocation of the macro is allowed to have
more arguments than there are macro parameters. The additional arguments are collected into
a single string, including commas, that can be referenced by the name __VA_ARGS__ in the
macro replacement list. The following example demonstrates how to use a
variable-argument-list macro.
fprintf(stderr, “Flag”);
fprintf(stderr, “X = %d\n”, x);
puts(“The first, second, and third items.”);
((x>y)?puts(“x>y”):printf(“x is %d but y is %d”, x, y));
2.5.4 #error
The #error directive no longer continues compilation after issuing a warning. The previous
behavior of the directive was to issue a warning and continue compilation. The new behavior,
consistent with other compilers, is to issue an error message and immediately halt compilation.
The compiler quits and reports the failure.
On the SPARC platform, if the optimizer runs out of memory, it tries to recover by retrying the
current procedure at a lower level of optimization. The optimizer then resumes subsequent
routines at the original level specified in the -xOlevel option on the command line.
If you compile a single source file that contains many routines, the compiler might run out of
memory or swap space. Try reducing the level of optimization. Alternately, split the largest
procedures into separate files of their own.
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 4 Gbytes:
Each of these examples causes the optimizer to try to recover at 4 Gbytes 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:
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 “A.2
Option Reference” on page 212.
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
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 the Preface to this manual for a detailed explanation of the usage syntax.
47
3.2 General Guidelines
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 OS on
SPARC-based systems are identified as SPARC, and the features that are unique to the Solaris
OS on x86-based systems are identified as x86.
Option Action
–xMerge (SPARC) Merges the data segment with the text segment.
–xmodel Modifies the form of 64-bit objects for the Solaris x86 platforms
+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.
-xregs 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.
Option Action
Option Action
-xpagesize Sets the preferred page size for the stack and the heap.
-xpg Prepares the object code to collect data for profiling with
gprof(1).
Option Action
Option Action
–xlibmieee Causes libm to return IEEE 754 values for math routines in
exceptional cases.
Option Action
-xchar Eases the migration of code from systems where the char type is
defined as unsigned.
Option Action
–Rplst Builds dynamic library search paths into the executable file.
-xlang=l[,l] Includes the appropriate runtime libraries and ensures the proper
runtime environment for the specified language.
–xlibmieee Causes libm to return IEEE 754 values for math routines in
exceptional cases.
Note – The following options are either currently obsolete and so no longer accepted by the
compiler, or they will be removed in a future release.
Option Action
-xlicinfo Deprecated.
-ptr Ignored by the compiler. A future release of the compiler may reuse
this option using a different behavior.
Option Action
–dryrun Shows all the command lines issued by the driver to the compiler, but
does not compile.
–E Runs only the preprocessor on the C++ source files and sends result
to stdout. Does not compile.
-filt Suppresses the filtering that the compiler applies to linker error
messages.
–Qproduce sourcetype Causes the CC driver to produce output of the type sourcetype.
-xe Performs only syntax and semantic checking on the source file, but
does not produce any object or executable code.
Option Action
-g Instructs both the compiler and the linker to prepare the program for
performance analysis (and for debugging).
-m32|-m64 Specifies the memory model for the compiled binary object.
–xpagesize Sets the preferred page size for the stack and the heap.
–xspace (SPARC) Does not allow optimizations that increase code size.
Option Action
–E Runs only the preprocessor on the C++ source files and sends result to
stdout. Does not compile.
Option Action
–p Prepares the object code to collect data for profiling using prof.
Option Action
Option Action
Option Action
Option Action
61
62
4
C H A P T E R
Language Extensions
4
This chapter documents the language extensions specific to this compiler. The compiler does
not recognize some of the features described in this chapter unless you specify certain compiler
options on the command line. The relevant compiler options are listed in each section as
appropriate.
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.
By using these specifiers, you no longer need to use mapfiles for linker scoping. You can also
control the default setting for variable scoping by specifying -xldscope on the command line.
63
4.1 Linker Scoping
Value Meaning
__global Symbol definitions have global linker scoping and is the least restrictive linker
scoping. All references to the symbol bind to the definition in the first dynamic
load module that defines the symbol. This linker scoping is the current linker
scoping for extern symbols.
__symbolic Symbol definitions have symbolic linker scoping and is more restrictive than
global linker scoping. All references to the symbol from within the dynamic load
module being linked bind to the symbol defined within the module. Outside of
the module, the symbol appears as though it were global. This linker scoping
corresponds to the linker option -Bsymbolic. Although you cannot use
-Bsymbolic with C++ libraries, you can use the __symbolic specifier without
causing problems. See ld(1) for more information on the linker.
__hidden Symbol definitions have hidden linker scoping. Hidden linker scoping is more
restrictive than symbolic and global linker scoping. All references within a
dynamic load module bind to a definition within that module. The symbol will
not be visible outside of the module.
A symbol definition may be redeclared with a more restrictive specifier, but may not be
redeclared with a less restrictive specifier. A symbol may not be declared with a different
specifier once the symbol has been defined.
__global is the least restrictive scoping, __symbolic is more restrictive, and __hidden is the
most restrictive scoping.
All virtual functions must be visible to all compilation units that include the class definition
because the declaration of virtual functions affects the construction and interpretation of virtual
tables.
You can apply the linker scoping specifiers to struct, class, and union declarations and
definitions because C++ classes may require generation of implicit information, such as virtual
tables and run-time type information. The specifier, in this case, follows the struct, class, or
union keyword. Such an application implies the same linker scoping for all its implicit
members.
When taking advantage of this syntax with Sun C++, you should add the option
-xldscope=hidden to CC command lines. The result will be comparable to the results using
MSVC++. With MSVC++, __declspec(dllimport) is supposed to be used only on
declarations of external symbols, not on definitions. Example:
MSVC++ is lax about allowing dllimport on definitions, and the results using Sun C++ will be
different. In particular, using dllimport on a definition using Sun C++ results in the symbol
having global linkage instead of symbolic linkage. Dynamic libraries on Microsoft Windows do
not support global linkage of symbols. If you run into this problem, you can change the source
code to use dllexport instead of dllimport on definitions. You will then get the same results with
MSVC++ and Sun C++.
You must include the __thread specifier in the first declaration of the thread variable. Variables
that you declare with the __thread specifier are bound as they would be without the __thread
specifier.
You can declare variables only of static duration with the __thread specifier. Variables with
static duration include file global, file static, function local static, and class static member. You
should not declare variables with dynamic or automatic duration with the __thread specifier. A
thread variable can have a static initializer, but it cannot have a dynamic initializer or
destructors. For example, __thread int x = 4; is permitted, but __thread int x = f(); is not. A
thread variable should not have a type with non-trivial constructors and destructors. In
particular, a thread variable may not have type std::string.
The address-of operator (&) for a thread variable is evaluated at run time and returns the
address of the current thread’s variable. Therefore, the address of a thread variable is not a
constant.
The address of a thread variable is stable for the lifetime of the corresponding thread. Any
thread in the process can freely use the address of a thread variable during the variable’s lifetime.
You cannot use a thread variable’s address after its thread terminates. All addresses of a thread’s
variables are invalid after the thread’s termination.
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.
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.
Note – On 64-bit architectures, it is possible for an enum to require a size that is larger than type
int. If that is the case, and if the forward declaration and the definition are visible in the same
compilation, the compiler will emit an error. If the actual size is not the assumed size and the
compiler does not see the discrepancy, the code will compile and link, but might not run
properly. Mysterious program behavior can occur, particularly if an 8-byte value is stored in a
4-byte variable.
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.
The -features=extensions option allows the use of an anonymous struct declaration, but
only as member of a union.
The following code is an example of an invalid anonymous struct declaration that compiles
when you use the -features=extensions option.
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;
Note that you can make the code valid by giving a name to each struct, such as:
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);
The temporary object is destroyed when the function returns. Ensuring that the address of the
temporary variable is not retained is the programmer’s responsibility. In addition, the data that
is stored in the temporary variable (for example, by f1) is lost when the temporary variable is
destroyed.
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
Specifying this attribute for struct and union types is equivalent to specifying the packed
attribute on each of the structure or union members.
In the following example struct my_packed_struct's members are packed closely together,
but the internal layout of its s member is not packed. To do that, struct my_unpacked_struct
would also need to be packed.
struct my_unpacked_struct
{
char c;
int i;
;
You may only specify this attribute on the definition of a enum, struct or union, and not on a
typedef that does not also define the enumerated type, structure or union.
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.
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
71
5.1 Header Files
Note – Early versions of C++ defined the macro c_plusplus instead of __ cplusplus. The
macro c_plusplus is no longer defined.
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
main.cc
When a file using a template includes a file that contains both the template’s declaration and the
template’s definition, the file that uses the template also has the definitions-included
organization. For example:
twice.h
#ifndef TWICE_H
#define TWICE_H
template <class Number>
Number twice(Number original);
template <class Number> Number twice( Number original )
{ return original + original; }
#endif
main.cc
#include “twice.h”
int main()
{ return twice(-3); }
Note – It is very important to make your template headers idempotent. (See “5.1.2 Idempotent
Header Files” on page 72.)
twice.h
#ifndef TWICE_H
#define TWICE_H
template <class Number>
Number twice(Number original);
#endif TWICE_H
twice.cc
main.cc
#include “twice.h”
int main( )
{ return twice<int>( -3 ); }
Template definition files must not include any non-idempotent header files and often need not
include any header files at all. (See “5.1.2 Idempotent Header Files” on page 72.) Note that not
all compilers support the definitions-separate model for templates.
Because a separate definitions file is a header file, it might be included implicitly in many files. It
therefore should not contain any function or variable definitions, unless they are part of a
template definition. A separate definitions file can include type definitions, including typedefs.
Note – Although source-file extensions for template definition files are commonly used (that is,
.c, .C, .cc, .cpp, .cxx, or .c++), template definition files are header files. The compiler includes
them automatically if necessary. Template definition files should not be compiled
independently.
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
“7.5 Template Definition Searching” on page 98” 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.
75
6.2 Class Templates
Because template definitions often appear in header files, a template definition might be
repeated in several compilation units. All definitions, however, must be the same. This
restriction is called the One-Definition Rule.
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
This example shows definitions of function members of the String class template.
#include <string.h>
template <unsigned Size> int String<Size>::length( )
{int len = 0;
while (len < Size && data[len]!= ’\0’) len++;
return len;}
Array<int> int_array(100);
The declaration in this example creates the short_string variable using the String template.
String<8> short_string("hello");
You can use template class member functions as you would any other member function
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.
The preceding example defines a sort function over the predeclared Array class template
objects. The next example shows the actual use of the sort function.
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;}}
The following code shows examples of partial specialization of the primary template.
Name resolution is complex. Consequently, you should not rely on nonlocal names, except
those provided in a pervasive global environment. That is, use only nonlocal names that are
declared and defined the same way everywhere. In the following example, the template function
converter uses the nonlocal names intermediary and temporary. These names have different
definitions in use1.cc and use2.cc, and will probably yield different results under different
compilers. For templates to work reliably, all nonlocal names (intermediary and temporary in
this case) must have the same definition everywhere.
use_common.h
// Common template definition
template <class Source, class Target>
Target converter(Source source)
{temporary = (intermediary)source;
return (Target)temporary;}
use1.cc
typedef int intermediary;
int temporary;
#include "use_common.h"
use2.cc
typedef double intermediary;
unsigned int temporary;
#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.
array.h
template <class Type> class Array {
Type* data;
int size;
public:
Array(int sz);
int GetSize();
};
array.cc
template <class Type> Array<Type>::Array(int sz)
{size = sz; data = new Type[size];}
template <class Type> int Array<Type>::GetSize()
{return size;}
file1.cc
#include "array.h"
struct Foo {int data;};
Array<Foo> File1Data(10);
file2.cc
#include "array.h"
struct Foo {double data;};
Array<Foo> File2Data(20);
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.
array.h
// generates undefined error for the operator<< function
#ifndef ARRAY_H
#define ARRAY_H
#include <iosfwd>
array.cc
#include <stdlib.h>
#include <iostream>
template<class T>
std::ostream&
operator<<(std::ostream& out, const array<T>& rhs)
{return out <<’[’ << rhs.size <<’]’;}
main.cc
#include <iostream>
#include "array.h"
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;
}
Note that there is no error message during compilation because the compiler reads the
following as the declaration of a normal function that is a friend of the array class.
Because operator<< is really a template function, you need to supply a template declaration for
prior to the declaration of template class array. However, because operator<< has a
parameter of type array<T>, you must precede the function declaration with a declaration of
array<T>. The file array.h must look like this:
#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
is interpreted as:
Consider the following example with make files a.cc, b.cc, x.h, and x.cc. Note that this
example is meaningful only if you specify -instances=extern:
........
Makefile
........
CCC = CC
all: a b
a:
$(CCC) -I. -instances=extern -c a.cc
$(CCC) -instances=extern -o a a.o
b:
$(CCC) -I. -instances=extern -c b.cc
$(CCC) -instances=extern -o b b.o
clean:
/bin/rm -rf SunWS_cache *.o a b
...
x.h
...
template <class T> class X {
public:
int open();
int create();
static int variable;
};
...
x.cc
...
template <class T> int X<T>::create() {
return variable;
}
...
a.cc
...
#include "x.h"
int main()
{
X<int> temp1;
temp1.open();
temp1.create();
}
...
b.cc
...
#include "x.h"
int main()
{
X<int> temp1;
temp1.create();
}
If you build both a and b, add a make clean between the two builds. The following commands
result in an error:
example% make a
example% make b
example% make a
example% make clean
example% make b
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.
91
7.2 Repository Administration
■ There are few instances referenced in more than one or two compilation units.
Static, deprecated . See below.
■ Global instances, the default, are suitable for all development, and perform best when
objects reference a variety of instances.
■ 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 “6.3 Template Instantiation” on page 79.
Note – If you are compiling and linking in separate steps and you specify -instance=extern for
the compilation step, you must also specify it for the link step.
The disadvantage of this method is that the cache must be cleared whenever changing programs
or making significant program changes. The cache is a bottleneck for parallel compilation, as
when using dmake because access to the cache must be restricted to one compilation at a time.
Also, you can only build one program within a directory.
It can take longer to determine whether a valid template instance is already in the cache than
just to create the instance in the main object file and discard it later if needed.
Specify external linkage with the -instances=extern 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:
Note – The -instances=static option is deprecated. There is no longer any reason to use
-instances=static, because -instances=global now gives you all the advantages of static
without the disadvantages. This option was provided in earlier compilers to overcome
problems that no longer exist.
With the static instances method, all instances are placed within the current compilation unit.
As a consequence, templates are reinstantiated during each recompilation; instances are not
saved to the template repository.
The disadvantage of this method is that it does not follow language semantics and makes
substantially larger objects and executables.
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.
The advantage of this method is that incorrect source code commonly accepted by other
compilers is now also accepted in this mode. In particular, references to static variables from
within a template instances are not legal, but commonly accepted.
The disadvantage of this method is that individual object files may be larger, due to copies of
template instances in multiple files. If you compile some object files for debug using the -g
option, and some without, it is hard to predict whether you will get a debug or non-debug
version of a template instance linked into the program.
Template instances receive global linkage. These instances are visible and usable outside the
current compilation unit.
Specify global instances with the -instances=global option (this is the default).
The advantage of this method is that you have the least amount of template compilation and
smallest object sizes.
Template instances receive global linkage. These instances are visible and usable outside the
current compilation unit. The linker recognizes and discards duplicates.
The cache directory is contained within the directory in which the object files are placed. You
can change the name of the cache directory by setting the SUNWS_CACHE_NAME environment
variable. Note that the value of the SUNWS_CACHE_NAME variable must be a directory name and
not a path name. This is because the compiler automatically places the template cache directory
under the object file directory so the compiler already has a path.
The simplest, though most conservative, way to ensure that 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.
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.
In addition, the template repository tracks changes in your compilation. For example, if you
have the— DDEBUG flag set to define the name DEBUG, the database tracks this. If you omit this flag
on a subsequent compile, the compiler reinstantiates those templates on which this dependency
is set.
Note – If you remove the source code of a template or stop using a template, instances of the
template remain in the cache. If you change the signature of a function template, instances
using the old signature remain in the cache. If you run into strange behavior at compile or link
time due to these issues, clear the template cache and rebuild the program.
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 “5.2.1 Template Definitions Included” on page 73.
Note – If you use the -template=no%extdef option, the compiler will not search for separate
source files.
If a header file, foo.h, has template declarations, the compiler searches for a file called foo with
a C++ file extension (.C, .c, .cc, .cpp, .cxx, or .c++) by default. If the compiler finds such a file, it
includes the file automatically. See “7.5 Template Definition Searching” on page 98 for more
information on such searches.
If you have a file foo.cc that you don’t intend to be treated this way, you have two options:
■ Change the name of the .h or the .cc file to eliminate the name match.
■ Disable the automatic search for template definition files by specifying the
-template=no%extdef option. You must then include all template definitions explicitly in
your code and will not be able to use the “definitions separate” model.
Exception Handling
8
This chapter discusses the C++ compiler’s implementation of exception handling. Additional
information can be found in “11.2 Using Exceptions in a Multithreaded Program” on page 118.
For more information on exception handling, see The C++ Programming Language, Third
Edition, by Bjarne Stroustrup (Addison-Wesley, 1997).
The C++ standard supports synchronous exception handling with a termination model.
Termination means that once an exception is thrown, control never returns to the throw point.
101
8.3 Disabling Exceptions
■ 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().
The compiler uses the information provided in the exception specification to optimize code
production. For example, table entries for functions that do not throw exceptions are
suppressed, and runtime checking for exception specifications of functions is eliminated
wherever possible.
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.
For compatibility with exceptions as used in C++ release 4.2, the header <exception.h> is also
provided for use in standard mode. This header allows for a transition to standard C++ code
and contains declarations that are not part of standard C++. Update your code to follow the
C++ standard (using <exception> instead of <exception.h>) as development schedules
permit.
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.
The exception mechanism relies on comparing addresses. If you have two copies of something,
their addresses won’t compare equal, and the exception mechanism can fail because the
exception mechanism relies on comparing what are supposed to be unique addresses.
Cast Operations
9
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 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()
105
9.2 reinterpret_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.
{
A a1;
long l = reinterpret_cast<long>(&a1);
A* ap = reinterpret_cast<A*>(l); // safe
B* bp = reinterpret_cast<B*>(&a1); // unsafe
const A a2;
ap = reinterpret_cast<A*>(&a2); // error, const removed
}
9.3 static_cast
The expression static_cast<T>(v) converts the value of the expression v to type T. It can be
used for any type conversion that is allowed implicitly. In addition, any value can be cast to
void, and any implicit conversion can be reversed if that cast would be legal as an old-style cast.
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.
Note – When compiling in compatibility mode ( -compat[=4]), you must compile with -f
eatures=rtti if your program uses dynamic casts.
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 ambiguous. In addition,
unless the conversion is from a derived class to one of its base classes, the smallest part of the
hierarchy enclosing both T1 and T2 must be polymorphic (have at least one virtual function).
In the expression dynamic_cast<T>(v), v is the expression to be cast, and T is the type to which
it should be cast. T must be a pointer or reference to a complete class type (one for which a
definition is visible), or a pointer to cv void, where cv is an empty string, const, volatile, or
const volatile.
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
}
In the presence of virtual inheritance and multiple inheritance of a single base class, the actual
dynamic cast must be able to identify a unique match. If the match is not unique, the cast fails.
For example, given the additional class definitions:
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);
}
The null-pointer error return of dynamic_cast is useful as a condition between two bodies of
code—one to handle the cast if the type guess is correct, and one if it is not.
In compatibility mode (-compat[=4]), if runtime type information has not been enabled with
the -features=rtti compiler option, the compiler converts dynamic_cast to static_cast
and issues a warning.
Dynamic cast is necessarily slower than an appropriate design pattern, such as conversion by
virtual functions. See Design Patterns: Elements of Reusable Object-Oriented Software by Erich
Gamma (Addison-Wesley, 1994).
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, and this chapter does not repeat such
valuable information, but discusses only those performance techniques that strongly affect the
C++ compiler.
Write functions to minimize the number of temporary objects as long as your programs remain
comprehensible. Techniques include using explicit variables rather than implicit temporary
objects and using reference parameters rather than value parameters. Another technique is to
implement and use operations such as += rather than implementing and using only + and =. For
example, the first line below introduces a temporary object for the result of a + b, while the
second line does not.
T x = a + b;
T x(a); x += b;
111
10.2 Using Inline Functions
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.
For most compilers, passing objects directly can result in faster execution. This execution
improvement is particularly noticeable with small value classes, such as complex numbers or
probability values. You can sometimes improve program efficiency by designing classes that are
more likely to be passed directly than indirectly.
In compatibility mode (-compat[=4]), a class is passed indirectly if it has any one of the
following:
■ A user-defined constructor
■ A virtual function
■ A virtual base class
■ A base that is passed indirectly
■ A non-static data member that is passed indirectly
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.
x86 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.
This optimization is most productive when the values can reside in registers, as is the case with
primitive types. The optimization may also be productive for memory-based values because the
reduced aliasing gives the compiler more opportunity to optimize.
This optimization may be counter productive if the member variable is often passed by
reference, either explicitly or implicitly.
On occasion, the desired semantics of a class requires explicit caching of member variables, for
instance when there is a potential alias between the current object and one of the member
function’s arguments. For example:
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.
For more information about multithreading, see the Multithreaded Programming Guide, the
Tools.h++ User’s Guide, and the Standard C++ Library User’s Guide.
See also the OpenMP API User's Guide for information on using OpenMP shared memory
paralellization directives to create multithreaded programs.
117
11.2 Using Exceptions in a Multithreaded Program
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 any thread (see “8.2 Specifying Runtime Errors” on
page 101).
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. The library handles that
locking automatically. You are only required to lock when making an object available to
multiple threads explicitly, either by passing references between threads or by using global or
static objects.
The following describes the locking (synchronization) mechanism used internally in the C++
Standard Library to ensure correct behavior in the presence of multiple threads.
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.
The original core classes have been renamed with the prefix unsafe_. Table 11–1 lists the classes
that are the core of the iostream package.
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.
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 number in
octal. A width of nonzero is assumed to be the field width for
int buflen,
formatting. The returned value is not guaranteed to point to the
long num, beginning of the user-provided buffer.
int width)
char *hex_r (char *buf, Returns a pointer to the ASCII string that represents the number in
hexadecimal. A width of nonzero is assumed to be the field width
int buflen,
for formatting. The returned value is not guaranteed to point to the
long num, beginning of the user-provided buffer.
int width)
char *dec_r (char *buf, Returns a pointer to the ASCII string that represents the number in
decimal. A width of nonzero is assumed to be the field width for
int buflen,
formatting. The returned value is not guaranteed to point to the
long num, beginning of the user-provided buffer.
int width)
char *chr_r (char *buf, Returns a pointer to the ASCII string that contains character chr. If
the width is nonzero, the string contains width blanks followed by
int buflen,
chr. The returned value is not guaranteed to point to the beginning
long num, of the user-provided buffer.
int width)
char *form_r (char *buf, Returns a pointer of the string formatted by sprintf, using the
format string format and any remaining arguments. The buffer
int buflen,
must have sufficient space to contain the formatted string.
long num,
int width)
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.
Single-threaded applications that use iostream classes do not require special compiler or linker
options. By default, the compiler links with the libC library.
#include <iostream.h>
enum iostate {IOok, IOeof, IOfail};
In this example, the constructor of the stream_locker object sl locks the istream object istr.
The destructor of sl, called at the termination of read_number, unlocks istr.
#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);
When an iostream object is MT-safe, mutex locking is provided to protect the object’s member
variables. This locking adds unnecessary overhead to an application that only executes in a
single-threaded environment. To improve performance, you can dynamically switch an
iostream object to and from MT-safety. The following example makes an iostream object
MT-unsafe:
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();
int blen_unlocked();
char* pbase_unlocked();
char* eback_unlocked();
char* gptr_unlocked();
char* egptr_unlocked();
char* pptr_unlocked();
void setp_unlocked(char*, char*);
void setg_unlocked(char*, char*, char*);
void pbump_unlocked(int);
void gbump_unlocked(int);
void setb_unlocked(char*, char*, int);
int unbuffered_unlocked();
char *epptr_unlocked();
void unbuffered_unlocked(int);
int allocate_unlocked(int);
};
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)
char* str_r (char* buf, int buflen, const char* format, int width
= 0);
char* form_r (char* buf, int buflen, const char* format,...)
(instances of a class) maintain state by the values in their member variables. If a class object is
shared, it is vulnerable to changes made by other threads.
When a multithreaded application uses the iostream library and includes iostream.h, the
standard streams—cout, cin, cerr, and clog— are, by default, defined as global shared objects.
Since the iostream library is MT-safe, it protects the state of its shared objects from access or
change by another thread while a member function of an iostream object is executing.
However, the scope of MT-safety for an object is confined to the period in which the object’s
public member function is executing. For example,
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 “11.4.5 Object Locks” on page 130 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 “11.4.5 Object Locks” on page 130 for information about the stream_locker class.
■ Dedicate a stream object to a particular thread. The object thread is private by convention.
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.
To perform a sequence of operations on an iostream class object atomically, you must use
some form of locking. Locking adds some overhead even to a single-threaded application. The
decision whether to add locking or make iostream objects private to a thread depends on the
thread model chosen for the application: Are the threads to be independent or cooperating?
■ If each independent thread is to produce or consume data using its own iostream object,
the iostream objects are private to their respective threads and locking is not required.
■ If the threads are to cooperate (that is, they are to share the same iostream object), then
access to the shared object must be synchronized and some form of locking must be used to
make sequential operations atomic.
Objects of class stream_locker can be used to make a sequence of operations on a stream object
atomic. For example, the code shown in the example below seeks to find a position in a file and
reads the next block of data.
#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.
An alternative way to use a stream_locker object is to explicitly define the mutual exclusion
region. In the following example, to make the I/O operation and subsequent error checking
atomic, lock and unlock member function calls of a vbstream_locker object are used.
{
...
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
}
■ Extending the formatting state of an ios object by using the member functions iword and
pword in class ios. However, a problem can occur if more than one thread is sharing the
same index to an iword or pword function. To make the threads MT-safe, use an appropriate
locking scheme.
■ Locking member functions that return the value of a member variable greater in size than a
char.
#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);
The example application creates up to 255 threads. Each thread reads a different input file, one
line at a time, and outputs the line to an output file, using the standard output stream, cout. The
output file, which is shared by all threads, is tagged with a value that indicates which thread
performed the output operation.
#include <stdlib.h>
#include <stdio.h>
#include <iostream.h>
#include <fstream.h>
#include <thread.h>
struct thread_args {
char* filename;
int thread_tag;
};
}
return 0;
}
// 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]);
}
Libraries
137
138
12
C H A P T E R
Using Libraries
1 2
Libraries provide a way to share code among several applications and a way to reduce the
complexity of very large applications. The 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.
The following table lists the libraries that are shipped with the C++ compiler and the modes in
which they are available.
139
12.2 Libraries Provided With the C++ Compiler
Note – Do not redefine or modify any of the configuration macros for STLport, Rogue Wave or
Sun Microsystems C++ libraries. The libraries are configured and built in a way that works with
the C++ compiler. libCstd and Tool.h++ are configured to inter-operate so modifying the
configuration macros results in programs that will not compile, will not link, or do not run
properly.
If your compiler 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.
Note – Much of the standard library depends on using standard iostreams. Using classic
iostreams in the same program can cause problems.
■ 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.
■ libstlport: This is the STLport implementation of the C++ standard library. You can use
this library instead of the default libCstd by specifying the option -library=stlport4.
However, you cannot use libstlport and libCstd in the same program. You must compile
and link everything, including imported libraries, using one or the other exclusively.
■ librwtool (Tools.h++): Tools.h++ is a C++ foundation class library from RogueWave.
Version 7 is provided. This library is obsolete and use of the library is deprecated in new
code. It is provided to accommodate programs written for C++ 4.2 that used RW Tools.h++.
■ libgc: This library is used in deployment mode or garbage collection mode. Simply linking
with the libgc library automatically and permanently fixes a program’s memory leaks.
When you link your program with the libgc library, you can program without calling free
or delete while otherwise programming normally. The garbage collection library has a
dependency on the dynamic load library so specify -lgc and -ldl when you link your
program.
Additional information can be found in the gcFixPrematureFrees(3) and
gcInitialize(3) man pages.
■ libdemangle: This library is used for demangling C++ mangled names.
To access man pages for version 4.2 of the C++ libraries, type:
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.
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<install_directory>/lib to ld by default (if the compiler is
installed in the standard location). You can use -norunpath to disable building the default path
for shared libraries into the executable.
Programs built for deployment should be built with -norunpath or an -R option that that
avoids looking in the compiler directory for libraries. (See “12.6 Using Shared Libraries” on
page 148).
■ Classic iostreams. This term refers to the iostreams library shipped with the C++ 4.0, 4.0.1,
4.1, and 4.2 compilers, and earlier with the cfront-based 3.0.1 compiler. There is no
standard for this library, but a lot of existing code uses it. This library is part of libC in
compatibility mode and is also available in libiostream in the standard mode.
■ Standard iostreams. This is part of the C++ standard library, libCstd, and is available only
in standard mode. It is neither binary-, nor source-compatible with the classic iostreams
library.
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;
}
The following command compiles in compatibility mode and links prog1.cc into an executable
program called prog1. The classic iostream library is part of libC, which is linked by default in
compatibility mode.
// 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 “Caveats:” on page 152. For more information about
libiostream, see “13.3.1 Redistribution and Supported STLport Libraries” on page 169.
For a full discussion of compilation modes, see the C++ Migration Guide.
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 work with the standard library. For
example, the following code was written for 4.2 and will compile in compatibility mode.
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)
For more information about using the complex arithmetic library, see Table 14–4.
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:
In this example, the -library option is not explicitly included in the command. In this case the
-library option is not necessary because the default setting for -library is Cstd,Crun in
standard mode (the default mode).
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 libm, and libc in the
Solaris 8, or Solaris 9 operating systems:
The order of the -l options is important. The– lCstd,– lCrun, and -lm options appear before
-lc.
Note – Linking the libCrun and libCstd statically is not recommended. The dynamic versions
in /usr/lib are built to work with the version of Solaris where they are installed.
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 “A.2.153 –xnolib” on
page 319 for more information. See Linker and Libraries Guide for more information about ld.
Note – Static versions of Solaris libraries in /lib and /usr/lib are no longer available. For
example this attempt to link libc statically will fail:
On Linux, these additional libraries are shipped as part of the C++ compiler:
■ libCrun.so.1
■ libCstd.so.1
■ libdemangle.so
■ libiostream.so.1
On Solaris, those additional libraries, along with some others, are installed as part of the Solaris
C++ runtime library package, SUNWlibC.
If your application uses any of the shared libraries that are shipped as part of the C++ compiler,
the CC driver arranges for a runpath (refer to the -R option) pointing to the location of the
library to be built into the executable. If the executable is later deployed to a different computer
where the same compiler version is not installed in the same location, the required shared
library will not be found.
At program start time, the library might not be found at all, or the wrong version of the library
might be used, leading to incorrect program behavior. In such a case, you should ship the
required libraries along with the executable, and build with a runpath that points to where they
will be installed.
The article Using and Redistributing Sun Studio Libraries in an Applicationcontains a full
discussion of this topic, along with examples and can be found at
http://developers.sun.com/sunstudio/documentation/techart/stdlibdistr.html
The compiler supports the STLport implementation of the standard library. See “13.3 STLport”
on page 168 for more information.
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.
The 17 standard headers inherited from C (<stdlib.h>, <stdio.h>, <string.h>, and so forth)
are tied tightly to the Solaris operating system and the basic Solaris runtime library libc, and
cannot reliably be replaced. The C++ versions of those headers (<cstdlib>, <cstdio>,
<cstring>, and so forth) are tied tightly to the basic C versions and cannot reliably be replaced.
During compiling, the -library=no%Cstd option prevents searching the directory where the
compiler’s own version of these headers is located.
On each program or library link, use the -library=no%Cstd option to prevent finding the
compiler’s own libCstd, the -L option to point to the directory where the replacement library
is, and the -l option to specify the replacement library. Example:
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 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 system prior to the Solaris 8 operating system, 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.
The name rewriting occurs only for the two forms of the 17 standard C headers and the 32
standard C++ headers, only when they appear in angle brackets and without any path specified.
If you use quotes instead of angle brackets, specify any path components, or specify some other
header, no rewriting occurs.
The following table illustrates common situations.
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 RogueWaveTM 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.
153
13.1 C++ Standard Library Header Files
The C++ compiler also supports STLport’s Standard Library implementation version 4.5.3.
libCstd is still the default library, but STLport’s product is available as an alternative. See “13.3
STLport” on page 168 for more information.
If you need to use your own version of the C++ standard library instead of one of the versions
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 “12.7 Replacing the C++ Standard Library” on
page 148.
For details about the standard library, see the Standard C++ Library User’s Guide and the
Standard C++ Class Library Reference.
<queue> Sequences supporting addition at the head and removal at the tail
Bidirectional_Iterators An iterator that can both read and write and can traverse a
container in both directions
Negators Function adaptors and function objects used to reverse the sense
of predicate function objects
Stream_Iterators Includes iterator capabilities for ostreams and istreams that allow
generic algorithms to be used directly on streams
adjacent_find Find the first adjacent pair of elements in a sequence that are
equivalent
basic_filebuf Class that associates the input or output sequence with a file
basic_ios A base class that includes the common functions required by all
streams
basic_ofstream Supports writing into named files or other devices associated with
a file descriptor
basic_streambuf Abstract base class for deriving various stream buffers to facilitate
control of character sequences
binary_negate A function object that returns the complement of the result of its
binary predicate
char_traits A traits class with types and operations for the basic_string
container and iostream classes
cin Controls input from a stream buffer associated with the object
stdin declared in <cstdio>
divides Returns the result of dividing its first argument by its second
equal_range Finds the largest subrange in a collection into which a given value
can be inserted without violating the ordering of the collection
equal_to A binary function object that returns true if its first argument
equals its second
filebuf Class that associates the input or output sequence with a file
find_first_of Finds the first occurrence of any value from one sequence in
another sequence
greater A binary function object that returns true if its first argument is
greater than its second
greater_equal A binary function object that returns true if its first argument is
greater than or equal to its second
insert_iterator An insert iterator used to insert items into a collection rather than
overwrite the collection
inserter An insert iterator used to insert items into a collection rather than
overwrite the collection
ios A base class that includes the common functions required by all
streams
ios_base Defines member types and maintains data for classes that inherit
from it
istreambuf_iterator Reads successive characters from the stream buffer for which it
was constructed
less A binary function object that returns true if tis first argument is
less than its second
less_equal A binary function object that returns true if its first argument is
less than or equal to its second
logical_and A binary function object that returns true if both of its arguments
are true
logical_not A unary function object that returns true if its argument is false
logical_or A binary function object that returns true if either of its arguments
are true
minus Returns the result of subtracting its second argument from its first
mismatch Compares elements from two sequences and returns the first two
elements that don’t match each other
multiplies A binary function object that returns the result of multiplying its
first and second arguments
negate Unary function object that returns the negation of its argument
not_equal_to A binary function object that returns true if its first argument is
not equal to its second
ofstream Supports writing into named files or other devices associated with
a file descriptor
ostream_iterator Stream iterators allow for use of iterators with ostreams and
istreams
ostreambuf_iterator Writes successive characters onto the stream buffer object from
which it was constructed
partition Places all of the entities that satisfy the given predicate before all of
the entities that do not
plus A binary function object that returns the result of adding its first
and second arguments
queue A container adaptor that behaves like a queue (first in, first out)
rotate Swaps the segment that contains elements from first through
middle-minus-one with the segment that contains the elements
from middle through last
rotate_copy Swaps the segment that contains elements from first through
middle-minus-one with the segment that contains the elements
from middle through last
stable_partition Places all of the entities that satisfy the given predicate before all of
the entities that do not, while maintaining the relative order of
elements in each group
stack A container adapter that behaves like a stack (last in, first out)
streambuf Abstract base class for deriving various stream buffers to facilitate
control of character sequences
strstreambuf Associates either the input sequence or the output sequence with a
tiny character array whose elements store arbitrary values
time_get_byname A time formatting facet for input, based on the named locales
time_put_byname A time formatting facet for output, based on the named locales
unary_negate A function object that returns the complement of the result of its
unary predicate
uninitialized_copy An algorithm that uses construct to copy values from one range to
another location
uninitialized_fill An algorithm that uses the construct algorithm for setting values
in a collection
uninitialized_fill_n An algorithm that uses the construct algorithm for setting values
in a collection
upper_bound Determines the last valid position for a value in a sorted container
wcin Controls input from a stream buffer associated with the object
stdin declared in <cstdio>
wfilebuf Class that associates the input or output sequence with a file
wios A base class that includes the common functions required by all
streams
wofstream Supports writing into named files or other devices associated with
a file descriptor
wstreambuf Abstract base class for deriving various stream buffers to facilitate
control of character sequences
13.3 STLport
Use the STLport implementation of the standard library if you wish to use an alternative
standard library to libCstd. You can issue the following compiler option to turn off libCstd
and use the STLport library instead:
■ -library=stlport4
This release includes both a static archive called libstlport.a and a dynamic library called
libstlport.so.
Consider the following information before you decide whether or not you are going to use the
STLport implementation:
■ STLport is an open source product and does not guarantee compatibility across different
releases. In other words, compiling with a future version of STLport may break applications
compiled with STLport 4.5.3. It also might not be possible to link binaries compiled using
STLport 4.5.3 with binaries compiled using a future version of STLport.
■ The stlport4, Cstd and iostream libraries provide their own implementation of I/O
streams. Specifying more than one of these with the -library option can result in
undefined program behavior.
■ Future releases of the compiler might not include STLport4. They might include only a later
version of STLport. The compiler option -library=stlport4 might not be available in
future releases, but could be replaced by an option referring to a later STLport version.
■ Tools.h++ is not supported with STLport.
■ STLport is binary incompatible with the default libCstd. If you use the STLport
implementation of the standard library, then you must compile and link all files, including
third-party libraries, with the option -library=stlport4. This means, for example, that
you cannot use the STLport implementation and the C++ interval math library
libCsunimath together. The reason for this is that libCsunimath was compiled with the
default library headers, not with STLport.
■ If you decide to use the STLport implementation, be certain to include header files that your
code implicitly references. The standard headers are allowed, but not required, to include
one another as part of the implementation.
■ You cannot use the STLport implementation if you compile with -compat=4.
The following test case does not compile with STLport because the code in the test case makes
unportable assumptions about the library implementation. In particular, it assumes that either
<vector> or <iostream> automatically include <iterator>, which is not a valid assumption.
#include <vector>
#include <iostream>
int main ()
{
vector <int> v1 (10);
vector <int> v3 (v1.size());
for (int i = 0; i < v1.size (); i++)
{v1[i] = i; v3[i] = i;}
vector <int> v2(v1.size ());
copy_backward (v1.begin (), v1.end (), v2.end ());
ostream_iterator<int> iter (cout, " ");
copy (v2.begin (), v2.end (), iter);
cout << endl;
return 0;
}
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:man -s 3CC4name
The predefined iostreams are fully buffered, except for cerr. See “14.3.1 Output Using
iostream” on page 173 and “14.3.2 Input Using iostream” on page 176.
171
14.2 Basic Structure of iostream Interaction
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.
iomanip.h Declares manipulators: values you insert into or extract from iostreams to
have different effects. Includes iostream.h.
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 insertion operator is overloaded for all built-in types, and the value represented by
someValue is converted to its proper output representation. If, for example, someValue is a
float value, the << operator converts the value to the proper sequence of digits with a decimal
point. Where it inserts float values on the output stream, << is called the float inserter. In
general, given a type X, << is called the X inserter. The format of output and how you can control
it is discussed in the ios(3CC4) man page.
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.
operator<< takes ostream& (that is, a reference to an ostream) as its first argument and returns
the same ostream, making it possible to combine insertions in one statement.
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.
In general, the recommended way to handle errors is to periodically check the state of the
output stream in some central place. If there is an error, you should handle it in some way. This
chapter assumes that you define a function error, which takes a string and aborts the program.
error is not a predefined function. See “14.3.9 Handling Input Errors” on page 179 for an
example of an error function. You can examine the state of an iostream with the operator
!,which returns a nonzero value if the iostream is in an error state. For example:
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.3.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:
flush is an example of a kind of object known as a manipulator, which is a value that can be
inserted into an iostream to have some effect other than causing output of its value. It is really a
function that takes an ostream& or istream& argument and returns its argument after
performing some actions on it (see “14.7 Manipulators” on page 183).
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.
Class string defines its extraction operator in the following code example:
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.
You must also be sure the pointer points to allocated storage. For example, here is a common
error:
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();
Such a connection is not the default because there is a significant performance penalty when the
predefined streams are made unbuffered as part of the connection. You can use both stdio and
iostreams in the same program applied to different files. That is, you can write to stdout using
stdio routines and write to other files attached to iostreams. You can open stdio FILEs for
input and also read from cin so long as you don’t also try to read from stdin.
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);
This code:
■ Creates an ifstream object called fromFile with a default mode of ios::in and connects it
to thisFile. It opens thisFile.
■ Checks the error state of the new ifstream object and, if it is in a failed state, calls the error
function, which must be defined elsewhere in the program.
■ Creates an ofstream object called toFile with a default mode of ios::out and connects it
to thatFile.
■ Checks the error state of toFile as above.
■ Creates a char variable to hold the data while it is passed.
■ Copies the contents of fromFile to toFile one character at a time.
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 “14.10 Streambufs” on
page 187, 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.7 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.
3 ostr << ends Inserts a null (0) character. Useful when dealing
with strstream.
5 ostr << hex, istr >> hex Makes the integer conversion base 16.
6 ostr << oct, istr >> oct Make the integer conversion base 8.
8 ostr << setbase(n), istr >> Sets the conversion base to n (0, 8, 10, 16 only).
setbase(n)
9 ostr << setw(n), istr >> Invokes ios::width(n). Sets the field width to
setw(n) n.
10 ostr << resetiosflags(i), istr>> Clears the flags bitvector according to the bits
resetiosflags(i) set in i.
11 ostr << setiosflags(i), istr >> Sets the flags bitvector according to the bits set
setiosflags(i) in i.
12 ostr << setfill(c), istr >> Sets the fill character (for padding a field) to c.
setfill(c)
13 ostr << setprecision(n), istr >> Sets the floating-point precision to n digits.
setprecision(n)
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.
#include <iostream.h>
#include <iomanip.h>
istream& skipon(istream &is) {
is.setf(ios::skipws, ios::skipws);
return is;
}
istream& skipoff(istream& is) {
is.unsetf(ios::skipws);
return is;
}
...
int main ()
{
int x,y;
cin >> skipon >> x >> skipoff >> y;
return 1;
}
//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.10 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.
■ A put pointer, which points just before the position where the next character will be stored
■ A get pointer, which points just before the next character to be fetched
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.
ios Details parts of class ios, which functions as a base class for
iostreams. It contains state data common to all streams.
Buffer A word with two meanings, one specific to the iostream package and
one more generally applied to input and output.
When referring specifically to the iostream library, a buffer is an object
of the type defined by the class streambuf.
A buffer, generally, is a block of memory used to make efficient transfer
of characters for input of output. With buffered I/O, the actual transfer
of characters is delayed until the buffer is full or forcibly flushed.
An unbuffered buffer refers to a streambuf where there is no buffer in
the general sense defined above. This chapter avoids use of the term
buffer to refer to streambufs. However, the man pages and other C++
documentation do use the term buffer to mean streambufs.
Fstream An input or output stream specialized for use with files. Refers
specifically to a class derived from class iostream when printed in
courier font.
iostream library The library implemented by the include files iostream.h, fstream.h,
strstream.h, iomanip.h, and stdiostream.h. Because iostream is an
object-oriented library, you should extend it. So, some of what you can
do with the iostream library is not implemented.
Strstream An iostream specialized for use with character arrays. It refers to the
specific class when printed in courier font.
Complex numbers are numbers made up of a real part and an imaginary part. For example:
3.2 + 4i
1 + 3i
1 + 2.3i
In the degenerate case, 0 + 3i is an entirely imaginary number generally written as 3i, and 5 + 0i
is an entirely real number generally written as 5. You can represent complex numbers using the
complex data type.
Note – The complex arithmetic library ( libcomplex) is available only for compatibility mode (
-compat[ =4]). In standard mode (the default mode), complex number classes with similar
functionality are included with the C++ Standard Library libCstd.
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.
193
15.2 Type complex
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.
If you declare a complex variable without specifying parameters, the first constructor is used
and the variable is initialized, so that both parts are 0. The following example creates a complex
variable whose real and imaginary parts are both 0:
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 “15.3 Mathematical Functions” on page 196). The polar
function creates a complex value given the polar coordinates magnitude and angle.
+-/*=
The subtraction operator (-) has its usual binary and unary meanings.
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.
complex polar(double mag, double ang=0.0) Takes a pair of polar coordinates that
represent the magnitude and angle of a
complex number and returns the
corresponding complex number.
complex pow(double b, const complex exp) Takes two arguments: pow(b, exp). It raises
b to the power of exp.
complex pow(const complex b, int exp)
complex pow(const complex b, double exp)
complex pow(const complex b, const
complex exp)
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 function complex_error takes a reference to type c_exception and is called by the
following complex arithmetic library functions:
■ exp
■ log
■ log10
■ sinh
■ cosh
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).
Default error handling is described in the man pages cplxtrig(3CC4) and cplxexp(3CC4) It is
also summarized in the following table.
log, log10 If the argument is zero, sets errno to EDOM and returns a
huge complex number.
For basic information on extractors and inserters, see “14.2 Basic Structure of iostream
Interaction” on page 172 and “14.3.1 Output Using iostream” on page 173.
For input, the complex extractor >> extracts a pair of numbers (surrounded by parentheses and
separated by a comma) from the input stream and reads them into a complex object. The first
number is taken as the value of the real part; the second as the value of the imaginary part. For
example, given the declaration and input statement:
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 input usually consists of a pair of numbers in parentheses separated by a comma; white
space is optional. If you provide a single number, with or without parentheses and white space,
the extractor sets the imaginary part of the number to zero. Do not include the symbol i in the
input text.
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.
Not all arithmetic operations and conversions are implicit, or even defined, however. For
example, complex numbers are not well-ordered, mathematically speaking, and complex
numbers can be compared for equality only.
complex a, b;
a == b; // OK
a != b; // OK
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
1 6
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.
Linking dynamically with shared libraries has several advantages over linking statically with
archive libraries:
■ The size of the executable is smaller.
203
16.2 Building Static (Archive) Libraries
■ 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 operating system 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:
The– xar flag causes CC to create a static (archive) library. The– o directive is required to name
the newly created library. The compiler examines the object files on the command line,
cross-references the object files with those known to the template repository, and adds those
templates required by the user’s object files (along with the main object files themselves) to the
archive.
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.
The -G option specifies the construction of a dynamic library. The -o option specifies the file
name for the library. The -h option specifies an internal name for the shared library. The -Kpic
option specifies that the object files are to be position-independent.
The CC -G command does not pass any -l options to the linker, ld. To ensure proper
initialization order, a shared library must have an explicit dependency on each other shared
library it needs. To create the dependencies, use a -l option for each such library. Typical C++
shared libraries will use one of the following sets of options:
To be sure you have listed all needed dependencies, build the library with the -zdefs option.
The linker will issue an error message for each missing symbol definition. To provide the
missing definitions, add a -l option for those libraries.
To find out if you have included unneeded dependencies, use the commands
ldd -u -r mylib.so
ldd -U -r mylib.so
The exception mechanism relies on comparing addresses. If you have two copies of something,
their addresses won’t compare equal, and the exception mechanism can fail because the
exception mechanism relies on comparing what are supposed to be unique addresses.
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 the shared library uses exceptions and does not have a dependency on the C++ runtime
library, your C program might behave erratically.
Appendixes
209
210
A
A P P E N D I X
This appendix details the command-line options for the C++ compiler. The features described
apply to all platforms except as noted; features that are unique to the Solaris OS on
SPARC-based systems are identified as SPARC, and the features that are unique to the Solaris
and Linux OS on x86-based systems are identified as x86. Features limited to the Solaris OS only
are marked Solaris; features limited only to Linux OS are marked Linux. Note that references to
the Solaris OS imply the OpenSolaris OS as well.
The typographical conventions that are listed in the Preface 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.
Subsection Contents
Values If the option has one or more values, this section defines each value.
211
A.2 Option Reference
Warnings If there are cautions regarding use of the option, they are noted here,
as are actions that might cause unexpected behavior.
“Replace with” “Same as” If an option has become obsolete and has been replaced by another
option, the replacement option is noted here. Options described this
way may not be supported in future releases.
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
x86: Same as –xtarget=386. This option is provided for backward compatibility only.
A.2.2 –486
x86: 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 – Many system libraries are only available as dynamic libraries in the Solaris 64-bit
compilation environment. Therefore, do not use -Bstatic as the last toggle on the command
line.
A.2.4.1 Values
binding must be one of the following:
Value Meaning
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.
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 operating systems. 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:
Warnings
Never use -Bsymbolic with programs containing C++ code, use linker map files instead.
With -Bsymbolic, references in different modules can bind to different copies of what is
supposed to be one global object.
The exception mechanism relies on comparing addresses. If you have two copies of something,
their addresses won’t compare equal, and the exception mechanism can fail because the
exception mechanism relies on comparing what are supposed to be unique addresses.
If you compile and link in separate steps and are using the -Bbinding option, you must include
the option in the link step.
See also
–nolib, –staticlib, ld(1), “12.5 Statically Linking Standard Libraries” on page 147, 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.
A.2.5.1 Examples
If you enter CC -c x.cc, the x.o object file is generated.
If you enter CC -c x.cc -o y.o, the y.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, –xe
A.2.6 –cg{89|92}
Same as –xcg{89|92}.
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.
A.2.7.1 Values
The -compat option can have the following values.
Value Meaning
–compat=4 (Compatibility mode) Set language and binary compatibility to that of the
4.0.1, 4.1, and 4.2 compilers. Set the __cplusplus preprocessor macro to
1 and the __SUNPRO_CC_COMPAT preprocessor macro to 4.
Defaults
If the –compat option is not specified, –compat=5 is assumed.
Interactions
You cannot use the standard libraries in compatibility mode (-compat[=4]).
Use of –compat[=4] with any of the following options is not supported.
■ -Bsymbolic
■ -features=[no%]strictdestrorder
■ -features=[no%]tmplife
■ -library=[no%]iostream
■ -library=[no%]Cstd
■ -library=[no%]Crun
■ -library=[no%]rwtools7_std
■ -xarch=native64, -xarch=generic64, -xarch=v9, -xarch=v9a, or -xarch=v9b
Use of –compat=5 with any of the following options is not supported.
■ -Bsymbolic
■ +e
■ features=[no%]arraynew
■ features=[no%]explicit
■ features=[no%]namespace
■ features=[no%]rtti
■ library=[no%]complex
■ library=[no%]libC
■ -vdelx
Warnings
When building a shared library do not use -Bsymbolic.
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
Under the C++ language rules, the compiler can choose whether actually to inline a call to an
inline function. The C++ compiler inlines calls to an inline function unless:
A.2.8.1 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
A.2.9 -Dname[=def]
Defines the macro symbol name to the preprocessor.
Using this option is equivalent to including a #define directive at the beginning of the source.
You can use multiple -D options.
A.2.9.1 Values
The following table shows the predefined macros. You can use these values in such
preprocessor conditionals as #ifdef.
__DATE__
__FILE__
__LINE__
__TIME__
__cplusplus
__unix
_WCHAR_T
SPARC __SUN_PREFETCH=1
__SunOS_OSversion _OSversion
__SVR4
__sparc
__sun
x86 i386
linux
__amd64
__gnu__linux__
__linux
__linux__
__x86_64
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.
A.2.10.1 Values
Value Meaning
Defaults
If no -d option is specified, –dy is assumed.
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 operating systems. Applications
must link with the dynamic libraries in these cases.
Warnings
This option causes fatal errors if you use it in combination with dynamic libraries. Most system
libraries are only available as dynamic libraries.
See also
ld(1), Linker and Libraries Guide
A.2.11 –dalign
(SPARC)-dalign is equivalent to -xmemalign=8s. See “A.2.151 -xmemalign=ab” on page 316
for more information.
A.2.11.1 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 CC driver to show, but not execute, the subcommands constructed by the
compilation driver.
A.2.13 –E
Runs the preprocessor on source files; does not compile.
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.
This option causes preprocessor-type line number information to be included in the output.
A.2.13.1 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 “A.2.13.1 Examples” on page 221
int main () {
int x;
x=power(2, 10);
}
.
example% CC -E foo.cc
#4 "foo.cc"
template < > int power (int, int);
int main () {
int x;
x = power (2, 10);
}
Warnings
Output of this option might not be usable as input to a C++ compilation if the code contains
templates under the "definitions-separate" model.
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).
A.2.14.1 Values
The +e option can have the following values.
Value Meaning
1 Creates virtual tables for all defined classes with virtual functions.
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
A.2.15 -erroff[=t]
This command suppresses C++ compiler warning messages and has no effect on error
messages. This option applies to all warning messages whether or not they have been designated
by -errwarn to cause a non-zero exit status.
A.2.15.1 Values
t is a comma-separated list that consists of one or more of the following: tag, no%tag, %all,
%none. Order is important; for example, %all,no%tag suppresses all warning messages except
tag. The following table lists the -erroff values:
Value Meaning
tag Suppresses the warning message specified by this tag. You can display the tag
for a message by using the -errtags=yes option.
Defaults
The default is -erroff=%none. Specifying -erroff is equivalent to specifying -erroff=%all.
Examples
For example, -erroff=tag suppresses the warning message specified by this tag. On the other
hand, -erroff=%all,no%tag suppresses all warning messages except the messages identified by
tag.
You can display the tag for a warning message by using the -errtags=yes option.
Warnings
Only warning messages from the C++ compiler front-end that display a tag when the -errtags
option is used can be suppressed with the -erroff option.
See Also
-errtags, -errwarn
A.2.16 -errtags[=a]
Displays the message tag for each warning message of the C++ compiler front-end that can be
suppressed with the -erroff option or made a fatal warning with the -errwarn option.
Warnings
Messages from the C++ compiler driver and other components of the compilation system do
not have error tags, and cannot be suppressed with -erroff or made fatal with -errwarn.
See Also
-erroff, -errwarn
A.2.17 -errwarn[=t]
Use -errwarn to cause the C++ compiler to exit with a failure status for the given warning
messages.
A.2.17.1 Values
t is a comma-separated list that consists of one or more of the following: tag, no%tag, %all,
%none. Order is important; for example %all,no%tag causes cc to exit with a fatal status if any
warning except tag is issued.
Value Meaning
tag Cause CC to exit with a fatal status if the message specified by this tag is issued as a
warning message. Has no effect if tag is not issued.
no%tag Prevent CC from exiting with a fatal status if the message specified by tag is issued only
as a warning message. Has no effect if the message specified by tag is not issued. Use this
option to revert a warning message that was previously specified by this option with tag
or %all from causing cc to exit with a fatal status when issued as a warning message.
%all Cause CC to exit with a fatal status if any warning messages are issued. %all can be
followed by no%tag to exempt specific warning messages from this behavior.
%none Prevents any warning message from causing CC to exit with a fatal status should any
warning message be issued.
Defaults
The default is -errwarn=%none. If you specify -errwarn alone, it is equivalent to
-errwarn=%all.
Warnings
Only warning messages from the C++ compiler front-end that display a tag when the -errtags
option is used can be specified with the -errwarn option to cause the compiler to exit with a
failure status.
The warning messages generated by the C++ compiler change from release to release as the
compiler error checking improves and features are added. Code that compiles using
-errwarn=%all without error may not compile without error in the next release of the
compiler.
See Also
-erroff, -errtags, -xwe
A.2.18 –fast
This option is a macro that can be effectively used as a starting point for tuning an executable
for maximum runtime performance. -fast is a macro that can change from one release of the
compiler to the next and expands to options that are target platform specific. Use the -dryrun
or -xdryrun option to examine the expansion of -fast, and incorporate the appropriate
options of -fast into the ongoing process of tuning the executable.
This option is a macro that selects a combination of compilation options for optimum
execution speed on the machine upon which the code is compiled.
A.2.18.1 Expansions
This option provides near maximum performance for many applications by expanding to the
following compilation options.
–fns X X
–fsimple=2 X X
–nofstore - X
-xarch X X
-xbuiltin=%all X X
-xcache X X
-xchip X X
–xlibmil X X
–xlibmopt X X
–xmemalign X -
–xO5 X X
-xregs=frameptr - X
–xtarget=native 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:
Correct:
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.
Object binaries compiled with the -fast option are 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.
In previous SPARC releases, the -fast macro expanded to -fsimple=1. Now it expands to
-fsimple=2.
To display the expansion of —fast on any platform, run the command CC —dryrun —fast
See also
-fns, -fsimple, -ftrap=%none, -xlibmil, -nofstore, -xO5, -xlibmopt, -xtarget=native
A.2.19 –features=a[,a...]
Enables/disables various C++ language features named in a comma-separated list.
A.2.19.1 Values
In both compatibility mode (-compat[=4]) and standard mode (the default mode), a can have
the following values.
TABLE A–6 The -features Values for Compatibility Mode and Standard Mode
Value Meaning
%all All the -features options that are valid for the specified mode
(compatibility mode or standard 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.
TABLE A–6 The -features Values for Compatibility Mode and Standard Mode (Continued)
Value Meaning
[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.
[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
“8.3 Disabling Exceptions” on page 102. 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. This feature is not
yet implemented, but the export keyword is recognized.
[no%]extensions [Do not] allow nonstandard code that is commonly accepted by other
C++ compilers. See Table 3–17 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%]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.
TABLE A–6 The -features Values for Compatibility Mode and Standard Mode (Continued)
Value Meaning
[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.
In standard mode (the default mode), a can have the following additional values.
Value Meaning
[no%]tmplife [Do not] Clean up the temporary objects that are created by an
expression at the end of the full expression, as defined in the
ANSI/ISO C++ Standard. (When -features=no%tmplife is in
effect, most temporary objects are cleaned up at the end of their
block.) The default is no%tmplife in compat=4 mode and
tmplife in standard mode.
Value Meaning
[no%]arraynew [Do not] Recognize array forms of operator new and operator delete
(for example, operator new [ ] (void*)). When enabled, the macro
__ARRAYNEW=1. When not enabled, the macro is not defined. The default
is no%arraynew.
[no%]explicit [Do not] Recognize the keyword explicit. The default is no%explicit.
[no%]namespace [Do not] Recognize the keywords namespace and using. The default is
no%namespace.
The purpose of -features=namespace is to aid in converting code to
standard mode. By enabling this option, you get error messages if you
use these keywords as identifiers. The keyword recognition options
allow you to find uses of the added keywords without having to compile
in standard mode.
[no%]rtti [Do not] Allow runtime type information (RTTI). RTTI must be
enabled to use the dynamic_cast<> and typeid operators. For
-compat=4 mode, the default is no%rtti. Otherwise, the default is
-features=rtti, and the option -features=no%rtti is not allowed.
Note – The [no%]castop setting is allowed for compatibility with makefiles written for the C++
4.2 compiler, but has no affect on later compiler versions. The new style casts ( const_cast,
dynamic_cast, reinterpret_cast, and static_cast) are always recognized and cannot be
disabled.
Defaults
If –features is not specified, the default in compatibility mode (-compat[=4]) is:
–features=%none,anachronisms,except,split_init,transitions
-features=%all,no%extensions,no%iddollar,no%tmplrefstatic
is assumed.
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
Warnings
Be careful when you specify -features=%all or -features=%none. The set of features can
change with each compiler release and with each patch. Consequently, you can get unintended
behavior.
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.
See also
Table 3–17 and the C++ Migration Guide
A.2.20 -filt[=filter[,filter...]]
Controls the filtering that the compiler normally applies to linker and compiler error messages.
A.2.20.1 Values
filter must be one of the following values.
Value Meaning
[no%]errors [Do not] Show the C++ explanations of the linker error messages. The
suppression of the explanations is useful when the linker diagnostics are
provided directly to another tool.
[no%]returns [Do not] Demangle the return types of functions. Suppression of this type of
demangling helps you to identify function names more quickly, but note that in
the case of co-variant returns some functions differ only in the return type.
[no%]stdlib [Do not] Simplify names from the standard library in both the linker and
compiler error messages. This makes it easier for you to recognize the names of
standard library template types.
Defaults
If you do not specify the -filt option, or if you specify -filt without any values, then the
compiler assumes -filt=%all.
Examples
The following examples show the effects of compiling this code with the -filt option.
// 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=errors,names,returns,stdlib 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.
#include <string>
#include <list>
int main()
{
std::list<int> l;
std::string s(l); // error here
}
Interactions
When you specify no%names, neither returns nor no%returns has an effect. That is, the
following options are equivalent:
■ -filt=no%names
■ -filt=no%names,no%returns
■ -filt=no%names,returns
A.2.21 –flags
Same as– xhelp=flags.
A.2.22 -fma[={none|fused}]
(SPARC) Enables automatic generation of floating-point, fused, multiply-add instructions.
-fma=none disables generation of these instructions. -fma=fused allows the compiler to attempt
to find opportunities to improve the performance of the code by using floating-point, fused,
multiply-add instructions.
The minimum requirements are -xarch=sparcfmaf and an optimization level of at least -xO2
for the compiler to generate fused multiply-add instructions. The compiler marks the binary
program if fused multiply-add instructions are generated in order to prevent the program from
executing on platforms that do not support them.
Fused multiply-adds eliminate the intermediate rounding step between the multiply and the
add. Consequently, programs may produce different results when compiled with -fma=fused,
although precision will tend to be increased rather than decreased.
A.2.23 –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).
A.2.23.1 Defaults
If –fnonstd is not specified, IEEE 754 floating-point arithmetic exceptions do not abort the
program, and underflows are gradual.
Expansions
x86: -fnonstd expands to -ftrap=common.
See also
–fns, –ftrap=common, Numerical Computation Guide.
A.2.24 –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.
This option provides a way of toggling the use of nonstandard or standard floating-point
mode following some other macro option that includes –fns, such as –fast.
On some SPARC devices, the nonstandard floating-point mode disables “gradual
underflow,” causing tiny results to be flushed to zero rather than to produce subnormal
numbers. It also causes subnormal operands to be silently replaced by zero.
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.
■ (x86) Selects SSE flush-to-zero mode and, where available, denormals-are-zero mode.
This option causes subnormal results to be flushed to zero. Where available, this option also
causes subnormal operands to be treated as zero.
This option has no effect on traditional x86 floating-point operations that do not utilize the
SSE or SSE2 instruction set.
A.2.24.1 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.
Warnings
When nonstandard mode is enabled, floating-point arithmetic can produce results that do not
conform to the requirements of the IEEE 754 standard.
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 x86 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.25 –fprecision=p
x86: 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.
A.2.25.1 Values
p must be one of the following values.
Value 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 single precision rounding mode causes results to be rounded to 24 significant bits, and
double precision rounding mode causes results to be rounded to 53 significant bits. In the
default extended precision mode, results are rounded to 64 significant bits. This mode controls
only the precision to which results in registers are rounded, and it does not affect the range. All
results in register are rounded using the full range of the extended double format. Results that
are stored in memory are rounded to both the range and precision of the destination format,
however.
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 x86 devices and only if used when compiling the main program.
On SPARC devices, this option is ignored.
A.2.26 –fround=r
Sets the IEEE rounding mode in effect at startup.
This option sets the IEEE 754 rounding mode that:
■ Can be used by the compiler in evaluating constant expressions
■ Is established at runtime during the program initialization
The meanings are the same as those for the ieee_flags subroutine, which can be used to
change the mode at runtime.
A.2.26.1 Values
r must be one of the following values.
Value Meaning
nearest Rounds towards the nearest number and breaks ties to even numbers.
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.27 –fsimple[=n]
Selects floating-point optimization preferences.
This option allows the optimizer to make simplifying assumptions concerning floating-point
arithmetic.
A.2.27.1 Values
If n is present, it must be 0, 1, or 2.
Value Meaning
1 Allow conservative simplification. The resulting code does not strictly conform to
IEEE 754, but numeric results of most programs are unchanged.
With -fsimple=1, the optimizer can assume the following:
■ IEEE754 default rounding/trapping modes do not change after process
initialization.
■ Computation producing no visible result other than potential floating-point
exceptions can be deleted.
■ Computation with infinities or NaNs as operands needs to propagate NaNs to
their results; that is, x*0 can be replaced by 0.
■ Computations do not depend on sign of zero.
With -fsimple=1, the optimizer is not allowed to optimize completely without
regard to roundoff or exceptions. In particular, a floating-point computation
cannot be replaced by one that produces different results when rounding modes
are held constant at runtime.
Defaults
If –fsimple is not designated, the compiler uses -fsimple=0.
If -fsimple is designated but no value is given for n, the compiler uses -fsimple=1.
Interactions
-fast implies– fsimple=2.
Warnings
This option can break IEEE 754 conformance.
See also
-fast
Techniques for Optimizing Applications: High Performance Computing written by Rajat Garg
and Ilya Sharapov for a more detailed explanation of how optimization can impact precision.
A.2.28 –fstore
x86:
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.
A.2.28.1 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.29 –ftrap=t[,t...]
Sets the IEEE trapping mode in effect at startup but does not install a SIGFPE handler. You can
use ieee_handler(3M) or fex_set_handling(3M) to simultaneously enable traps and install a
SIGFPE handler. If you specify more than one value, the list is processed sequentially from left
to right.
A.2.29.1 Values
t can be one of the following values.
Value 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.
Defaults
If you do not specify –ftrap, the compiler assumes –ftrap=%none.
Examples
–ftrap=%all,no%inexact means to set all traps except inexact.
Warnings
If you compile one routine with –ftrap=t, compile all routines of the program with the same
-ftrap=t option; otherwise, you might get unexpected results.
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), fex_set_handling(3M) man pages.
A.2.30 –G
Build a dynamic shared library instead of an executable file.
All source files specified in the command line are compiled with -xcode=pic13 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.
If you are creating a shared object by specifying -G along with other compiler options that must
be specified at both compile time and link time, make sure that those same options are also
specified at both compile time and link time when you link with the resulting shared object.
When you create a shared object, all the object files compiled with -xarch=v9, must also be
compiled with an explicit -xcode value as recommended in “A.2.119 –xcode=a” on page 292.
A.2.30.1 Interactions
The following options are passed to the linker 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++.
When you use the -G option, the compiler does not pass any default -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, you must pass -lCrun on the command line.
See also
-dy, -Kpic, -xcode=pic13, –ztext, ld(1) man page, “16.3 Building Dynamic (Shared)
Libraries” on page 205.
A.2.31 –g
Produces additional symbol table information for debugging with dbx(1) or the Debugger and
for analysis with the Performance Analyzer analyzer(1).
Instructs both the compiler and the linker to prepare the file or program for debugging and for
performance analysis.
A.2.31.1 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 “A.2.157 -xOlevel” on page 321.
If you use this option and the optimization level is -xO4 or higher, the compiler provides
best-effort symbolic information with full optimization.
When you specify this option, the +d option is specified automatically unless you also specify -O
or -xO.
Note – In previous releases, this option forced the compiler to use the incremental linker ( ild)
by default instead of the linker ( ld) for link-only invocations of the compiler. That is, with -g,
the compiler’s default behavior was to automatically invoke ild in place of ld whenever you
used the compiler to link object files, unless you specified -G or source files on the command
line. This is no longer the case. The incremental linker is no longer available.
To use the full capabilities of the 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
Program Performance Analysis Tools 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,– xs, analyzer(1) man page, er_src(1) man page, ld(1) man page, Debugging a
Program With dbx (for details about stabs), Program Performance Analysis Tools.
A.2.32 –g0
Compiles and links for debugging, but does not disable inlining.
This option is the same as –g, except that +d is disabled and dbx cannot step into inlined
functions.
If you specify -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.
A.2.33 –H
Prints path names of included files.
On the standard error output (stderr), this option prints, one per line, the path name of each
#include file contained in the current compilation.
This is a linker option, passed to ld. In general, the name after -h should be exactly the same as
the one after –o. A space between the –h and name is optional.
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.
When a shared library is built without the-h option, the runtime loader looks only for the file
name of the library. You can replace the library with a different library with the same file name.
If the shared library has an intrinsic name, the loader checks the intrinsic name when loading
the file. If the intrinsic name does not match, the loader will not use the replacement file.
A.2.34.1 Examples
example% CC -G -o libx.so.1 -h libx.so.1 a.o b.o c.o
A.2.35 –help
Same as -xhelp=flags.
A.2.36 -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 quote-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 “12.7.5
Standard Header Implementation” on page 150 .
A.2.36.1 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 “12.7
Replacing the C++ Standard Library” on page 148.
If –ptipath is not used, the compiler looks for template files in –Ipathname.
Use –Ipathname instead of –ptipath.
This option accumulates instead of overrides.
Warnings
Never specify the compiler installation area, /usr/include, /lib, or /usr/lib, as search
directories.
See also
-I-
A.2.37 -I-
Change the include-file search rules to the following:
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 “12.7.5
Standard Header Implementation” on page 150 .
A.2.37.1 Examples
The following example shows the results of using -I- when compiling prog.cc.
prog.cc
#include "a.h"
#include <b.h>
#include "c.h"
c.h
#ifndef _C_H_1
#define _C_H_1
int c1;
#endif
inc/a.h
#ifndef _A_H
#define _A_H
#include "c.h"
int a;
#endif
inc/b.h
#ifndef _B_H
#define _B_H
#include <c.h>
int b;
#endif
inc/c.h
#ifndef _C_H_2
#define _C_H_2
int c2;
#endif
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 that they appear in the command
line. When processing the #include "c.h" statement in inc/a.h, the compiler includes the
./c.h header file instead of the inc/c.h header file.
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.
Never specify the compiler installation area, /usr/include, /lib, or /usr/lib, as search
directories.
A.2.38 –i
Tells the linker, ld, to ignore any LD_LIBRARY_PATH setting.
main()
{
...
}
If you compile t.c with the command cc -include t.h t.c, the compilation proceeds as if the
source file contains the following:
#include "t.h"
main()
{
...
}
The first directory the compiler searches for filename is the current working directory and not
the directory containing the main source file, as is the case when a file is explicitly included. For
example, the following directory structure contains two header files with the same name, but at
different locations:
foo/
t.c
t.h
bar/
u.c
t.h
If your working directory is foo/bar and you compile with the command cc ../t.c -include
t.h, the compiler includes t.h from foo/bar, not foo/ as would be the case with a #include
directive from within the source file t.c.
If the compiler cannot find the file specified with -include in the current working directory, it
searches the normal directory paths for the file. If you specify multiple -include options, the
files are included in the order they appear on the command line.
A.2.40 -inline
Same as -xinline.
A.2.41 –instances=a
Controls the placement and linkage of template instances.
A.2.41.1 Values
a must be one of the following values.
Value Meaning
extern Places all needed instances into the template repository within comdat
sections and gives them global linkage. (If an instance in the repository is out
of date, it is reinstantiated.)
Note: If you are compiling and linking in separate steps and you specify
-instance=extern for the compilation step, you must also specify it for the
link step.
explicit Places explicitly instantiated instances into the current object file and gives
them global linkage. Does not generate any other needed instances.
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 global linkage. Does not generate any
other needed instances.
Defaults
If –instances is not specified, –instances=global is assumed.
See also
“7.2.4 Template Instance Placement and Linkage” on page 92.
A.2.42 –instlib=filename
Use this option to inhibit the generation of template instances that are duplicated in a library,
either shared or static, and the current object. In general, if your program shares large numbers
of instances with libraries, try -instlib=filename and see whether compilation time improves.
A.2.42.1 Values:
Use the filename argument to specify the library that you know contains the existing template
instances. The filename argument must contain a forward slash ’/’ character. For paths relative
to the current directory, use dot-slash ’./’.
Defaults:
The -instlib=filename option has no default and is only used if you specify it. This option can
be specified multiple times and accumulates.
Example:
Assume that the libfoo.a and libbar.so libraries instantiate many template instances that are
shared with your source file a.cc. Adding -instlib=filename and specifying the libraries helps
reduce compile time by avoiding the redundancy.
Interactions:
When you compile with -g, if the library specified with -instlib=file is not compiled with -g,
those template instances will not be debuggable. The workaround is to avoid -instlib=file
when you use -g.
Warning
If you specify a library with -instlib, you must link with that library.
See Also:
-template, -instances, -pti
A.2.43 –KPIC
SPARC: Same as –xcode=pic32.
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.44 –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.45 –keeptmp
Retains temporary files created during compilation.
A.2.46 –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.
A.2.46.1 Interactions
This option accumulates instead of overrides.
Warnings
Never specify the compiler installation area, /usr/include, /lib, or /usr/lib, as search
directories.
A.2.47 –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.
A.2.47.1 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.
See also
–Ldir, -mt, “11.4.8 An Example Application” on page 133, and Tools.h++ Class Library
Reference
A.2.48 –libmieee
Same as –xlibmieee.
A.2.49 –libmil
Same as -xlibmil.
A.2.50 -library=l[,l...]
Incorporates specified CC-provided libraries into compilation and linking.
A.2.50.1 Values
For compatibility mode (–compat[-4]]), l must be one of the following values.
Value Meaning
For standard mode (the default mode), l must be one of the following:
Value Meaning
[no%]Cstd [Do not] Use libCstd, the C++ standard library. [Do not]
Include the compiler-provided C++ standard library header
files.
Defaults
■ Compatibility mode (–compat[=4])
■ If –library is not specified, -library=libC is assumed.
■ The libC library is always included unless it is specifically excluded using
-library=no%libC.
Regardless of standard or compat mode, the libm and libc libraries are always included,
even if you specify -library=%none.
Examples
To link in standard mode without any C++ libraries (except libCrun), use:
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.
This option accumulates instead of overrides.
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.
You cannot use -library=sunperf and -xlic_lib=sunperf on the same command line.
You can use at most only one of -library=stlport4, or -library=Cstd options on any
command line.
Only one Rogue Wave tools library can be used at a time and you cannot use any Rogue Wave
tools library with -library=stlport4.
When you include the classic-iostreams Rogue Wave tools library in standard mode (the
default mode), you must also include libiostream (see the C++ Migration Guide for additional
information). You can use the standard-iostreams Rogue Wave tools library in standard mode
only. The following command examples show both valid and invalid use of the Rogue Wave
tools.h++ library options.
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.
Compatibility-mode programs that do not link the libC library cannot use all features of the
C++ language. Similarly, standard-mode programs that do not link Crun or any of the Cstd, or
stlport4 libraries, cannot use all features of the C++ language.
If -xnolib is specified, -library is ignored.
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 stlport4, Cstd, and iostream libraries provide their own implementation of I/O streams.
Specifying more than one of these with the -library option can result in undefined program
behavior. For more information about using STLport’s implementation, see “13.3 STLport” on
page 168.
The set of libraries is not stable and might change from release to release.
See also
–I, –l, –R, –staticlib, -xia, -xlang, –xnolib, “11.4.8 An Example Application” on
page 133, “Caveats:” on page 152, “13.3.1 Redistribution and Supported STLport Libraries” on
page 169, Tools.h++ User’s Guide, Tools.h++ Class Library Reference, Standard C++ Class
Library Reference, C++ Interval Arithmetic Programming Reference.
For information on using the -library=no%cstd option to enable use of your own C++
standard library, see “12.7 Replacing the C++ Standard Library” on page 148.
A.2.51 -m32|-m64
Specifies the memory model for the compiled binary object.
Use -m32 to create 32-bit executables and shared libraries. Use -m64 to create 64-bit executables
and shared libraries.
The ILP32 memory model (32-bit int, long, pointer data types) is the default on all Solaris
platforms and on Linux platforms that are not 64-bit enabled. The LP64 memory model (64-bit
long, pointer data types) is the default on Linux platforms that are 64-bit enabled. -m64 is
permitted only on platforms that are enabled for the LP64 model.
Object files or libraries compiled with -m32 cannot be linked with object files or libraries
compiled with-m64.
Modules that are compiled with -m32|-m64 must also be linked with -m32|-m64. For a complete
list of compiler options that must be specified at both compile time and at link time, see “3.3.3
Compile-Time and Link-Time Options” on page 50.
When compiling applications with large amounts of static data on x64 platforms, using -m64,
-xmodel=medium may also be required. Be aware that some Linux platforms do not support the
medium model.
Note that in previous compiler releases, the memory model, ILP32 or LP64, was implied by the
choice of the instruction set with -xarch. Starting with the Sun Studio 12 compilers, this is no
longer the case. On most platforms, just adding -m64 to the command line is sufficient to create
64-bit objects.
On Solaris, -m32 is the default. On Linux systems supporting 64-bit programs, -m64
-xarch=sse2 is the default.
A.2.52 -mc
Removes duplicate strings from the .comment section of the object file. If the string contains
blanks, the string must be enclosed in quotation marks. When you use the -mc option, the mcs
-c command is invoked.
A.2.53 –migration
Explains where to get information about migrating source code that was built for earlier
versions of the compiler.
A.2.54 –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.
A.2.54.1 Interactions
When using #pragma pack on a SPARC platform to pack denser than the type’s default
alignment, the -misalign option must be specified for both the compilation and the linking of
the application.
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.55 -mr[,string]
Removes all strings from the .comment section of the object file and, if string is supplied, places
string in that section. If the string contains blanks, the string must be enclosed in quotation
marks. When you use this option, the command mcs -d [-a string] is invoked.
A.2.56 –mt
Use this option to compile and link multithreaded code using the Solaris threads or POSIX
threads API. The -mt option assures that libraries are linked in the appropriate order.
This option passes -D_REENTRANT to the preprocessor.
To use Solaris threads, include the thread.h header file and compile with the —mt option. To
use POSIX threads on Solaris platforms, include the pthread.h header file and compile with the
—mt —lpthread options.
On Linux platforms, only the POSIX threads API is available. (There is no libthread on Linux
platforms.) Consequently, —mt on Linux platforms adds —lpthread instead of —lthread. To use
POSIX threads on Linux platforms, compile with —mt.
Note that when compiling with —G, neither —lthread nor —lpthread are automatically included
by —mt. You will need to explicitly list these libraries when building a shared library.
The —xopenmp option (for using the OpenMP shared-memory parallelization API) includes —mt
automatically.
If you compile with -mt and link in a separate step, you must use the -mt option in the link step
as well as the compile step. If you compile and link one translation unit with -mt, you must
compile and link all units of the program with -mt
A.2.57 –native
Same as –xtarget=native.
A.2.58 –noex
Same as –features=no%except.
A.2.59 –nofstore
x86: Disables forced precision of an expression.
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
A.2.60 –nolib
Same as –xnolib.
A.2.61 –nolibmil
Same as –xnolibmil.
A.2.62 –noqueue
(Obsolete) 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. This option is obsolete and is
ignored.
A.2.63 –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.
This option is recommended for building executables that will be shipped to customers who
may have a different path for the shared libraries that are used by the program. Refer to “12.6
Using Shared Libraries” on page 148
A.2.63.1 Interactions
If you use any shared libraries under the compiler installed area 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.64 –O
The -O macro now expands to -xO3 instead of -xO2.
The change in default yields higher run-time performance. However, -xO3 may be
inappropriate for programs that rely on all variables being automatically considered volatile.
Typical programs that might have this assumption are device drivers and older multi-threaded
applications that implement their own synchronization primitives. The work around is to
compile with -xO2 instead of -O.
A.2.65 –Olevel
Same as –xOlevel.
A.2.66 –o filename
Sets the name of the output file or the executable file to filename.
A.2.66.1 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.
The compiler reads from the template repositories corresponding to the object files that it reads.
For example, the following command reads from ./sub1/SunWS_Cache and
./sub2/SunWS_cache, and, if necessary, writes to ./SunWS_cache.
For more information, see “7.4 The Template Repository” on page 96.
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.67 +p
Ignore nonstandard preprocessor asserts.
A.2.67.1 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.68 –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.69 –p
Obsolete, see “A.2.165 –xpg” on page 331.
A.2.70 –pentium
x86: Replace with –xtarget=pentium.
A.2.71 –pg
Same as –xpg.
A.2.72 -PIC
SPARC: Same as –xcode=pic32.
A.2.73 –pic
SPARC: Same as –xcode=pic13.
A.2.74 –pta
Same as –template=wholeclass.
A.2.75 –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.
A.2.75.1 Interactions
This option accumulates instead of overrides.
See also
–Ipathname, and “7.5.2 Definitions Search Path” on page 98
A.2.76 –pto
Same as –instances=static.
A.2.77 –ptr
This option is obsolete and is ignored by the compiler.
A.2.77.1 Warnings
Even though the -ptr option is ignored, you should remove -ptr from all compilation
commands because, in a later release, it may be reused with a different behavior.
See also
For information about repository directories, see “7.4 The Template Repository” on page 96.
A.2.78 –ptv
Same as –verbose=template.
To pass multiple options, specify them in order as a comma-separated list. Options that are
passed to components with -Q might be reordered. Options that the driver recognizes are kept
in the correct order. Do not use -Q for options that the driver already recognizes. For example,
the C++ compiler recognizes the -z option for the linker (ld). If you issue a command like this
the -z options are passed in order to the linker. But if you specify the command like this
A.2.79.1 Values
phase must have one of the following values.
SPARC x86
ccfe ccfe
iropt iropt
cg ube
CClink CClink
ld ld
— ir2hf
fbe fbe
Examples
In the following command line, when ld is invoked by the CC driver, –Qoption passes the –i and
–m options to ld.
Warnings
Be careful to avoid unintended effects. For example,
is interpreted as
A.2.81 –qp
Same as –p.
Suffix Meaning
A.2.84 –Rpathname[:pathname…]
Builds dynamic library search paths into the executable file.
A.2.84.1 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).
Examine the output from —dryrun and the —R option passed to the linker, ld, to see the default
paths assumed by the compiler.
Interactions
This option accumulates instead of overrides.
If the LD_RUN_PATH environment variable is defined and the –R option is specified, then the path
from –R is scanned and the path from LD_RUN_PATH is ignored.
See also
–norunpath, Linker and Libraries Guide
A.2.85 –readme
Same as -xhelp=readme.
A.2.86 –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.87 –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.88 –sb
Obsolete and silently ignored.
A.2.89 –sbfast
Obsolete and silently ignored.
A.2.90 -staticlib=l[,l…]
Indicates which C++ libraries, specified by the -library option (including its defaults), by the
-xlang option, and by the -xia option, are to be linked statically.
A.2.90.1 Values
l must be one of the following values.
Value 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.
Warnings
The set of allowable values for library is not stable and might change from release to release.
The options -staticlib=Crun and -staticlib=Cstd do not work on 64-bit Solaris x86
platforms. Sun recommends against linking these libraries statically on any platform. In some
cases, static linking can prevent a program from working.
See also
-library, “12.5 Statically Linking Standard Libraries” on page 147
A.2.91 -sync_stdio=[yes|no]
Use this option when your run-time performance is degraded due to the synchronization
between C++ iostreams and C stdio. Synchronization is needed only when you use iostreams to
write to cout and stdio to write to stdout in the same program. The C++ standard requires
synchronization so the C++ compiler turns it on by default. However, application performance
is often much better without synchronization. If your program does not write to both cout and
stdout, you can use the option -sync_stdio=no to turn off synchronization.
A.2.91.1 Defaults:
If you do not specify -sync_stdio, the compiler sets it to -sync_stdio=yes.
Examples:
Consider the following example:
#include <stdio.h>
#include <iostream>
int main()
{
std::cout << "Hello ";
printf("beautiful ");
std::cout << "world!";
printf("\n");
}
Warnings:
This option is only effective for linking of executables, not for libraries.
A.2.92 –temp=path
Defines the directory for temporary files.
This option sets the path name of the directory for storing the temporary files which are
generated during the compilation process. The compiler gives precedence to the value set by
-tempover the value of TMPDIR.
A.2.93 –template=opt[,opt…]
Enables/disables various template options.
A.2.93.1 Values
opt must be one of the following values.
Value 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.
Defaults
If the -template option is not specified, -template=no%wholeclass,extdef is assumed.
Examples
Consider the following code:
int main() {
}
example%
When you specify -template=geninlinefuncs, even though the two member functions of S
are not called in the program, they are generated in the object file.
Example.o:
See also
“7.2.2 Whole-Class Instantiation” on page 92, “7.5 Template Definition Searching” on page 98
A.2.94 –time
Same as –xtime.
A.2.95 –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.
A.2.95.1 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.
All -U options are processed after any -D options that are present. That is, if the same name is
specified for both -D and -U on the command line, name is undefined, regardless of the order
the options appear.
See also
-D
A.2.96 –unroll=n
Same as –xunroll=n.
A.2.97 –V
Same as –verbose=version.
A.2.98 –v
Same as –verbose=diags.
A.2.99 –vdelx
Deprecated, do not use.
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.
The function _vector_deletex_ behaves the same as _vector_delete_ except that it takes a
third argument: the address of the destructor for the class. This third argument is not used by
the function, but is provided to be used by third-party vendors.
A.2.99.1 Default
The compiler generates a call to _vector_delete_ for expressions using delete[].
Warnings
This is an obsolete option that will be removed in future releases. Do not use this option unless
you have bought some software from a third-party vendor and the vendor recommends using
this option.
A.2.100 –verbose=v[,v…]
Controls compiler verbosity.
A.2.100.1 Values
v must be one of the following values.
Value Meaning
[no%]diags [Do not] Print the command line for each compilation pass.
[no%]version [Do not] Direct the CC driver to print the names and version
numbers of the programs it invokes.
Defaults
If –verbose is not specified, –verbose=%none is assumed.
Interactions
This option accumulates instead of overrides.
A.2.101 +w
Identifies code that might have unintended consequences. The +w option no longer generates a
warning if a function is too large to inline or if a declared program element is unused. These
warnings do not identify real problems in the source, and were thus inappropriate to some
development environments. Removing these warnings from +w enables more aggressive use of
+w in those environments. These warnings are still available with the +w2 option.
This option generates additional warnings about questionable constructs that are:
■ Nonportable
■ Likely to be mistakes
■ Inefficient
A.2.101.1 Defaults
If +w is not specified, the compiler warns about constructs that are almost certainly problems.
See also
–w, +w2
A.2.102 +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.
The +w2 option no longer warns about the use of implementation-dependent constructs in the
system header files. Because the system header files are the implementation, the warning was
inappropriate. Removing these warnings from +w2 enables more aggressive use of the option.
A.2.103 –w
Suppresses most warning messages.
This option causes the compiler not to print warning messages. However, some warnings,
particularly warnings regarding serious anachronisms, cannot be suppressed.
A.2.104 –Xm
Same as –features=iddollar.
A.2.105 –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.
A.2.105.1 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, Program Performance Analysis Tools.
A.2.106 -xaddr32
(Solaris x86/x64 only) The -xaddr32=yes compilation flag restricts the resulting executable or
shared object to a 32-bit address space.
An executable that is compiled in this manner results in the creation of a process that is
restricted to a 32-bit address space.
This option is only applicable to -m64 compilations and only on Solaris platforms supporting
SF1_SUNW_ADDR32 software capability. Since Linux kernels do not support address space
limitation, this option is not available on Linux.
When linking, if a single object file was compiled with -xaddr32=yes the whole output file is
assumed to be compiled with -xaddr32=yes.
A shared object that is restricted to a 32-bit address space must be loaded by a process that
executes within a restricted 32-bit mode address space.
For more information refer to the SF1_SUNW_ADDR32 software capabilities definition, described
in the Linker and Libraries Guide.
A.2.107 -xalias_level[=n]
(SPARC) The C++ compiler can perform type-based alias-analysis and optimizations when you
specify the following command:
■ -xalias_level[=n]
where n is any, simple, or compatible.
■ -xalias_level=any
At this level of analysis, the compiler assumes that any type may alias any other type.
However, despite this assumption, some optimization is possible.
■ -xalias_level=simple
The compiler assumes that simple types are not aliased. Specifically, a storage object with a
dynamic type that is one of the following simple types:
data pointer types function pointer types data member pointer types function member
pointer types
-xalias_level=compatible
The compiler assumes that layout-incompatible types are not aliased. A storage object is
only accessed through lvalues of the following types:
■ The dynamic type of the object
■ A constant or volatile qualified version of the dynamic type of the object, a type that is
the signed or unsigned type which corresponds to the dynamic type of the object
■ A type that is the signed or unsigned type which corresponds to the constant or
volatile qualified version of the dynamic type of the object
■ An aggregate or union type that includes one of the aforementioned types among its
members (including, recursively, a member of a subaggregate or contained union)
■ A type that is (possibly constant or volatile qualified) base class type of the dynamic
type of the object
A.2.107.1 Defaults
If you do not specify -xalias_level, the compiler sets the option to -xalias_level=any. If
you specify -xalias_level but do not provide a value, the compiler sets the option to
-xalias_level=compatible.
Interactions
The compiler does not perform type-based alias analysis at optimization level -xO2 and below.
Warning
If you are using reinterpret_cast or an equivalent old-style cast, the program may violate the
assumptions of the analysis. Also, union type punning, as shown in the following example,
violates the assumptions of the analysis.
union bitbucket{
int i;
float f;
};
A.2.108 -xannotate[=yes|no]
(Solaris) Instructs the compiler to create binaries that can later be transformed by binary
modification tools like binopt(1). Future binary analysis, code coverage and memory error
detection tools will also work with binaries built with this option.
Use the -xannotate=no option to prevent the modification of the binary file by these tools.
The -xannotate=yes option must be used with optimization level -xO1 or higher to be effective,
and it is only effective on systems with the new linker support library interface -ld_open(). If
the compiler is used on an operating system without this linker interface, such as the Solaris 9
OS, the compiler silently reverts to -xannotate=no. The new linker interface is available in
Solaris 10 patch 127111-07, Solaris 10 Update 5 and OpenSolaris.
The default is -xannotate=yes, but if either of the above conditions is not met, the default
reverts to -xannotate=no.
A.2.109 –xar
Creates archive libraries.
When building a C++ archive that uses templates, it is necessary to include in the archive those
template functions that are instantiated in the template repository. The template repository is
used only when at least one object file was compiled using the -instances=extern option.
Using this option automatically adds those templates to the archive as needed.
A.2.109.1 Values
Specify -xar to invokes ar -c -r and create an archive from scratch.
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
ar(1), Table 15–3
A.2.110 –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. This option does not guarantee use of any target–specific
instructions. However, use of this option may affect the portability of a binary program.
Note – Use the -m64 or -m32 option to specify the intended memory model, LP64 (64-bits) or
ILP32 (32-bits) respectively. The -xarch option no longer indicates the memory model, except
for compatibility with previous releases, as indicated below.
If you compile and link in separate steps, make sure you specify the same value for -xarch in
both steps. For complete list of all compiler options that must be specified at both compile time
and at link time, see “3.3.3 Compile-Time and Link-Time Options” on page 50.
Flag Meaning
generic Uses the instruction set common to most processors. This is the default, and is
equivalent to v8plus when compiling with —m32, and sparc with —m64.
generic64 Compile for good performance on most 64-bit platforms. (Solaris only).
This option is equivalent to -m64 -xarch=generic and is provided for
compatibility with earlier releases. Use -m64 to specify 64-bit compilation instead
of
-xarch=generic64.
native Compile for good performance on this system. The compiler chooses the
appropriate setting for the current system processor it is running on.
native64 Compile for good performance on this system (Solaris only). This option is
equivalent to -m64 -xarch=native and is provided for compatibility with earlier
releases.
sparc Compile for the SPARC-V9 ISA, but without the Visual Instruction Set (VIS), and
without other implementation-specific ISA extensions. This option enables the
compiler to generate code for good performance on the V9 ISA.
sparcvis Compile for SPARC-V9 plus the Visual Instruction Set (VIS) version 1.0, and with
UltraSPARC extensions. This option enables the compiler to generate code for
good performance on the UltraSPARC architecture.
sparcvis2 Enables the compiler to generate object code for the UltraSPARC architecture,
plus the Visual Instruction Set (VIS) version 2.0, and with UltraSPARC III
extensions.
sparcfmaf Enables the compiler to use instructions from the SPARC-V9 instruction set, plus
the UltraSPARC extensions, including the Visual Instruction Set (VIS) version
1.0, the UltraSPARC-III extensions, including the Visual Instruction Set (VIS)
version 2.0, and the SPARC64 VI extensions for floating-point multiply-add.
You must use -xarch=sparcfmaf in conjunction with fma=fused and some
optimization level to get the compiler to attempt to find opportunities to use the
multiply-add instructions automatically.
v7 (Obsolete)
Compile for the SPARC-V7 ISA. Current Solaris operating systems no longer
support the SPARC V7 architecture, and programs compiled with this option run
slower on current platforms.
The default is -xarch=v8plus.
Examples: SPARCstation 1, SPARCstation 2.
v8a (Obsolete)
Compile for the V8a version of the SPARC-V8 ISA. By definition, V8a means the
V8 ISA, but without the fsmuld instruction.
This option enables the compiler to generate code for good performance on the
V8a ISA.
Example: Any system based on the microSPARC I chip architecture
v8 (Obsolete)
Compile for the SPARC-V8 ISA. Enables the compiler to generate code for good
performance on the V8 architecture. Example: SPARCstation 10
v8plus Compile for the V8plus version of the SPARC-V9 ISA. By definition, V8plus
means the V9 ISA, but limited to the 32–bit subset defined by the V8plus ISA
specification, without the Visual Instruction Set (VIS), and without other
implementation-specific ISA extensions.
■ 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.
Example: Any system based on the UltraSPARC chip architecture
v8plusa Compile for the V8plusa version of the SPARC-V9 ISA. By definition, V8plusa
means the V8plus architecture, plus the Visual Instruction Set (VIS) version 1.0,
and with UltraSPARC extensions.
■ 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 V8 processor.
Example: Any system based on the UltraSPARC chip architecture
v8plusb Compile for the V8plusb version of the SPARC-V8plus ISA with UltraSPARC III
extensions.
Enables the compiler to generate object code for the UltraSPARC architecture,
plus the Visual Instruction Set (VIS) version 2.0, and with UltraSPARC III
extensions.
■ The resulting object code is in SPARC-V8+ ELF32 format and executes only
in a Solaris UltraSPARC III environment.
■ Compiling with this option uses the best instruction set for good performance
on the UltraSPARC III architecture.
For any particular choice, the generated executable may run much more slowly on earlier
architectures. Also, although quad-precision (long double) floating-point instructions are
available in many of these instruction set architectures, the compiler does not use these
instructions in the code it generates.
Flag Meaning
amd64 Is equivalent to -m64 -xarch=sse2 (Solaris only). Legacy makefiles and scripts
that use -xarch=amd64 to obtain the 64-bit memory model need only use -m64.
generic Uses the instruction set common to most processors. This is the default, and is
equivalent to pentium_pro when compiling with —m32, and sse2 with —m64.
generic64 Compile for good performance on most 64-bit platforms. (Solaris only). This
option is equivalent to -m64 -xarch=generic and is provided for compatibility
with earlier releases. Use -m64 to specify 64-bit compilation instead of
-xarch=generic64.
native Compile for good performance on this system. The compiler chooses the
appropriate setting for the current system processor it is running on.
native64 Compile for good performance on this system (Solaris only). This option is
equivalent to -m64 -xarch=native and is provided for compatibility with
earlier releases.
pentium_proa Adds the AMD extensions (3DNow!, 3DNow! extensions, and MMX
extensions) to the 32-bit pentium_pro architecture.
ssea Adds the AMD extensions (3DNow!, 3DNow! extensions, and MMX
extensions) to the 32-bit SSE architecture.
sse2a Adds the AMD extensions (3DNow!, 3DNow! extensions, and MMX
extensions) to the 32-bit SSE2 architecture.
ssse3 Supplements the pentium_pro, SSE, SSE2, and SSE3 instruction sets with the
SSSE3 instruction set.
sse4_1 Supplements the pentium_pro, SSE, SSE2, SSE3, and SSSE3 instruction sets
with the SSE4.1 instruction set.
sse4_2 Supplements the pentium_pro, SSE, SSE2, SSE3,SSSE3, and SSE4.1 instruction
sets with the SSE4.2 instruction set.
The legacy Sun-style parallelization pragmas are not available on x86. Use OpenMP instead. See
the Sun Studio OpenMP API User’s Guide for information on converting legacy parallelization
directives to OpenMP.
Programs compiled with -xarch set to sse, sse2, sse2a, sse3, or beyond must be run only on
platforms that provide these extensions and features.
If you compile and link in separate steps, always link using the compiler and using the same
-xarch setting to ensure that the correct startup routine is linked.
Numerical results on x86 may differ from results on SPARC due to the x86 80-bit floating-point
registers. To minimize these differences, use the -fstore option or compile with -xarch=sse2
if the hardware supports SSE2.
Numerical results can also differ between Solaris and Linux because the intrinsic math libraries
(for example, sin(x)) are not the same.
On systems prior to Solaris 10, no verification is done and it is the user's responsibility to ensure
objects built using these flags are deployed on suitable hardware.
Running programs compiled with these -xarch options on platforms that are not enabled with
the appropriate features or instruction set extensions could result in segmentation faults or
incorrect results occurring without any explicit warning messages.
This warning extends also to programs that employ .il inline assembly language functions or
__asm() assembler code that utilize SSE, SSE2, SSE2a, and SSE3 instructions and extensions.
A.2.110.5 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.110.6 Warnings
If you use this option with optimization, the appropriate choice can provide good performance
of the executable on the specified architecture. An inappropriate choice, however, might result
in serious degradation of performance or in a binary program that is not executable on the
intended target platform.
If you compile and link in separate steps, make sure you specify the same value for -xarch in
both steps.
A.2.111 -xautopar
Note – This option does not accept OpenMP parallelization directives. The Sun-specific MP
pragmas have been deprecated and are no longer supported. See the Sun Studio OpenMP API
User’s Guide for migration information to the directives of the standard.
(SPARC) Turns on automatic parallelization for multiple processors. Does dependence analysis
(analyze loops for inter-iteration data dependence) and loop restructuring. If optimization is
not at -xO3 or higher, optimization is raised to -xO3 and a warning is issued.
If you use -xautopar and compile and link in one step, then linking automatically includes the
microtasking library and the threads-safe C runtime library. If you use -xautopar and compile
and link in separate steps, then you must also link with -xautopar.
A.2.112 -xbinopt={prepare|off}
(SPARC) Instructs the compiler to prepare the binary for later optimizations, transformations
and analysis, see binopt(1). This option may be used for building executables or shared objects.
If you compile in separate steps, -xbinopt must appear on both compile and link steps:
If some source code is not available for compilation, this option may still be used to compile the
remainder of the code. It should then be used in the link step that creates the final binary. In
such a situation, only the code compiled with this option can be optimized, transformed or
analyzed.
A.2.112.1 Defaults
The default is -xbinopt=off.
Interactions
This option must be used with optimization level -xO1 or higher to be effective. There is a
modest increase in size of the binary when built with this option.
Compiling with -xbinopt=prepare and -g increases the size of the executable by including
debugging information.
A.2.113 -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. See the er_src(1) man page for an explanation of how to read compiler commentary
in object files to determine for which functions the compiler actually makes a substitution.
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.
A.2.113.1 Defaults
If the -xbuiltin option is not specified, then the compiler assumes -xbuiltin=%none.
If only -xbuiltin is specified, then the compiler assumes -xbuiltin=%all.
Interactions
The expansion of the macro -fast includes -xbuiltin=%all.
Examples
The following compiler command requests special handling of the standard library calls.
The following compiler command request that there be no special handling of the standard
library calls. Note that the expansion of the macro -fast includes -xbuiltin=%all.
A.2.114 –xcache=c
Defines cache properties for use by the optimizer. This option 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.
This release introduces an optional property [/ti] which sets the number of threads that can
share the cache.
A.2.114.1 Values
c must be one of the following values.
Value Meaning
Property Definition
Defaults
If –xcache is not specified, the default –xcache=generic is assumed. This value directs the
compiler to use cache properties for good performance on most SPARC processors, without
major performance degradation on any of them.
Examples
–xcache=16/32/4:1024/32/1 specifies the following:
See also
–xtarget=t
A.2.115 -xcg[89|92]
(SPARC) Obsolete, do not use this option. Current Solaris operating system software no longer
support SPARC V7 architecture. Compiling with this option generates code that runs slower on
current SPARC platforms. Use -O instead and take advantage of compiler defaults for -xarch,
-xchip, and -xcache.
A.2.116 -xchar[=o]
The option is provided solely for the purpose of easing the migration of code from systems
where the char type is defined as unsigned. Unless you are migrating from such a system, do not
use this option. Only code that relies on the sign of a char type needs to be rewritten to explicitly
specify signed or unsigned.
A.2.116.1 Values
You can substitute one of the following for o:
Value Meaning
signed Treat character constants and variables declared as char as signed. This
impacts the behavior of compiled code, it does not affect the behavior of
library routines.
s Equivalent to signed
unsigned Treat character constants and variables declared as char as unsigned. This
impacts the behavior of compiled code, it does not affect the behavior of
library routines.
u Equivalent to unsigned
Defaults
If you do not specify -xchar, the compiler assumes -xchar=s.
If you specify -xchar, but do not specify a value, the compiler assumes -xchar=s.
Interactions
The -xchar option changes the range of values for the type char only for code compiled with
-xchar. This option does not change the range of values for type char in any system routine or
header file. In particular, the value of CHAR_MAX and CHAR_MIN, as defined by limits.h, do not
change when this option is specified. Therefore, CHAR_MAX and CHAR_MIN no longer represent
the range of values encodable in a plain char.
Warnings
If you use -xchar=unsigned, be particularly careful when you compare a char against a
predefined system macro because the value in the macro may be signed. This is most common
for any routine that returns an error code which is accessed through a macro. Error codes are
typically negative values so when you compare a char against the value from such a macro, the
result is always false. A negative number can never be equal to any value of an unsigned type.
It is strongly recommended that you never use -xchar to compile routines for any interface
exported through a library. The Solaris ABI specifies type char as signed, and system libraries
behave accordingly. The effect of making char unsigned has not been extensively tested with
system libraries. Instead of using this option, modify your code so that it does not depend on
whether type char is signed or unsigned. The signedness of type char varies among compilers
and operating systems.
A.2.117 -xcheck[=i]
SPARC: Compiling with -xcheck=stkovf adds a runtime check for stack overflow of the main
thread in a singly-threaded program as well as slave-thread stacks in a multithreaded program.
If a stack overflow is detected, a SIGSEGV is generated. If your application needs to handle a
SIGSEGV caused by a stack overflow differently than it handles other address-space violations,
see sigaltstack(2).
A.2.117.1 Values
i must be one of the following:
Value Meaning
Defaults
If you do not specify -xcheck, the compiler defaults to -xcheck=%none.
If you specify -xcheck without any arguments, the compiler defaults to -xcheck=%none.
The -xcheck option does not accumulate on the command line. The compiler sets the flag in
accordance with the last occurrence of the command.
A.2.118 -xchip=c
Specifies target processor for use by the optimizer.
The –xchip option specifies timing properties by specifying the target processor. This option
affects:
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.
A.2.118.1 Values
c must be one of the following values.
Defaults
On most 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.119 –xcode=a
SPARC: Specifies the code address space.
Note – You should build shared objects by specifying -xcode=pic13 or -xcode=pic32. Shared
objects built without pic13 or pic32 will not work correctly, and might not build at all.
A.2.119.1 Values
a must be one of the following values.
Value 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. Do not use this value with dynamic
(shared) libraries.
abs64 SPARC: Generates 64-bit absolute addresses, which are slow, but have full
range. Available only on 64-bit architectures.
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.
To determine whether to use –xcode=pic13 or –xcode=pic32, check the size of the Global
Offset Table (GOT) by using elfdump -c (see the elfdump(1) man page for more information)
and for the section header, sh_name: .got. The sh_size value is the size of the GOT. If the GOT
is less than 8,192 bytes, specify -xcode=pic13, otherwise specify -xcode=pic32.
In general, use the following guidelines to determine how you should use -xcode:
■ If you are building an executable you should not use -xcode=pic13 or -xcode=pic32.
■ If you are building an archive library only for linking into executables you should not use
-xcode=pic13 or -xcode=pic32.
■ If you are building a shared library, start with– xcode=pic13 and once the GOT size exceed
8,192 bytes, use -xcode=pic32.
■ If you are building an archive library for linking into shared libraries you should just use
-xcode=pic32.
Defaults
The default is -xcode=abs32 for 32–bit architectures. The default for 64–bit architectures
is-xcode=abs44.
When building shared dynamic libraries, the default -xcode values of abs44 and abs32 will not
work with 64–bit architectures. Specify -xcode=pic13 or -xcode=pic32 instead. There are two
nominal performance costs with -xcode=pic13 and -xcode=pic32 on SPARC:
■ A routine compiled with either -xcode=pic13 or -xcode=pic32 executes a few extra
instructions upon entry to set a register to point at a table (_GLOBAL_OFFSET_TABLE_) used
for accessing a shared library’s global or static variables.
■ Each access to a global or static variable involves an extra indirect memory reference
through _GLOBAL_OFFSET_TABLE_. If the compile is done with -xcode=pic32, there are two
additional instructions per global and static memory reference.
When considering the above costs, remember that the use of -xcode=pic13 and -xcode=pic32
can significantly reduce system memory requirements, due to the effect of library code sharing.
Every page of code in a shared library compiled -xcode=pic13 or– xcode=pic32 can be shared
by every process that uses the library. If a page of code in a shared library contains even a single
non-pic (that is, absolute) memory reference, the page becomes nonsharable, and a copy of the
page must be created each time a program using the library is executed.
The easiest way to tell whether or not a .o file has been compiled with -xcode=pic13 or
–xcode=pic32 is with the nm command:
A.2.120 -xcrossfile[=n]
Obsolete, do not use. Use -xipo instead.
A.2.121 -xdebugformat=[stabs|dwarf]
The compiler is migrating the format of debugger information from the stabs format to the
dwarf format as specified in ’DWARF Debugging Information Format’. The default setting for
this release is -xdebugformat=stabs.
If you maintain software which reads debugging information, you now have the option to
transition your tools from the stabs format to the dwarf format.
Use this option as a way of accessing the new format for the purpose of porting tools. There is
no need to use this option unless you maintain software which reads debugger information, or
unless a specific tool tells you that it requires debugger information in one of these formats.
Value Meaning
If you do not specify -xdebugformat, the compiler assumes -xdebugformat=stabs. This option
requires an argument.
This option affects the format of the data that is recorded with the -g option. Some small
amount of debugging information is recorded even without -g, and the format of that
information is also controlled with this option. So -xdebugformat has an effect even when -g is
not used.
The dbx and Performance Analyzer software understand both stabs and dwarf format so using
this option does not have any effect on the functionality of either tool.
Note – This is a transitional interface so expect it to change in incompatible ways from release to
release, even in a minor release. The details of any specific fields or values in either stabs or
dwarf are also evolving.
See also the dumpstabs(1) and dwarfdump(1) man pages for more information.
A.2.122 -xdepend=[yes|no]
(SPARC) Analyzes loops for inter-iteration data dependencies and does loop restructuring,
including loop interchange, loop fusion, scalar replacement, and eliminationi of “dead array”
assignments.
On SPARC, -xdepend defaults to —xdepend=on for all optimization levels -xO3 and above.
Otherwise —xdepend defaults to —xdepend=off. Specifying an explicit setting of -xdepend
overrides any default setting.
Dependency analysis may help on single-processor systems. However, if you uese -xdepend on
single-processor systems, you should not also specify -xautopar , because the -xdepend
optimization will be done for a multiprocessor system.
A.2.123 -xdumpmacros[=value[,value...]]
Use this option when you want to see how macros are behaving in your program. This option
provides information such as macro defines, undefines, and instances of usage. It prints output
to the standard error (stderr), based on the order macros are processed. The -xdumpmacros
option is in effect through the end of the file or until it is overridden by the dumpmacros or
end_dumpmacros pragma. See “B.2.5 #pragma dumpmacros” on page 366.
A.2.123.1 Values
You can substitute the following arguments in place of value:
Value Meaning
[no%]loc [Do not] Print location (path name and line number) also for defs, undefs,
and use
[no%]conds [Do not] Print use information for macros used in conditional directives
[no%]sys [Do not] Print all macros defines, undefines, and use information for macros
in system header files
Note – The sub-options loc, conds, and sys are qualifiers for defs, undefs and use options. By
themselves, loc, conds, and sys have no effect. For example, -xdumpmacros=loc,conds,sys
has no effect.
Defaults
If you specify -xdumpmacros without any arguments, it means
-xdumpmacros=defs,undefs,sys. If you do not specify -xdumpmacros, it defaults to
-xdumpmacros=%none.
Examples
If you use the option -xdumpmacros=use,no%loc, the name of each macro that is used is printed
only once. However, if you want more detail, use the option -xdumpmacros=use,loc so the
location and macro name is printed every time a macro is used.
The following examples show the output for file t.c based on the defs, undefs, sys, and loc
arguments.
#define __SUNPRO_CC_COMPAT 5
#define __SUN_PREFETCH 1
#define FOO 1
#undef FOO
#define COMPUTE(a, b) a + b
The following examples show how the use, loc, and conds arguments report macro behavior in
file t.c:
See Also
Use the dumpmacros pragma and the end_dumpmacros pragma when you want to override the
scope of -xdumpmacros.
A.2.124 -xe
Checks only for syntax and semantic errors. When you specify -xe, the compiler does not
produce any object code. The output for -xe is directed to stderr.
Use the -xe option if you do not need the object files produced by compilation. For example, if
you are trying to isolate the cause of an error message by deleting sections of code, you can
speed the edit and compile cycle by using -xe.
A.2.125 -xF[=v[,v...]]
Enables optimal reordering of functions and variables by the linker.
This option instructs the compiler to place functions and/or data variables into separate section
fragments, which enables the linker, using directions in a mapfile specified by the linker’s -M
option, to reorder these sections to optimize program performance. Generally, this
optimization is only effective when page fault time constitutes a significant fraction of program
run time.
Reording of variables can help solve the following problems which negatively impact run-time
performance:
■ Cache and page contention caused by unrelated variables that are near each other in
memory.
■ Unnecessarily large work-set size as a result of related variables which are not near each
other in memory.
■ Unnecessarily large work-set size as a result of unused copies of weak variables that decrease
the effective data density.
Reordering variables and functions for optimal performance requires the following operations:
1. Compiling and linking with -xF.
2. Following the instructions in the “Program Performance Analysis Tools” manual regarding
how to generate a mapfile for functions or following the instructions in the “Linker and
Libraries Guide” regarding how to generate a mapfile for data.
3. Relinking with the new mapfile by using the linker’s -M option.
4. Re-executing under the Analyzer to verify improvement.
A.2.125.1 Values
v can be one or more of the following:
Value Meaning
[no%]gbldata [Do not] fragment global data (variables with external linkage) into separate
sections.
[no%]lcldata [Do not] fragment local data (variables with internal linkage) into separate
sections.
Defaults
If you do not specify -xF, the default is -xF=%none. If you specify -xF without any arguments,
the default is -xF=%none,func.
Interactions
Using -xF=lcldata inhibits some address calculation optimizations, so you should only use
this flag when it is experimentally justified.
See also
analyzer(1), debugger(1), ld(1) man pages
A.2.126 -xhelp=flags
Displays a brief description of each compiler option.
A.2.127 -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.128 -xhwcprof
(SPARC) Enables compiler support for hardware counter-based profiling.
When -xhwcprof is enabled, the compiler generates information that helps tools associate
profiled load and store instructions with the data-types and structure members (in conjunction
with symbolic information produced with -gto which they refer. It associates profile data with
the data space of the target, rather than the instruction space, and provides insight into behavior
that is not easily obtained from only instruction profiling.
You can compile a specified set of object files with -xhwcprof. However, -xhwcprof is most
useful when applied to all object files in the application. This will provide coverage to identify
and correlate all memory references distributed in the application’s object files.
If you are compiling and linking in separate steps, use -xhwcprof at link time as well. Future
extensions to -xhwcprof may require its use at link time.
-xhwcprof requires that optimization be turned on and that the debug data format be set to
DWARF (-xdebugformat=dwarf).
The combination of -xhwcprof and -g increases compiler temporary file storage requirements
by more than the sum of the increases due to -xhwcprof and -g specified alone.
The following command compiles example.cc and specifies support for hardware counter
profiling and symbolic analysis of data types and structure members using DWARF symbols:
For more information on hardware counter-based profiling, see the Program Performance
Analysis Tools manual.
A.2.129 -xia
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.
A.2.129.1 Expansions
The -xia option is a macro that expands to -fsimple=0 -ftrap=%none -fns=no
-library=interval. If you use intervals and override what is set by -xia by specifying a
different flag for -fsimple, -ftrap, -fns or -library, you may cause the compiler to exhibit
incorrect behavior.
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.
Warnings
If you use intervals and you specify different values for -fsimple, -ftrap, or -fns, then your
program may have incorrect behavior.
C++ interval arithmetic is experimental and evolving. The specifics may change from release to
release.
See Also
-library
A.2.130 -xinline[=func_spec[,func_spec...]]
Specifies which user-written routines can be inlined by the optimizer at -xO3 levels or higher.
A.2.130.1 Values
func_spec must be one of the following values.
Value Meaning
func_name Strongly request that the optimizer inline the function. If the function is
not declared as extern "C", the value of func_name must be mangled. You
can use the nm command on the executable file to find the mangled
function names. For functions declared as extern "C", the names are not
mangled by the compiler.
no%func_name When you prefix the name of a routine on the list with no%, the inlining of
that routine is inhibited. The rule about mangled names for func_name
applies to no%func_name as well.
Only routines in the file being compiled are considered for inlining unless you use
-xipo[=1|2]. The optimizer decides which of these routines are appropriate for inlining.
Defaults
If the -xinline option is not specified, the compiler assumes -xinline=%auto.
Examples
To enable automatic inlining while disabling inlining of the function declared int foo(), use
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.
Warnings
If you force the inlining of a function with -xinline, you might actually diminish
performance.
See Also
“A.2.136 -xldscope={v}” on page 310
A.2.131 -xinstrument=[no%]datarace
Specify this option to compile and instrument your program for analysis by the Thread
Analyzer. For more information on the Thread Analyzer, seetha(1) for details.
You can then use the Performance Analyzer to run the instrumented program with collect -r
races to create a data-race-detection experiment. You can run the instrumented code
standalone but it runs more slowly.
You can specify -xinstrument=no%datarace to turn off preparation of source code for the
thread analyzer. This is the default.
If you compile and link in separate steps, you must specify -xinstrument=datarace in both the
compilation and linking steps.
This option defines the preprocessor token __THA_NOTIFY. You can specify #ifdef
__THA_NOTIFY to guard calls to libtha(3) routines.
A.2.132 -xipo[={0|1|2}]
Performs interprocedural optimizations.
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 or libraries.
A.2.132.1 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.
In this example, interprocedural optimizations will be performed between one.cc, two.cc and
three.cc, and between main.cc and four.cc, but not between main.cc or four.cc and the
routines in mylib.a. (The first compilation may generate warnings about undefined symbols,
but the interprocedural optimizations will be performed because it is a compile and link step.)
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.
■ The calls to foo() from any routine in the set of object files are not interposed upon by a
different version of foo() defined outside this set of object files.
Do not compile with -xipo=2, if assumption 1 is not true for the given application.
As an example, consider interposing on the function malloc() with your own version and
compiling with -xipo=2. Consequently, all the functions in any library that reference malloc()
that are linked with your code have to be compiled with -xipo=2 also and their object files need
to participate in the link step. Since this might not be possible for system libraries, do not
compile your version of malloc with -xipo=2.
As another example, suppose that you build a shared library with two external calls, foo() and
bar() inside two different source files. Furthermore, suppose that bar() calls foo(). If there is a
possibility that foo() could be interposed at runtime, then do not compile the source file for
foo() or for bar() with -xipo=1 or -xipo=2. Otherwise, foo() could be inlined into bar(), which
could cause incorrect results.
See Also
-xjobs
A.2.133 -xipo_archive=[a]
The -xipo_archive option enables the compiler to optimize object files that are passed to the
linker with object files that were compiled with -xipo and that reside in the archive library (.a)
before producing an executable. Any object files contained in the library that were optimized
during the compilation are replaced with their optimized version.
Value Meaning
writeback The compiler optimizes object files passed to the linker with object files
compiled with -xipo that reside in the archive library (.a) before producing an
executable. Any object files contained in the library that were optimized
during the compilation are replaced with an optimized version.
For parallel links that use a common set of archive libraries, each link should
create its own copy of archive libraries to be optimized before linking.
readonly The compiler optimizes object files passed to the linker with object files
compiled with -xipo that reside in the archive library (.a) before producing an
executable.
The option -xipo_archive=readonly enables cross-module inlining and
interprocedural data flow analysis of object files in an archive library specified
at link time. However, it does not enable cross-module optimization of the
archive library's code except for code that has been inserted into other
modules by cross module inlining.
To apply cross-module optimization to code within an archive library,
-xipo_archive=writeback is required. Note that doing so modifies the
contents of the archive library from which the code was extracted.
none This is the default. There is no processing of archive files. The compiler does
not apply cross-module inlining or other cross-module optimizations to
object files compiled using -xipo and extracted from an archive library at link
time. To do that, both -xipo and either -xipo_archive=readonly or
-xipo_archive=writeback must be specified at link time.
If you do not specify a setting for -xipo_archive, the compiler sets it to -xipo_archive=none.
A.2.134 -xjobs=n
Specify the -xjobs option to set how many processes the compiler creates to complete its work.
This option can reduce the build time on a multi-cpu machine. Currently, -xjobs works only
with the -xipo option. When you specify -xjobs=n, the interprocedural optimizer uses n as the
maximum number of code generator instances it can invoke to compile different files.
A.2.134.1 Values
You must always specify -xjobs with a value. Otherwise an error diagnostic is issued and
compilation aborts.
Generally, a safe value for n is 1.5 multiplied by the number of available processors. Using a
value that is many times the number of available processors can degrade performance because
of context switching overheads among spawned jobs. Also, using a very high number can
exhaust the limits of system resources such as swap space.
Defaults
Multiple instances of -xjobs on the command line override each other until the right-most
instance is reached.
Examples
The following example compiles more quickly on a system with two processors than the same
command without the -xjobs option.
A.2.135 -xlang=language[,language]
Includes the appropriate runtime libraries and ensures the proper runtime environment for the
specified language.
A.2.135.1 Values
language must be either f77, f90, f95, or c99.
The f90 and f95 arguments are equivalent. The c99 argument invokes ISO 9899:1999 C
programming language behavior for objects that were compiled with cc -xc99=%all and are
being linked with CC.
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++
2. Fortran 95 (or Fortran 90)
3. Fortran 77
4. C or C99
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.
example% CC -xlang=f95...
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.
Warnings
Do not use -xnolib with -xlang.
If you are mixing parallel Fortran objects with C++ objects, the link line must specify the -mt
flag.
See also
-library, -staticlib
A.2.136 -xldscope={v}
Specify the -xldscope option to change the default linker scoping for the definition of extern
symbols. Changing the default can result in faster and safer shared libraries and executables
because the implementation are better hidden.
A.2.136.1 Values
v must be one of the following:
Value Meaning
global Global linker scoping is the least restrictive linker scoping. All references to
the symbol bind to the definition in the first dynamic load module that
defines the symbol. This linker scoping is the current linker scoping for
extern symbols.
symbolic Symbolic linker scoping and is more restrictive than global linker scoping.
All references to the symbol from within the dynamic load module being
linked bind to the symbol defined within the module. Outside of the module,
the symbol appears as though it is global. This linker scoping corresponds to
the linker option -Bsymbolic. Although you cannot use -Bsymbolic with
C++ libraries, you can use the -xldscope=symbolic without causing
problems. See ld(1) for more information on the linker.
hidden Hidden linker scoping is more restrictive than symbolic and global linker
scoping. All references within a dynamic load module bind to a definition
within that module. The symbol will not be visible outside of the module.
Defaults
If you do not specify -xldscope, the compiler assumes -xldscope=global. If you specify
-xldscope without any values, the compiler issues an error. Multiple instances of this option on
the command line override each other until the right most instance is reached.
Warning
If you intend to allow a client to override a function in a library, you must be sure that the
function is not generated inline during the library build. The compiler inlines a function if you
specify the function name with -xinline, if you compile at -xO4 or higher in which case
inlining can happen automatically, if you use the inline specifier, or if you are using cross-file
optimization.
For example, suppose library ABC has a default allocator function that can be used by library
clients, and is also used internally in the library:
If you build the library at -xO4 or higher, the compiler inlines calls to ABC_allocator that occur
in library components. If a library client wants to replace ABC_allocator with a customized
version, the replacement will not occur in library components that called ABC_allocator. The
final program will include different versions of the function.
Library functions declared with the __hidden or __symbolic specifiers can be generated inline
when building the library. They are not supposed to be overridden by clients. See “4.1 Linker
Scoping” on page 63.
Library functions declared with the __global specifier, should not be declared inline, and
should be protected from inlining by use of the -xinline compiler option.
See Also
-xinline, -xO, -xcrossfile
A.2.137 -xlibmieee
Causes libm to return IEEE 754 values for math routines in exceptional cases.
A.2.138 -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.
A.2.138.1 Interactions
This option is implied by the –fast option.
See also
-fast, Numerical Computation Guide
A.2.139 –xlibmopt
Uses library of optimized math routines. You must use default rounding mode by specifying
-fround=nearest when you use this option.
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.
A.2.139.1 Interactions
This option is implied by the –fast option.
See also
–fast, –xnolibmopt, -fround
A.2.140 –xlic_lib=sunperf
Deprecated, do not use. Specify -library=sunperf instead. See “A.2.50 -library=l[,l...]” on
page 252 for more information.
A.2.141 –xlicinfo
This option is silently ignored by the compiler.
A.2.142 -xlinkopt[=level]
Instructs the compiler to perform link-time optimization on the resulting executable or
dynamic library over and above any optimizations in the object files. These optimizations are
performed at link time by analyzing the object binary code. The object files are not rewritten but
the resulting executable code may differ from the original object codes.
You must use -xlinkopt on at least some of the compilation commands for -xlinkopt to be
useful at link time. The optimizer can still perform some limited optimizations on object
binaries that are not compiled with -xlinkopt.
-xlinkopt optimizes code coming from static libraries that appear on the compiler command
line, but it skips and does not optimize code coming from shared (dynamic) libraries that
appear on the command line. You can also use -xlinkopt when you build shared libraries
(compiling with -G).
A.2.142.1 Values
level sets the level of optimizations performed, and must be 0, 1, or 2. The optimization levels
are:
Value Meaning
If you compile in separate steps, -xlinkopt must appear on both compile and link steps:
Note that the level parameter is only used when the compiler is linking. In the example above,
the link optimizer level is 2 even though the object binaries are compiled with an implied level
of 1.
Defaults
Specifying -xlinkopt without a level parameter implies -xlinkopt=1.
Interactions
This option is most effective when you use it to compile the whole program, and with profile
feedback. Profiling reveals the most and least used parts of the code and building directs the
optimizer to focus its effort accordingly. This is particularly important with large applications
where optimal placement of code performed at link time can reduce instruction cache misses.
Typically, this compiles as follows:
For details on using profile feedback, see “A.2.170 -xprofile=p” on page 339.
Warnings
Do not use the -zcombreloc linker option when you compile with -xlinkopt.
Note that compiling with this option increases link time slightly. Object file sizes also increase,
but the size of the executable remains the same. Compiling with -xlinkopt and -g increases the
size of the executable by including debugging information.
A.2.143 -xloopinfo
This option shows which loops are parallelized and which are not. It is normally for use with the
-xautopar option.
A.2.144 –xM
Runs only the C++ preprocessor on the named C++ programs, requesting that the preprocessor
generate makefile dependencies and send the result to the standard output (see make(1) for
details about make files and dependencies).
However, -xM only reports dependencies of the included headers and not the associated
template definition files. You can use the .KEEP_STATE feature in your makefile to generate all
the dependencies in the .make.state file which the make utility creates.
A.2.144.1 Examples
For example:
#include <unistd.h>
void main(void)
{}
e.o: e.c
e.o: /usr/include/unistd.h
e.o: /usr/include/sys/types.h
e.o: /usr/include/sys/machtypes.h
e.o: /usr/include/sys/select.h
e.o: /usr/include/sys/time.h
e.o: /usr/include/sys/types.h
e.o: /usr/include/sys/time.h
e.o: /usr/include/sys/unistd.h
Interactions
If you specify -xM and -xMF, the compiler writes all makefile dependency information to the file
specified with -xMF. This file is overwritten each time the preprocessor writes to it.
See also
make(1S) (for details about makefiles and dependencies)
A.2.145 -xM1
Generates makefile dependencies like –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.
If you specify -xM1 and -xMF, the compiler writes all makefile dependency information to the
file specified with -xMF. This file is overwritten each time the preprocessor writes to it.
A.2.146 -xMD
Generates makefile dependencies like -xM but includes compilation. -xMD generates an output
file for the makefile-dependency information based on the input filename but with the addition
of a .d suffix. If you specify -xMD and -xMF, the preprocessor appends all makefile dependency
information to the file specified with -xMF.
A.2.147 -xMF
Use this option to specify a file for the makefile-dependency output. There is no way to specify
individual filenames for multiple input files with -xMF on the command line.
A.2.148 -xMMD
Use this option to generate makefile dependencies excluding system header files. This is the
same functionality as -xM1, but includes compilation. -xMMD generates an output file for the
makefile-dependency information based on the input filename but with the addition of a .d
suffix. If you specify both -xMMD and -xMF, the compiler uses the filename you provide instead.
A.2.149 –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.
The three options -xMerge -ztext -xprofile=collect should not be used together. While
-xMerge forces statically initialized data into read-only storage, -ztext prohibits
position-dependent symbol relocations in read-only storage, and -xprofile=collect
generates statically initialized, position-dependent symbol relocations in writable storage.
A.2.150 -xmaxopt[=v]
This command limits the level of pragma opt to the level specified. v is one of off, 1, 2, 3, 4, 5.
The default value is -xmaxopt=off which causes pragma opt to be ignored. If you specify
-xmaxopt without supplying an argument, that is the equivalent of specifying -xmaxopt=5.
If you specify both -xO and -xmaxopt, the optimization level set with -xO must not exceed the
-xmaxopt value.
A.2.151 -xmemalign=ab
(SPARC) Use the -xmemalign option to control the assumptions the compiler makes about the
alignment of data. By controlling the code generated for potentially misaligned memory
accesses and by controlling program behavior in the event of a misaligned access, you can more
easily port your code to SPARC.
Specify the maximum assumed memory alignment and behavior of misaligned data accesses.
There must be a value for both a (alignment) and b (behavior). a specifies the maximum
assumed memory alignment and b specifies the behavior for misaligned memory accesses.
For memory accesses where the alignment is determinable at compile time, the compiler
generates the appropriate load/store instruction sequence for that alignment of data.
For memory accesses where the alignment cannot be determined at compile time, the compiler
must assume an alignment to generate the needed load/store sequence.
If actual data alignment at runtime is less than the specified alignment, the misaligned access
attempt (a memory read or write) generates a trap. The two possible responses to the trap are
■ The OS converts the trap to a SIGBUS signal. If the program does not catch the signal, the
program aborts. Even if the program catches the signal, the misaligned access attempt will
not have succeeded.
■ The OS handles the trap by interpreting the misaligned access and returning control to the
program as if the access had succeeded normally.
A.2.151.1 Values
The following table lists the alignment and behavior values for -xmemalign
a b
You must specify -xmemalign whenever you want to link to an object file that was compiled
with the value of b set to either i or f. For a complete list of all compiler options that must be
specified at both compile time and at link time, see “3.3.3 Compile-Time and Link-Time
Options” on page 50.
Defaults
The following default values only apply when no -xmemalign option is present:
■ -xmemalign=8i for all v8 architectures.
■ -xmemalign=8s for all v9 architectures.
Here is the default when the -xmemalign option is present but no value is given:
■ -xmemalign=1i for all -xarch values.
Examples
The following table shows how you can use -xmemalign to handle different alignment
situations.
Command Situation
-xmemalign=1s All memory accesses are misaligned so trap handling is too slow.
-xmemalign=2i You want to check for possible odd-byte access and you want the
program to work.
A.2.152 -xmodel=[a]
(x86) The -xmodel option enables the compiler to modify the form of 64-bit objects for the
Solaris x86 platforms and should only be specified for the compilation of such objects.
This option is valid only when -m64 is also specified on 64–bit enabled x64 processors.
Value Meaning
small This option generates code for the small model in which the virtual
address of code executed is known at link time and all symbols are known
to be located in the virtual addresses in the range from 0 to 2^31 - 2^24 - 1.
kernel Generates code for the kernel model in which all symbols are defined to be
in the range from 2^64 - 2^31 to 2^64 - 2^24.
medium Generates code for the medium model in which no assumptions are made
about the range of symbolic references to data sections. Size and address of
the text section have the same limits as the small code model. Applications
with large amounts of static data might require -xmodel=medium when
compiling with -m64.
This option is not cumulative so the compiler sets the model value according to the rightmost
instance of -xmodel on the command-line.
If you do not specify -xmodel, the compiler assumes -xmodel=small. Specifying -xmodel
without an argument is an error.
It is not necessary to compile all translation units with this option. You can compile select files
as long as you ensure the object you are accessing is within reach.
Be aware that not all Linux system support the medium model.
A.2.153 –xnolib
Disables linking with default system libraries.
Normally (without this option), the C++ compiler links with several system support libraries to
support C++ programs. With this option, the -llib options to link the default system support
libraries are not passed to ld.
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 option 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:
A.2.153.1 Examples
For minimal compilation to meet the C application binary interface (that is, a C++ program
with only C support required), use:
To link libm statically into a single-threaded application with the generic architecture
instruction set, use:
Interactions
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
A.2.154 –xnolibmil
Cancels –xlibmil on the command line.
Use this option with –fast to override linking with the optimized math library.
A.2.155 –xnolibmopt
Does not use the math routine library.
A.2.155.1 Examples
Use this option after the –fast option on the command line, as in this example:
A.2.156 -xnorunpath
Same as “A.2.63 –norunpath” on page 259
A.2.157 -xOlevel
Specifies optimization level; note the uppercase letter O followed by the digit 1, 2, 3, 4, or 5. In
general, program execution speed depends on the level of optimization. The higher the level of
optimization, 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 x86 platform.
A.2.157.1 Values
On the SPARC Platform:
■ –xO1 does only the minimum amount of optimization (peephole), which is post-pass,
assembly-level optimization. Do not use -xO1 unless using -xO2 or -xO3 results in
excessive compilation time, or you are running out of swap space.
■ –xO2 does basic local and global optimization, which includes:
■ Induction-variable elimination
■ Local and global common-subexpression elimination
■ Algebraic simplification
■ Copy propagation
■ Constant propagation
■ Loop-invariant optimization
■ Register allocation
–xO3, in addition to optimizations performed at the –xO2 level, also optimizes references
and definitions for external variables. This level does not trace the effects of pointer
assignments. When compiling either device drivers that are not properly protected by
volatile or programs that modify external variables from within signal handlers, use– xO2.
In general, this level results in increased code size unless combined with the -xspace
option.
■ –xO4 does automatic inlining of functions contained in the same file in addition to
performing– xO3 optimizations. This automatic inlining usually improves execution speed
but sometimes makes it worse. In general, this level results in increased code size unless
combined with the -xspace option.
■ –xO5 generates the highest level of optimization. It is suitable only for the small fraction of a
program that uses the largest fraction of computer time. This level uses optimization
algorithms that take more compilation time or that do not have as high a certainty of
improving execution time. Optimization at this level is more likely to improve performance
if it is done with profile feedback. See “A.2.170 -xprofile=p” on page 339.
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.
Defaults
The default is no optimization. However, this is only possible if you do not specify an
optimization level. If you specify an optimization level, there is no option for turning
optimization off.
If you are trying to avoid setting an optimization level, be sure not to specify any option that
implies an optimization level. For example, -fast is a macro option that sets optimization at
-xO5. All other options that imply an optimization level give a warning message that
optimization has been set. The only way to compile without any optimization is to delete all
options from the command line or make file that specify an optimization level.
Warnings
If you optimize at –xO3 or –xO4 with very large procedures (thousands of lines of code in a
single procedure), the optimizer might require an unreasonable amount of memory. In such
cases, machine performance can be degraded.
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 4 gigabytes:
This command causes the optimizer to try to recover if it reaches 4 gigabytes of data space.
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
-xldscope –fast, -xcrossfile=n, –xprofile=p, csh(1) man page
A.2.158 -xopenmp[=i]
Use the -xopenmp option to enable explicit parallelization with OpenMP directives. To run a
parallelized program in a multithreaded environment, you must set the
OMP_NUM_THREADS environment variable prior to execution.
To enable nested parallelism, you must set the OMP_NESTED environment variable to TRUE.
Nested parallelism is disabled by default.
A.2.158.1 Values
The following table lists the values for i:
Values Meaning
noopt Enables recognition of OpenMP pragmas. The compiler does not raise the
optimization level if it is lower than -O3.
If you explicitly set the optimization lower than -O3, as in CC -O2
-xopenmp=noopt, the compiler issues an error. If you do not specify an
optimization level with -xopenmp=noopt, the OpenMP pragmas are
recognized, the program is parallelized accordingly, but no optimization is
done.
This flag also defines the preprocessor token _OPENMP.
none This flag is the default and disables recognition of OpenMP pragmas, does
not change the optimization level of your program, and does not predefine
any preprocessor tokens.
Defaults
If you do not specify -xopenmp, the compiler sets the option to -xopenmp=none.
If you specify -xopenmp, but without an argument, the compiler sets the option to
-xopenmp=parallel.
Interactions
If you are debugging an OpenMP program with dbx, compile with -g and -xopenmp=noopt so
you can breakpoint within parallel regions and display the contents of variables.
Warnings
Do not specify -xopenmp, with either -xexplicitpar, or -xparallel.
The default for -xopenmp might change in future releases. You can avoid warning messages by
explicitly specifying an appropriate optimization.
If you compile and link in separate steps, specify -xopenmp in both the compilation step and the
link step. This is important if you are building a shared object. The compiler which was used to
compile the executable must not be any older than the compiler that built the .so with
-xopenmp. This is especially important when you compile libraries that contain OpenMP
directives. See “3.3.3 Compile-Time and Link-Time Options” on page 50 for a complete list of
options that must be specified at both compile time and line time.
Make sure that the latest patch of the OpenMP runtime library, libmtsk.so, is installed on the
system for best performance.
See also
For a complete summary of the OpenMP Fortran 95, C, and C++ application program interface
(API) for building multiprocessing applications, see the Sun Studio OpenMP API User’s Guide.
A.2.159 -xpagesize=n
Sets the preferred page size for the stack and the heap.
A.2.159.1 Values
The following values are valid for SPARC: 4k, 8K, 64K, 512K, 2M, 4M, 32M, 256M, 2G, 16G, or
default.
The following values are valid on x86/x64: 4K, 2M. 4M, 1G, or default.
You must specify a valid page size for the target platform. If you do not specify a valid pagesize,
the request is silently ignored at run-time.
Use the getpagesize(3C) command on the Solaris operating system to determine the number
of bytes in a page. The Solaris operating system offers no guarantee that the page size request
will be honored. You can use pmap(1) or meminfo(2) to determine page size of the target
platform.
Defaults
If you specify -xpagesize=default, the Solaris operating system sets the page size.
Expansions
This option is a macro for -xpagesize_heap and -xpagesize_stack. These two options accept
the same arguments as -xpagesize: 4k, 8K, 64K, 512K, 2M, 4M, 32M, 256M, 2G, 16G, or default.
You can set them both with the same value by specifying -xpagesize or you can specify them
individually with different values.
Warnings
The -xpagesize option has no effect unless you use it at compile time and at link time. See
“3.3.3 Compile-Time and Link-Time Options” on page 50 for a complete list of options that
must be specified at both compile time and link time.
See Also
Compiling with this option has the same effect as setting the LD_PRELOAD environment variable
to mpss.so.1 with the equivalent options, or running the Solaris command ppgsz(1) with the
equivalent options before running the program. See the Solaris man pages for details.
A.2.160 -xpagesize_heap=n
Set the page size in memory for the heap.
A.2.160.1 Values
n can be 4k, 8K, 64K, 512K, 2M, 4M, 32M, 256M, 2G, 16G, or default. You must specify a valid page
size for the target platform. If you do not specify a valid page size, the request is silently ignored
at run-time.
Use the getpagesize(3C) command on the Solaris operating system to determine the number
of bytes in a page. The Solaris operating system offers no guarantee that the page size request
will be honored. You can use pmap(1) or meminfo(2) to determine page size of the target
platform.
Defaults
If you specify -xpagesize_heap=default, the Solaris operating system sets the page size.
Warnings
The -xpagesize_heap option has no effect unless you use it at compile time and at link time.
See Also
Compiling with this option has the same effect as setting the LD_PRELOAD environment variable
to mpss.so.1 with the equivalent options, or running the Solaris command ppgsz(1) with the
equivalent options before running the program. See the Solaris man pages for details.
A.2.161 -xpagesize_stack=n
Set the page size in memory for the stack.
A.2.161.1 Values
n can be 4k, 8K, 64K, 512K, 2M, 4M, 32M, 256M, 2G, 16G, or default. You must specify a valid page
size for the target platform. If you do not specify a valid page size, the request is silently ignored
at run-time.
Use the getpagesize(3C) command on the Solaris operating system to determine the number
of bytes in a page. The Solaris operating system offers no guarantee that the page size request
will be honored. You can use pmap(1) or meminfo(2) to determine page size of the target
platform.
Defaults
If you specify -xpagesize_stack=default, the Solaris operating system sets the page size.
Warnings
The -xpagesize_stack option has no effect unless you use it at compile time and at link time.
See Also
Compiling with this option has the same effect as setting the LD_PRELOAD environment variable
to mpss.so.1 with the equivalent options, or running the Solaris command ppgsz(1) with the
equivalent options before running the program. See the Solaris man pages for details.
A.2.162 -xpch=v
This compiler option activates the precompiled-header feature. The precompiled-header
feature may reduce compile time for applications whose source files share a common set of
include files containing a large amount of source code. The compiler collects information about
a sequence of header files from one source file, and then uses that information when
recompiling that source file, and when compiling other source files that have the same sequence
of headers. The information that the compiler collects is stored in a precompiled-header file.
You can take advantage of this feature through the -xpch and -xpchstop options in
combination with the #pragma hdrstop directive.
See Also:
■ “A.2.163 -xpchstop=file” on page 331
■ “B.2.8 #pragma hdrstop” on page 368
CC -xpch=collect:myheader a.cc
A valid precompiled-header filename always has the suffix .Cpch. When you specify
pch_filename, you can add the suffix or let the compiler add it for you. For example, if you
specify cc -xpch=collect:foo a.cc, the precompiled-header file is called foo.Cpch.
When you create a precompiled-header file, pick a source file that contains the common
sequence of include files across all the source files with which the precompiled-header file is to
be used. The common sequence of include files must be identical across these source files.
Remember, only one source filename value is legal in collect mode. For example, CC
-xpch=collect:foo bar.cc is valid, whereas CC -xpch=collect:foo bar.cc foobar.cc is
invalid because it specifies two source files.
You should only use an existing precompiled-header file if the following is true. If any of the
following is not true, you should recreate the precompiled-header file:
■ The compiler that you are using to access the precompiled-header file is the same as the
compiler that created the precompiled-header file. A precompiled-header file created by one
version of the compiler may not be usable by another version of the compiler, including
differences caused by installed patches.
■ Except for the -xpch option, the compiler options you specify with -xpch=use must match
the options that were specified when the precompiled-header file was created.
■ The set of included headers you specify with -xpch=use is identical to the set of headers that
were specified when the precompile header was created.
■ The contents of the included headers that you specify with -xpch=use is identical to the
contents of the included headers that were specified when the precompiled header was
created.
■ The current directory (that is, the directory in which the compilation is occurring and
attempting to use a given precompiled-header file) is the same as the directory in which the
precompiled-header file was created.
■ The initial sequence of pre-processing directives, including #include directives, in the file
you specified with -xpch=collect are the same as the sequence of pre-processing directives
in the files you specify with -xpch=use.
In order to share a precompiled-header file across multiple source files, those source files must
share a common set of include files as their initial sequence of tokens. This initial sequence of
tokens is known as the viable prefix. The viable prefix must be interpreted consistently across all
the source files that use the same precompiled-header file.
The viable prefix of a source file can only be comprised of comments and any of the following
pre-processor directives:
#include
#if/ifdef/ifndef/else/elif/endif
#define/undef
#ident (if identical, passed through as is)
#pragma (if identical)
Any of these may reference macros. The #else, #elif, and #endif directives must match
within the viable prefix.
Within the viable prefix of each file that shares a precompiled-header file, each corresponding
#define and #undef directive must reference the same symbol (in the case of #define, each one
must reference the same value). Their order of appearance within each viable prefix must be the
same as well. Each corresponding pragma must also be the same and appear in the same order
across all the files sharing a precompiled header.
A header file that is incorporated into a precompiled-header file must not violate the following.
The results of compiling a program that violate any of these constraints is undefined.
■ The header file must not contain function and variable definitions.
■ The header file must not use __DATE__ and __TIME__. Use of these pre-processor macros
can generate unpredictable results.
■ The header file must not contain #pragma hdrstop.
■ The header file must not use __LINE__ and __FILE__ in the viable prefix. It is allowed to use
__LINE__ and __FILE__ in included headers.
.KEEP_STATE:
CCFLAGS_AUX = -O etc
CCFLAGS = -xpch=use:shared $(CCFLAGS_AUX)
shared.Cpch: foo.cc
$(CCC) -xpch=collect:shared $(CCFLAGS_AUX) foo.cc
a.out: foo.o ping.o pong.o
$(CCC) foo.o ping.o pong.o
You can also define your own compilation rule instead of trying to use an auxiliary CCFLAGS.
.KEEP_STATE:
.SUFFIXES: .o .cc
%.o:%.cc shared.Cpch
$(CCC) -xpch=use:shared $(CCFLAGS) -c $<
shared.Cpch: foo.cc
$(CCC) -xpch=collect:shared $(CCFLAGS) foo.cc -xe
a.out: foo.o ping.o pong.o
$(CCC) foo.o ping.o pong.o
■ You can produce the precompiled header as a side effect of regular compilation, and without
using KEEP_STATE, but this approach requires explicit compilation commands.
A.2.163 -xpchstop=file
Use the -xpchstop=file option to specify the last include file to be considered in creating the
precompile-header file with the -xpch option. Using -xpchstop on the command line is
equivalent to placing a hdrstop pragma after the first include-directive that references file in
each of the source files that you specify with the cc command.
In the following example, the -xpchstop option specifies that the viable prefix for the
precompiled header file ends with the include of projectheader.h. Therefore,
privateheader.h is not a part of the viable prefix.
A.2.164 -xpec[={yes|no}]
Generates a Portable Executable Code (PEC) binary. PEC binaries can be used with the
Automatic Tuning System (ATS) which works by rebuilding the compiled PEC binary for
tuning and troubleshooting - the original source code is not required. More information about
the ATS is available at http://cooltools.sunsource.net/ats/index.html.
A binary that is built with -xpecis usually five to ten times larger than if it is built without -xpec.
If you do not specify -xpec, the compiler sets it to -xpec=no. If you specify -xpec, but do not
supply a flag, the compiler sets it to -xpec=yes.
A.2.165 –xpg
Compiles for profiling with the gprof profiler.
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.
Note – There is no advantage for -xprofile if you specify -xpg. The two do not prepare or use
data provided by the other.
Profiles are generated by using prof(1) or gprof(1) on 64 bit Solaris platforms or just gprof on
32 bit Solaris platforms and include approximate user CPU times. These times are derived from
PC sample data (see pcsample(2)) for routines in the main executable and routines in shared
libraries specified as linker arguments when the executable is linked. Other shared libraries
(libraries opened after process startup using dlopen(3DL)) are not profiled.
On 32 bit Solaris systems, profiles generated using prof(1) are limited to routines in the
executable. 32 bit shared libraries can be profiled by linking the executable with -xpg and using
gprof(1).
The Solaris 10 software does not include system libraries compiled with -p. As a result, profiles
collected on Solaris 10 platforms do not include call counts for system library routines.
A.2.165.1 Warnings
If you compile and link separately, and you compile with –xpg, be sure to link with –xpg. See
“3.3.3 Compile-Time and Link-Time Options” on page 50 for a complete list of options that
must be specified at both compile time and link time.
See also
–xprofile=p, the analyzer(1) man page, and the Performance Analyzer manual.
A.2.166 -xport64[=(v)]
Use this option to help you debug code you are porting to a 64-bit environment. Specifically,
this option warns against problems such as truncation of types (including pointers), sign
extension, and changes to bit-packing that are common when code is ported from a 32-bit
architecture such as V8 to a 64-bit architecture such as V9.
A.2.166.1 Values
The following table lists the valid values for v:
Values Meaning
implicit Generate warning only for implicit conversions. Do not generate warnings
when an explicit cast is present.
full Generate all warnings related to the porting of code from a 32 bit
environment to a 64 bit environment. This includes warnings for truncation
of 64-bit values, sign-extension to 64 bits under ISO value-preserving rules,
and changes to packing of bitfields.
Defaults
If you do not specify -xport64, the default is -xport64=no. If you specify -xport64, but do not
specify a flag, the default is -xport64=full.
Examples
This section provides examples of code that can cause truncation of type, sign extension and
changes to bit-packing.
1 Warning(s) detected.
example%
Another common issue that arises from porting to a 64-bit architecture is the truncation of a
pointer. This is always an error in C++. An operation such as casting a pointer to an int which
causes such a truncation results in an error diagnostic in V9 when you specify -xport64.
int main() {
unsigned long l;
l = i; // warn
promo(i); // warn
}
example% CC -c -xarch=v9 -Qoption ccfe -xport64=full test3.c
"test3.c", line 6: Warning: Sign extension from "int" to 64-bit integer.
"test3.c", line 7: Warning: Sign extension from "int" to 64-bit integer.
2 Warning(s) detected.
union U {
struct S {
unsigned long b1:20;
unsigned long b2:20;
} s;
long buf[2];
} u;
int main() {
u.s.b1 = 0XFFFFF;
u.s.b2 = 0XFFFFF;
printf(" u.buf[0] = %lx u.buf[1] = %lx\n", u.buf[0], u.buf[1]);
return 0;
}
example%
Output in V9:
Warnings
Note that warnings are generated only when you compile in 64-bit mode by specifying options
such as -m64.
See Also
“A.2.51 -m32|-m64” on page 256
A.2.167 -xprefetch[=a[,a...]]
Enable prefetch instructions on those architectures that support prefetch.
Explicit prefetching should only be used under special circumstances that are supported by
measurements.
Value Meaning
With -xprefetch and -xprefetch=auto the compiler is free to insert prefetch instructions
into the code it generates. This may result in a performance improvement on architectures that
support prefetch.
If you are running computationally intensive codes on large multiprocessors, you might find it
advantageous to use -xprefetch=latx:factor. This option instructs the code generator to
adjust the default latency time between a prefetch and its associated load or store by the
specified factor.
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.
Note – The assumed latency between a prefetch and a load may not be the same as the assumed
latency between a prefetch and a store.
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 data sets 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.
A.2.167.1 Defaults
The default is -xprefetch=auto,explicit. This default adversely affects applications that have
essentially non-linear memory access patterns. Specify -xprefetch=no%auto,no%explicit to
override the default.
The default of auto is assumed unless explicitly overridden with an argument of no%auto or an
argument of no. For example, -xprefetch=explicit is the same as
-xprefetch=explicit,auto.
The default of explicit is assumed unless explicitly overridden with an argument of
no%explicit or an argument of no. For example, -xprefetch=auto is the same as
-xprefetch=auto,explicit.
If only -xprefetch is specified, -xprefetch=auto,explicit is assumed.
If automatic prefetching is enabled, but a latency factor is not specified, then
-xprefetch=latx:1.0 is assumed.
Interactions
This option accumulates instead of overrides.
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 or -xprefetch=explicit.
If you call the macros and include the sun_prefetch.h header file, but specify
-xprefetch=no%explicit, 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 -xprefetch=auto,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.168 -xprefetch_auto_type=a
Where a is [no%]indirect_array_access.
Use this option to determine whether or not the compiler generates indirect prefetches for the
loops indicated by the option -xprefetch_level in the same fashion the prefetches for direct
memory accesses are generated.
Options such as -xdepend, -xrestrict, and -xalias_level can affect the aggressiveness of
computing the indirect prefetch candidates and therefore the aggressiveness of the automatic
indirect prefetch insertion due to better memory alias disambiguation information.
A.2.169 -xprefetch_level[=i]
Use the -xprefetch_level=i option to control the aggressiveness of the automatic insertion of
prefetch instructions as determined with -xprefetch=auto. The compiler becomes more
aggressive, or in other words, introduces more prefetches, with each higher, level of
-xprefetch_level.
The appropriate value for -xprefetch_level depends on the number of cache misses your
application has. Higher -xprefetch_level values have the potential to improve the
performance of applications with a high number of cache misses.
A.2.169.1 Values
i must be one of 1, 2, or 3.
Value Meaning
Defaults
The default is -xprefetch_level=1 when you specify -xprefetch=auto.
Interactions
This option is effective only when it is compiled with -xprefetch=auto, with optimization level
3 or greater (-xO3), and on a platform that supports prefetch (v9, v9a, v9b, generic64,
native64).
A.2.170 -xprofile=p
Use this option to first collect and save execution-frequency data so that you can then use the
data in subsequent runs to improve performance. This option is only valid when you specify
optimization at level -xO2 or above.
Compiling with high optimization levels (for example -xO5) is enhanced by providing the
compiler with runtime-performance feedback. In order to produce runtime-performance
feedback, you must compile with -xprofile=collect, run the executable against a typical data
set, and then recompile at the highest optimization level and with -xprofile=use.
Profile collection is safe for multithreaded applications. That is, profiling a program that does its
own multitasking (-mt) produces accurate results. This option is only valid when you specify
optimization at level -xO2 or above.
A.2.170.1 Values
p must be one of the following values.
■ 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 optional name of the directory in which profile data will be stored when the
program is executed. If specified, name should be an absolute UNIX pathname. If name is
not specified, profile data for a profiled program named program will be stored in a directory
named program.profile in the current working directory at the time that program is
executed.
At runtime, a program compiled with –xprofile=collect:name creates the subdirectory
name.profile to hold the runtime feedback information. Data is written to the file
feedback in this subdirectory. You can use the $SUN_PROFDATA and $SUN_PROFDATA_DIR
environment variables to change the location of the feedback information. See the
Interactions section for more information.
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.
If you are compiling and linking in separate steps, make sure that any object files compiled
with -xprofile=collect are also linked with -xprofile=collect. See “3.3.3
Compile-Time and Link-Time Options” on page 50 for a complete list of options that must
be specified at both compile time and link time.
The three options -xMerge -ztext -xprofile=collect should not be used together. While
-xMerge forces statically initialized data into read-only storage, -ztext prohibits
position-dependent symbol relocations in read-only storage, and -xprofile=collect
generates statically initialized, position-dependent symbol relocations in writable storage.
■ use[:name]
The program is optimized by using the executions-frequency data generated and saved in
the feedback files from a previous execution of the program that was compiled with
–xprofile=collect.
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.
Except for the -xprofile option which changes from -xprofile=collect to
-xprofile=use, the source files and other compiler options must be exactly the same as
those used for the compilation that created the compiled program which in turn 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.
The association between an object file and its profile data is based on the UNIX pathname of
the object file when it is compiled with -xprofile=collect. In some circumstances, the
compiler will not associate an object file with its profile data: the object file has no profile
data because it was not previously compiled with -xprofile=collect, the object file is not
linked in a program with -xprofile=collect, the program has never been executed.
The compiler can also become confused if an object file was previously compiled in a
different directory with -xprofile=collect and this object file shares a common basename
with other object files compiled with -xprofile=collect but they cannot be uniquely
identified by the names of their containing directories. In this case, even if the object file has
profile data, the compiler will not be able to find it in the feedback directory when the object
file is recompiled with -xprofile=use.
All of these situations cause the compiler to loose the association between an object file and
its profile data. Therefor, if an object file has profile data but the compiler is unable to
associate it with the object file’s pathname when you specify -xprofile=use, use the
-xprofile_pathmap option to identify correct directory. See “A.2.172 -xprofile_pathmap”
on page 342
■ 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.
Unlike the –xa option, the TCOVDIR environment variable has no effect at compile time.
However, its value is used at program runtime.
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.
The code coverage report produced by -xprofile=tcov can be unreliable if there is inlining of
functions due to the use of -xinline or -xO4.
You can set the environment variables $SUN_PROFDATA and $SUN_PROFDATA_DIR to control
where a program that is compiled with -xprofile=collect puts the profile data. If these
variables are not set, the profile data is written to name.profile/feedback in the current
directory (name is the name of the executable or the name specified in the
-xprofile=collect:name flag). If these variables are set, the -xprofile=collect data is
written to $SUN_PROFDATA_DIR/$SUN_PROFDATA.
The $SUN_PROFDATA and $SUN_PROFDATA_DIR environment variables similarly control the path
and names of the profile data files written by tcov. See the tcov(1) man page for more
information.
Warnings
If you compile and link in separate steps, the same -xprofile option must appear in both the
compile command and the link command. Including -xprofile 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
-xa, tcov(1) man page, Program Performance Analysis Tools.
A.2.171 -xprofile_ircache[=path]
(SPARC) Use -xprofile_ircache[=path] with -xprofile=collect|use to improve
compilation time during the use phase by reusing compilation data saved from the collect
phase.
With large programs, compilation time in the use phase can improve significantly because the
intermediate data is saved. Note that the saved data could increase disk space requirements
considerably.
When you use -xprofile_ircache[=path], path overrides the location where the cached files
are saved. By default, these files are saved in the same directory as the object file. Specifying a
path is useful when the collect and use phases happen in two different directories. Here’s a
typical sequence of commands:
A.2.172 -xprofile_pathmap
(SPARC) Use the -xprofile_pathmap=collect_prefix:use_prefix option when you are also
specifying the -xprofile=use command. Use -xprofile_pathmap when both of the following
are true and the compiler is unable to find profile data for an object file that is compiled with
-xprofile=use.
■ You are compiling the object file with -xprofile=use in a directory that is different from
the directory in which the object file was previously compiled with -xprofile=collect.
■ Your object files share a common basename in the profile but are distinguished from each
other by their location in different directories.
The collect-prefix is the prefix of the UNIX pathname of a directory tree in which object files
were compiled using -xprofile=collect.
The use-prefix is the prefix of the UNIX pathname of a directory tree in which object files are to
be compiled using -xprofile=use.
If you specify multiple instances of -xprofile_pathmap, the compiler processes them in the
order of their occurrence. Each use-prefix specified by an instance of -xprofile_pathmap is
compared with the object file pathname until either a matching use-prefix is identified or the last
specified use-prefix is found not to match the object file pathname.
A.2.173 -xreduction
Analyzes loops for reduction in automatic parallelization. This option is valid only if -xautopar
is also specified. Otherwise the compiler issues a warning.
When reduction recognition is enabled, the compiler parallelizes reductions such as dot
products, maximum and minimum finding. These reductions yield different roundoffs from
those obtained by unparallelized code.
A.2.174 –xregs=r[,r...]
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.
A.2.174.1 Values
r must be one of the following values. The meaning of each value depends upon the -m32|-m64
setting.
Values Meaning
[no%]appl (SPARC) [Does not] Allow the compiler to generate code using the application
registers as scratch registers. The application registers are:
g2, g3, g4 (on 32–bit platforms)
g2, g3 (on 64–bit platforms)
It is strongly recommended that all system software and libraries be compiled
using -xregs=no%appl. System software (including shared libraries) must
preserve these registers’ values for the application. Their use is intended to be
controlled by the compilation system and must be consistent throughout the
application.
In the SPARC ABI, these registers are described as application registers. Using
these registers can increase performance because fewer load and store
instructions are needed. However, such use can conflict with programs that
use the registers for other purposes.
[no%]float (SPARC) [Does not] Allow the compiler to generate code by using the
floating-point registers as scratch registers for integer values. Use of
floating-point values may use these registers regardless of this option. If you
want your code to be free of all references to floating point registers, you need
to use -xregs=no%float and also make sure your code does not use floating
point types in any way.
[no%]frameptr (x86) [Does not] Allow the compiler to use the frame-pointer register (%ebp
on IA32, %rbp on AMD64) as an unallocated callee-saves register.
Using this register as an unallocated callee-saves register may improve
program run time. However, it also reduces the capacity of some tools to
inspect and follow the stack. This stack inspection capability is important for
system performance measurement and tuning. Therefor, using this
optimization may improve local program performance at the expense of global
system performance.
■ Tools, such as the Performance Analyzer, that dump the stack for
postmortem diagnosis will not work.
■ Debuggers (adb, mdb, dbx) will not be able to dump the stack or directly
pop stack frames.
■ The dtrace performance analysis facility will be unable to collect
information on any frames on the stack before the most recent frame
missing the frame pointer.
■ Posix pthread_cancel will fail trying to find cleanup handlers.
■ C++ exceptions cannot propagate through C functions.
The failures in C++ exceptions occur when a C function that has lost its
frame pointer calls a C++ function that throws an exception through the C
function. Such calls typically occur when a function accepts a function
pointer (for example, qsort) or when a global function, such as malloc, is
interposed upon.
The last two affects listed above may impact the correct operation of
applications. Most application code will not encounter these problems.
Libraries that are developed by using -xO4, however, need documentation
that details the restrictions of their usage by their clients.
■ Note – The compiler ignores -xregs=framptr and issues a warning if you
also specify -xpg. Also, the compiler ignores this option for 32–bit x86
compilation unless exceptions are disabled with -noex option.
Defaults
The SPARC default is -xregs=appl,float.
Examples
To compile an application program using all available scratch registers, use
-xregs=appl,float.
See also
SPARC V8 and SPARC V9 ABI
A.2.175 -xrestrict[=f]
(SPARC) Treats pointer-valued function parameters as restricted pointers . f must be one of the
following values:
Value Meaning
%all All pointer parameters in the entire file are treated as restricted.
%source Only functions defined within the main source file are restricted. Functions
defined within included files are not restricted.
This command-line option can be used on its own, but it is best used with optimization. For
example, the command:
treats all pointer parameters in the file prog.c as restricted pointers. The command:
treats all pointer parameters in the function agc in the file prog.c as restricted pointers.
The default is %none; specifying -xrestrict is equivalent to specifying -xrestrict=%source.
extern "C"
void vsq(int n, double *a, double *b) {
int i;
for (i=0; i<n; i++) {
b[i] = a[i] * a[i];
}
}
The compiler can parallelize the execution of the different iterations of the loops if it knows that
pointers a and b access different objects. If there is an overlap in objects accessed through
pointers a and b then it would be unsafe for the compiler to execute the loops in parallel.
At compile time, the compiler does not know if the objects accessed by a and b overlap by
simply analyzing the function vsq(); the compiler may need to analyze the whole program to
get this information. You can specify that pointer-valued function parameters be treated as
restricted pointers by using the following command line option: -xrestrict[=func1,...,funcn]
If a function list is specified, pointer parameters in the specified functions are treated as
restricted; otherwise, all pointer parameters in the entire source file are treated as restricted (not
recommended). For example, -xrestrict=vsq qualifies the pointers a and b given in the
example of the function vsq().
Declaring the pointer arguments as restricted states that the pointers designate distinct objects.
The compiler can assume that a and b point to distinct regions of storage. With this alias
information, the compiler is able to parallelize the loop.
It is critical that you use -xrestrict correctly. If pointers qualified as restricted pointers point
to objects that are not distinct, the compiler can incorrectly parallelize loops resulting in
undefined behavior. For example, assume that pointers a and b of function vsq() point to
objects that overlap, such that b[i] and a[i+1] are the same object. If a and b are not declared
as restricted pointers the loops will be executed serially. If a and b are incorrectly qualified as
restricted pointers the compiler may parallelize the execution of the loops, which is not safe,
because b[i+1] should only be computed after b[i] is computed
A.2.176 –xs
Allows debugging by dbx without object (.o) files.
This option causes all the debug information to be copied into the executable. This has little
impact on dbx performance or the run-time performance of the program, but it does take more
disk space.
This option has an effect only with -xdebugformat=stabs, where the default is not to copy
debug data into the executable. With the default debug format -xdebugformat=dwarf, debug
data is always copied into the executable, and there is no option to prevent the copying.
A.2.177 –xsafe=mem
SPARC: Allows the compiler to assume that no memory protection violations occur.
This option allows the compiler to use the non-faulting load instruction in the SPARC V9
architecture.
A.2.177.1 Interactions
This option takes effect only when used with optimization level -xO5 and one of the following
-xarch values: sparc, sparcvis, or sparcvis2 for both -m32 and -m64.
A.2.177.2 Warnings
Because non-faulting 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.178 –xsb
Deprecated - do not use. The source browser functionality is obsolete. This options is silently
ignored.
A.2.179 –xsbfast
Deprecated - do not use. The source browser functionality is obsolete. This option is silently
igored.
A.2.180 –xspace
SPARC: Does not allow optimizations that increase code size.
A.2.181 –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.
The value of t must be one of the following: native, generic, native64, generic64,
system-name.
Each specific value for -xtarget expands into a specific set of values for the -xarch, -xchip,
and -xcache options. Use the -xdryrun option to determine the expansion of
-xtarget=native on a running system.
Note – The expansion of -xtarget for a specific host platform might not expand to the same
-xarch, -xchip, or -xcache settings as -xtarget=native when compiling on that platform.
Value 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 This is the default value. Gets the best performance for generic architecture,
chip, and cache.
generic64 Sets the parameters for the best performance of 64-bit object binaries over
most 64-bit platform architectures.
See “A.2.114 –xcache=c” on page 287 for more information on the cache properties of the UltraSPARC
IVplus, UltraSPARC T1, and UltraSPARC T2 chips.
Defaults
On both SPARC and x86 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.
Interactions
Compilation for SPARC V9 architecture indicated by the -xarch=v9|v9a|v9b option. Setting
–xtarget=ultra or ultra2 is not necessary or sufficient. If -xtarget is specified, the
-xarch=v9, v9a, or v9b option must appear after the -xtarget. For example:
-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.182 -xthreadvar[=o]
Specify -xthreadvar to control the implementation of thread local variables. Use this option in
conjunction with the __thread declaration specifier to take advantage of the compiler’s
thread-local storage facility. After you declare the thread variables with the __thread specifier,
specify -xthreadvar to enable the use of thread-local storage with position dependent code
(non-PIC code) in dynamic (shared) libraries. For more information on how to use __thread,
see “4.2 Thread-Local Storage” on page 65.
A.2.182.1 Values
o must be one of the following:
Value Meaning
[no%]dynamic [Do not] Compile variables for dynamic loading. Access to thread
variables is significantly faster when -xthreadvar=no%dynamic but you
cannot use the object file within a dynamic library. That is, you can only
use the object file in an executable file.
Defaults
If you do not specify -xthreadvar, the default used by the compiler depends upon whether or
not position-independent code is enabled. If position-independent code is enabled, the option
is set to -xthreadvar=dynamic. If position-independent code is disabled, the option is set to
-xthreadvar=no%dynamic.
If you specify -xthreadvar but do not specify any arguments, the option is set to
-xthreadvar=dynamic.
Interactions
the -mt option must be used when compiling and linking files that use __thread.
Warnings
If there is non-position-independent code within a dynamic library, you must specify
-xthreadvar.
The linker cannot support the thread-variable equivalent of non-PIC code in dynamic libraries.
Non-PIC thread variables are significantly faster, and hence should be the default for
executables.
See Also
-xcode, -KPIC, -Kpic
A.2.183 –xtime
Causes the CC driver to report execution time for the various compilation passes.
A.2.184 -xtrigraphs[={yes|no}]
Enables or disables recognition of trigraph sequences as defined by the ISO/ANSI C standard.
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.
A.2.184.1 Values
You can specify one of the following two values for -xtrigraphs:
Value Meaning
Defaults
When you do not include the -xtrigraphs option on the command line, the compiler assumes
-xtrigraphs=yes.
If only -xtrigraphs is specified, 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.185 –xunroll=n
Enables unrolling of loops where possible.
This option specifies whether or not the compiler optimizes (unrolls) loops.
A.2.185.1 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.
A.2.186 -xustr={ascii_utf16_ushort|no}
Use this option if your code contains string or character literals that you want the compiler to
convert to UTF-16 strings in the object file. Without this option, the compiler neither produces
nor recognizes sixteen-bit character string literals. This option enables recognition of the
U"ASCII_string" string literals as an array of unsigned short int. Since such strings are not yet
part of any standard, this option enables recognition of non-standard C++.
A.2.186.1 Values
Specify -xustr=ascii_utf16_ushort if you need to support an internationalized application
that uses ISO10646 UTF-16 string literals. You can turn off compiler recognition of
U"ASCII_string" string or character literals by specifying -xustr=no. The right-most instance
of this option on the command line overrides all previous instances.
Defaults
The default is -xustr=no. If you specify -xustr without an argument, the compiler won’t accept
it and instead issues a warning. The default can change if the C or C++ standards define a
meaning for the syntax.
Example
The following example shows a string literal in quotes that is prepended by U. It also shows a
command line that specifies -xustr
An 8-bit character literal can be prepended with U to form a 16-bit UTF-16 character of type
unsigned short. Examples:
A.2.187 -xvector[=a]
Enables automatic generation of calls to the vector library functions and/or the generation of
the SIMD (Single Instruction Multiple Data) instructions. You must use default rounding mode
by specifying -fround=nearest when you use this option.
Value Meaning
[no%]lib (Solaris only) Does [not] enable the compiler to transform math library
calls within loops into single calls to the equivalent vector math routines
when such transformations are possible. This could result in a
performance improvement for loops with large loop counts.
[no%]simd Does [not] direct the compiler to use the native x86 SSE SIMD
instructions to improve performance of certain loops. The compiler can
only accept this switch if the target architecture supports SIMD
instructions. For example, you must specify -xarch=amd64,
-xarch=amd64a or -xarch=generic64. You must also specify an
optimization level of -xO3 or above as well as -xdepend when you specify
-xvector=simd.
A.2.187.1 Defaults
The default is -xvector=%none. If you specify -xvector, but do not provide a flag, the compiler
assumes -xvector=lib.
Interactions
If you use -xvector on the command line without previously specifying -xdepend, -xvector
triggers -xdepend. The -xvector option also raises the optimization level to -x03 if
optimization is not specified or optimization is set lower than -x03.
If you compile and link with separate commands, be sure to use -xvector in the linking CC
command. See “3.3.3 Compile-Time and Link-Time Options” on page 50 for a complete list of
options that must be specified at both compile time and link time.
A.2.188 -xvis[={yes|no}]
(SPARC) Use the -xvis=[yes|no] command when you are using the assembly-language
templates defined in the VISTM instruction-set Software Developers Kit (VSDK).
The VIS instruction set is an extension to the SPARC v9 instruction set. Even though the
UltraSPARC processors are 64-bit, there are many cases, especially in multimedia applications,
when the data are limited to eight or 16 bits in size. The VIS instructions can process four 16-bit
data with one instruction so they greatly improve the performance of applications that handle
new media such as imaging, linear algebra, signal processing, audio, video and networking.
A.2.188.1 Defaults
The default is -xvis=no. Specifying -xvis is equivalent to specifying -xvis=yes.
See Also
For more information on the VSDK, see http://www.sun.com/processors/vis/.
A.2.189 -xvpara
Issues warnings about potential parallel-programming related problems that may cause
incorrect results when using OpenMP. Use with -xopenmp and OpenMP API directives.
The compiler issues warnings when it detects the following situations:
■ Loops are parallelized using MP directives with data dependencies between different loop
iterations
■ OpenMP data-sharing attributes-clauses are problematic. For example, declaring a variable
"shared" whose accesses in an OpenMP parallel region may cause a data race, or declaring a
variable "private" whose value in a parallel region is used after the parallel region.
No warnings appear if all parallelization directives are processed without problems.
Example:
Note – Sun Studio compilers support OpenMP 2.5 API parallelization. Consequently, the MP
pragmas directives are deprecated and are no longer supported. See the OpenMP API User’s
Guide for information on migrating to the OpenMP API.
A.2.190 –xwe
Converts all warnings to errors by returning nonzero exit status.
A.2.191 -Yc,path
Specifies a new path for the location of component c.
If the location of a component is specified, then the new path name for the component is
path/component_name. This option is passed to ld.
A.2.191.1 Values
c must be one of the following values:
Value Meaning
P Adds path to the default library search path. This path will be searched
before the default library search paths.
Interactions
You can have multiple -Y options on a command line. If more than one -Y option is applied to
any one component, then the last occurrence holds.
See also
Solaris Linker and Libraries Guide
Pragmas
B
This appendix describes the 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
int bar(int);
int foo(int);
363
B.2 Pragma Reference
int foo(double);
#pragma does_not_read_global_data(foo, bar)
In this example, foo means foo(double), the declaration of foo immediately preceding the
pragma, and bar means bar(int), the only declared bar. Now, consider this following example
in which foo is again overloaded:
int foo(int);
int foo(double);
int bar(int);
#pragma does_not_read_global_data(foo, bar)
In this example, bar means bar(int), the only declared bar.However, the pragma will not
know which version of foo to use. To correct this problem, you must place the pragma
immediately following the definition of foo that you want the pragma to use.
The following pragmas use the selection method described in this section:
■ does_not_read_global_data
■ does_not_return
■ does_not_write_global_data
■ no_side_effect
■ opt
■ rarely_called
■ returns_new_memory
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.
When #pragma align is used inside a namespace, mangled names must be used. For example,
in the following code, the #pragma align statement will have no effect. To correct the problem,
replace a, b, and c in the #pragma align statement with their mangled names.
namespace foo {
#pragma align 8 (a, b, c)
static char a;
static char b;
static char c;
}
This pragma asserts that the specified routines do not read global data directly or indirectly.
This allows for better optimization of code around calls to such routines. In particular,
assignment statements or stores could be moved around such calls.
This pragma is permitted only after the prototype for the specified functions are declared. If the
assertion about global access is not true, then the behavior of the program is undefined.
For a more detailed explanation of how the pragma treats overloaded function names as
arguments, see “B.1.1 Overloaded Functions as Pragma Arguments” on page 363.
This pragma is an assertion to the compiler that the calls to the specified routines will not
return. This allows the compiler to perform optimizations consistent with that assumption. For
example, register life-times terminate at the call sites which in turn allows more optimizations.
If the specified function does return, then the behavior of the program is undefined.
This pragma is permitted only after the prototype for the specified functions are declared as the
following example shows:
For a more detailed explanation of how the pragma treats overloaded function names as
arguments, see “B.1.1 Overloaded Functions as Pragma Arguments” on page 363.
This pragma asserts that the specified list of routines do not write global data directly or
indirectly. This allows for better optimization of code around calls to such routines. In
particular, assignment statements or stores could be moved around such calls.
This pragma is permitted only after the prototype for the specified functions are declared. If the
assertion about global access is not true, then the behavior of the program is undefined.
For a more detailed explanation of how the pragma treats overloaded function names as
arguments, see “B.1.1 Overloaded Functions as Pragma Arguments” on page 363.
Use this pragma when you want to see how macros are behaving in your program. This pragma
provides information such as macro defines, undefines, and instances of usage. It prints output
to the standard error (stderr) based on the order macros are processed. The dumpmacros
pragma is in effect through the end of the file or until it reaches a #pragma end_dumpmacro. See
“B.2.6 #pragma end_dumpmacros” on page 367. You can substitute the following arguments in
place of value:
Value Meaning
loc Print location (path name and line number) also for defs, undefs, and use
Value Meaning
sys Print all macros defines, undefines, and use information for macros in
system header files
Note – The sub-options loc, conds, and sys are qualifiers for defs, undefs and use options. By
themselves, loc, conds, and sys have no effect. For example, #pragma
dumpmacros=loc,conds,sys has no effect.
The dumpmacros pragma has the same effect as the command line option, however, the pragma
overrides the command line option. See “A.2.123 -xdumpmacros[=value[,value...]]” on
page 296.
The dumpmacros pragma does not nest so the following lines of code stop printing macro
information when the #pragma end_dumpmacros is processed:
If you use the option #pragma dumpmacros=use,no%loc, the name of each macro that is used is
printed only once. If you use the option #pragma dumpmacros=use,loc the location and macro
name is printed every time a macro is used.
This pragma marks the end of a dumpmacros pragma and stops printing information about
macros. If you do not use an end_dumpmacros pragma after a dumpmacros pragma, the
dumpmacros pragma continues to generate output through the end of the file.
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.
In a source file, the functions specified in #pragma fini are executed after the static destructors
in that file. You must declare the identifiers before using them in the pragma.
The viable source prefix ends at c.h so you would insert a #pragma hdrstop after c.h in each
file.
#pragma hdrstop must only appear at the end of the viable prefix of a source file that is specified
with the CC command. Do not specify #pragma hdrstop in any include file.
See “A.2.162 -xpch=v” on page 328 and “A.2.163 -xpchstop=file” on page 331.
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.
This pragma requests that the specified list of functions always be compiled to have a complete
stack frame (as defined in the System V ABI). You must declare the prototype for a function
before listing that function with this pragma.
This pragma is permitted only after the prototype for the specified functions is declared. The
pragma must precede the end of the function.
void foo(int) {
.
#pragma must_have_frame(foo)
.
return;
}
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.
For a more detailed explanation of how the pragma treats overloaded function names as
arguments, see “B.1.1 Overloaded Functions as Pragma Arguments” on page 363.
funcname specifies the name of a function defined within the current translation unit. The value
of level specifies the optimization level for the named function. You can assign optimization
levels 0, 1, 2, 3, 4, 5. You can turn off optimization by setting level to 0. The functions must be
declared with a prototype or empty parameter list prior to the pragma. The pragma must
proceed the definitions of the functions to be optimized.
The level of optimization for any function listed in the pragma is reduced to the value of
-xmaxopt. The pragma is ignored when -xmaxopt=off.
For a more detailed explanation of how the pragma treats overloaded function names as
arguments, see “B.1.1 Overloaded Functions as Pragma Arguments” on page 363.
If present, n must be 0 or a power of 2. A value of other than 0 instructs the compiler to use the
smaller of n-byte alignment and the platform’s natural alignment for the data type. For example,
the following directive causes the members of all structures defined after the directive (and
before subsequent pack directives) to be aligned no more strictly than on 2-byte boundaries,
even if the normal alignment would be on 4- or 8-byte boundaries.
#pragma pack(2)
When n is 0 or omitted, the member alignment reverts to the natural alignment values.
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.
x86 4
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.
When using #pragma pack on a SPARC platform to pack denser than the type’s default
alignment, the -misalign option must be specified for both the compilation and the linking of
the application. The following table shows the storage sizes and default alignments of the
integral data types.
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
pointer to data 4, 4 8, 8 4, 4
pointer to function 4, 4 8, 8 4, 4
This pragma provides a hint to the compiler that the specified functions are called infrequently.
This allows the compiler to perform profile-feedback style optimizations on the call-sites of
such routines without the overhead of a profile-collections phase. Since this pragma is a
suggestion, the compiler may not perform any optimizations based on this pragma.
The #pragma rarely_called preprocessor directive is only permitted after the prototype for
the specified functions are declares. The following is an example of #pragma rarely_called:
For a more detailed explanation of how the pragma treats overloaded function names as
arguments, see “B.1.1 Overloaded Functions as Pragma Arguments” on page 363.
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.
For a more detailed explanation of how the pragma treats overloaded function names as
arguments, see “B.1.1 Overloaded Functions as Pragma Arguments” on page 363.
Use unknown_control_flow to specify a list of routines that violate the usual control flow
properties of procedure calls. For example, the statement following a call to setjmp() can be
reached from an arbitrary call to any other routine. The statement is reached by a call to
longjmp().
Because such routines render standard flowgraph analysis invalid, routines that call them
cannot be safely optimized; hence, they are compiled with the optimizer disabled.
If the function name is overloaded, the most recently declared function is chosen.
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.
Overloading Functions
When you use the identifier form, there must be exactly one function with the specified name in
scope at the pragma location. Attempting to use the identifier form of #pragma weak with an
overloaded function is an error. For example:
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.
ANSI/ISO C++ The American National Standards Institute and the ISO standard for the C++ programming language. See
ISO.
application binary The binary system interface between compiled applications and the operating system on which they run.
interface
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 The ability to link object files that are compiled by one release while using a compiler of a different release.
compatibility
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.
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.
377
constructor
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.
derived class See inheritance.
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.
early binding See static binding.
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.
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.
inheritance A feature of object-oriented programming that allows the programmer to derive new classes (derived
classes) from existing ones (base classes). There are three kinds of inheritance: public, protected, and
private.
inline function A function that replaces the function call with the actual function code.
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.
instantiation The process by which a C++ compiler creates a usable function or object (instance) from a template.
ISO International Organization for Standardization.
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.
late binding See dynamic binding.
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.
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.
mangle See name mangling.
member function An element of a class that is a function, as opposed to a data definition or type definition.
multiple Inheritance of a derived class directly from more than one base class.
inheritance
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.
379
namespace
namespace A mechanism that controls the scope of global names by allowing the global space to be divided into
uniquely named scopes.
operator The ability to use the same operator notation to produce different outcomes. A special form of function
overloading overloading.
optimization The process of improving the efficiency of the object code that is generated by the compiler.
runtime type A mechanism that provides a standard method for a program to determine an object type during runtime.
identification
(RTTI)
rvalue The variable that is located to the right of an assignment operator. The rvalue can be read but not altered.
scope The range over which an action or definition applies.
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.
stack A data storage method by which data can be added to or removed from only the top of the stack, using a
last-in, first-out strategy.
static binding Connection of a function call to a function body at compile time. Also called early binding.
template A specialized instance of a class template member function that overrides the default instantiation when
specialization the default cannot handle a given type adequately.
trapping Interception of an action, such as program execution, in order to take other action. The interception
causes the temporary suspension of microprocessor operations and transfers program control to another
source.
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.
381
382
Index
383
Index
385
Index
files functions
See also source files in dynamic (shared) libraries, 205
C standard header files, 150 inlining by optimizer, 302
copying, 181, 188 MT-safe public, 122
executable program, 37 overriding, 66
multiple source, using, 36 static, as class friend, 69
object, 37, 48, 205 streambuf public virtual, 132
opening and closing, 181-182
repositioning, 182-183
standard library, 150
using fstreams with, 180-183 G
-filt, compiler option, 231 -G
finalization functions, 368 dynamic library command, 205
-flags, compiler option, 233 option description, 241
float inserter, iostream output, 173 -g
floating point compiling templates using, 97
invalid, 240 option description, 242
options, 52 garbage collection
libraries, 141, 146
precision (Intel), 239
get, char extractor, 177
flush, iostream manipulator, 184
get pointer, streambuf, 188
flush, iostream manipulator, 176
__global, 64
-fnonstd, compiler option, 234
global
-fns, compiler option, 234-236
data, in a multithreaded application, 129
format control, iostreams, 183
instances, 93
Fortran runtime libraries, linking, 309
linkage, 93
-fprecision=p, compiler option, 236
shared objects in MT application, 130
front end, compilation component, 40 -gO option description, 243
-fround=r, compiler option, 237-238
-fsimple=n, compiler option, 238
-fstore, compiler option, 239
fstream, defined, 172, 191 H
fstream.h -H, compiler option, 244
iostream header file, 173 -h, compiler option, 244
using, 180 header files
-ftrap, compiler option, 240 C standard, 150
__func__, identifier, 69-70 complex, 200
function-level reordering, 299 creating, 71-72
function templates, 75-76 idempotency, 72
See also templates iostream, 130, 173, 184
declaration, 75 language-adaptable, 71-72
definition, 75-76 standard library, 149, 154-155
using, 76 heap, setting page size for, 325
function, declaration specifier, 63 -help, compiler option, 244
functions, name in __func__, 69-70 hex, iostream manipulator, 184
387
Index
__hidden, 64 instantiation
options, 92
template class static data members, 80
template classes, 79
I template function members, 80
.i, file name suffixes, 35 template functions, 79
I/O library, 171 -instlib, compiler option, 249
-I-, compiler option, 245-247 intermediate language translator, compilation
-I, compiler option, 98, 244-245 component, 40
-i, compiler option, 247 internationalization, implementation, 31
__i386, predefined macro, 219 interprocedural optimizations, 305
i386, predefined macro, 219 interval arithmetic libraries, linking, 302
idempotency, 71 iomanip.h, iostream header files, 173, 184
ifstream, defined, 172 iostream.h, iostream header file, 130, 173
.il, file name suffixes, 36 iostream
-include, compiler option, 248 classic iostreams, 140, 143, 255
include directories, template definition files, 98 compatibility mode, 171
include files, search order, 244, 245-247
constructors, 172
incompatibility, compiler versions, 36
copying, 183
initialization function, 369
creating, 180-183
-inline, See -xinline, 248
defined, 191
inline expansion, assembly language templates, 40
error bits, 175
inline functions
error handling, 179
by optimizer, 302
extending functionality, MT considerations, 132
C++, when to use, 112
input/output, complex, 171, 198 flushing, 176
input formats, 183
binary, 178 header files, 173
error handling, 179 input, 176
iostream, 176 library, 140, 143-144, 146
peeking at, 178 man pages, 171, 189-190
insertion operator manipulators, 183-187
complex, 198 mixing old and new forms, 255
iostream, 173-176 MT-safe interface changes, 127-129
insertion iostream, MT-safe reentrant functions, 123
defined, 191 iostream
operator, 173 MT-safe restrictions, 124-125
instance methods new class hierarchy for MT, 127-128
explicit, 95 new MT interface functions, 128
global, 95 output errors, 175
semi-explicit, 96 output to, 173-176
static, 95 predefined, 171
template, 92 single-threaded applications, 124
instance states, consistent, 97 standard iostreams, 140, 143, 255
-instances=a, compiler option, 92, 248 standard mode, 171, 173, 255
389
Index
391
Index
393
Index
stdio __symbolic, 64
with iostreams, 179-180 symbols, See macros
STL (Standard Template Library), components, 153 -sync_stdio, compiler option, 268
STLport, 168 syntax
storage sizes, 371-372 CC commands, 34
stream, defined, 191 options, 47
stream.h, iostream header file, 173
stream_locker
man pages, 132
synchronization with MT-safe objects, 127 T
streambuf -temp=dir, compiler option, 269
defined, 187, 191 -template, compiler option, 98
get pointer, 188 -template, compiler option, 92, 269
locking, 122 template definition
man pages, 188 included, 73
new functions, 128 search path, 98
public virtual functions, 132 separate, 74
separate, file, 98
put pointer, 188
troubleshooting a search for definitions, 98
queue-like versus file-like, 188
template instantiation, 79-80
using, 188
explicit, 79-80
streampos, 182
function, 79-80
string literal of U"..." form, 358
implicit, 79
strstream, defined, 172, 191
whole-class, 92
strstream.h, iostream header file, 173
template pre-linker, compilation component, 40
struct, anonymous declarations, 67-68 template problems, 83-89
structure declaration specifier, 64 friend declarations of template functions, 84-86
subprograms, compilation options, 38 local types as arguments, 84
suffixes non-local name resolution and instantiation, 83
command line file name, 35 static objects, referencing, 87
files without, 150 troubleshooting a search for definitions, 98
library, 203 using qualified names in template definitions, 86-87
.SUNWCCh, 150 templates
__sun, predefined macro, 219 cache directory, 36
__SUNPRO_CC, 218 commands, 91
__SUNPRO_CC, predefined macro, 218 compilation, 93
__SUNPRO_CC_COMPAT=(4|5), predefined macro, 215, definitions-separate vs. definitions-included
218 organization, 98
.SUNWCCh file name suffix, 150 inline, 311
SunWS_cache, 96 instance methods, 92, 97
__SVR4, predefined macro, 218 linking, 38
swap -s, command, 42 nested, 80
swap space, 42 options, 59-60
symbol declaration specifier, 63 partial specialization, 82
symbol tables, executable file, 266 repositories, 96
V X
-V, compiler option, 272 X inserter, iostream, 173
-v, compiler option, 39, 272 -xa, compiler option, 274-275
__VA_ARGS__ identifier, 41 -xalias_level, compiler option, 275
395
Index