HP aC++/HP C A.06.
© Copyright 2012, 2014 Hewlett-Packard Development Company, L.P. Confidential computer software. Valid license from HP required for possession, use or copying. Consistent with FAR 12.211 and 12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are licensed to the U.S. Government under vendor's standard commercial license. The information contained herein is subject to change without notice.
Contents HP secure development lifecycle....................................................................17 About This Document ..................................................................................18 Intended Audience..................................................................................................................18 What’s in This Document.........................................................................................................18 Typographical Conventions......
+DSmodel........................................................................................................................33 Using +DS to Specify Instruction Scheduling.....................................................................33 Compiling in Networked Environments.............................................................................33 -S.....................................................................................................................................
+hdr_create......................................................................................................................45 +hdr_use..........................................................................................................................45 -I directory........................................................................................................................45 -I-.............................................................................................................
Advanced +Ooptimization Options......................................................................................57 +O[no]cross_region_addressing......................................................................................58 +O[no]datalayout.........................................................................................................58 +O[no]dataprefetch.......................................................................................................58 +O[no]fltacc..............
-E.....................................................................................................................................72 Redirecting Output From This Option...............................................................................72 make[d]............................................................................................................................73 +Make[d]...................................................................................................................
-Bsymbolic.........................................................................................................................91 Template Options...................................................................................................................91 +[no]dep_name.................................................................................................................91 +inst_compiletime..................................................................................................
HDR_STOP Pragma..........................................................................................................107 HIDDEN Pragma.............................................................................................................107 HP_DEFINED_EXTERNAL Pragma......................................................................................107 HP_DEFINED_INTERNAL Pragma.......................................................................................107 IF_CONVERT Pragma...........
4 Preprocessing Directives..........................................................................119 Overview of the Preprocessor.................................................................................................119 Syntax............................................................................................................................119 Usage Guidelines............................................................................................................
5 Using HP aC++ Templates.......................................................................132 Invoking Compile-Time Instantiation.........................................................................................132 Scope and Precedence.....................................................................................................132 Template Processing.........................................................................................................132 Explicit Instantiation.........
Example....................................................................................................................149 typename Keyword..........................................................................................................149 Usage.......................................................................................................................149 Example....................................................................................................................
Function Scoping..................................................................................................................167 Performance Options.............................................................................................................167 Parallel Programming Using OpenMP......................................................................................167 OpenMP Implementation..................................................................................................
Standard Components Library Not Provided...................................................................179 Linking to C++ Libraries...............................................................................................180 Linking with Shared or Archive Libraries.........................................................................180 Specifying Other Libraries............................................................................................180 Creating and Using Shared Libraries....
Strings.......................................................................................................................194 Arrays.......................................................................................................................194 Files in FORTRAN........................................................................................................194 11 Distributing Your C++ Products................................................................
overload not a Keyword...............................................................................................213 Dangling Comma in enum...........................................................................................214 Static Member Definition Required.................................................................................214 Declaring friend Classes...............................................................................................
HP secure development lifecycle Starting with HP-UX 11i v3 March 2013 update release, HP secure development lifecycle provides the ability to authenticate HP-UX software. Software delivered through this release has been digitally signed using HP's private key. You can now verify the authenticity of the software before installing the products, delivered through this release. To verify the software signatures in signed depot, the following products must be installed on your system: • B.11.31.
About This Document This manual presents programming information on the C++ programming language, as implemented on Itanium®- based systems. The document printing date and part number indicate the document’s current edition. The printing date will change when a new edition is printed. Minor changes may be made at reprint without changing the printing date. The document part number will change when extensive changes are made.
Chapter 9 Tools and Libraries Discusses the tools and libraries bundled with HP aC++. Chapter 10 Mixing C++ with Other Languages Provides guidelines for linking HP aC++ modules with modules written in HP C and HP FORTRAN 90 on HP systems. Chapter 11 Distributing Your C++ Products Provides distribution-related information for C++ products. If you choose to distribute archive libraries or object files, your customer must have purchased HP aC++.
HP-UX Release Name and Release Identifier Each HP-UX 11i release has an associated release name and release identifier. Theuname(1) command with the -r option returns the release identifier. This table shows the releases available for HP-UX 11i. Table 1 HP-UX 11i Releases Release Identifier Release Name Supported Processor Architecture B.11.31 HP-UX 11i v3.0 Intel® Itanium® B.11.11 HP-UX 11i v1 PA-RISC B.11.23 HP-UX 11i v2.0 PA-RISC B.11.31 HP-UX 11i v3.0 PA-RISC B.11.20 HP-UX 11i v1.
The following is a list of documents available with this release: • HP aC++/HP ANSI C Release Notes This document gives an overview of new command-line options and features in HP aC++ and HP C compilers for Itanium®-based systems. • HP C/HP-UX Reference Manual This manual presents reference information on the C and C++ programming languages. HP Encourages Your Comments HP encourages your comments concerning this document. We are truly committed to providing documentation that meets your needs.
1 Getting Started with HP aC++ The information in this document applies to the release of HP aC++ and HP ANSI C compilers version A.06.28 for the HP-UX 11i v3 operating system. The HP ANSI C compiler supports ANSI programming language C standard ISO 9899:1999. HP aC++ compiler supports the ISO/IEC 14882 Standard for the C++ Programming Language (the international standard for C++). Version A.06.
Standard C++ Library /usr/lib/hpux32/libstream.so /usr/lib/hpux32/libstream.a /usr/lib/hpux64/libstream.so /usr/lib/hpux64/libstream.a (32-bit (32-bit (64-bit (64-bit shared version) archive version) shared version) archive version) Header files for these libraries are located at /opt/aCC/include/. Using the aCC Command To invoke the HP aC++ compiling system, use the aCC command at the shell prompt.
The gdb command runs the HP WDB debugger: $ gdb a.out For more information on the HP WDB debugger, refer to “Debugging Options” (page 35). Accessing Online Example Source Files Online example source files are located in the directory /opt/aCC/contrib/Examples/ RogueWave. These include examples for the Standard C++ Library and for the Tools.h++ Library. Compiler Command Syntax and Environmental Variables The aCC command (the driver) invokes the HP aC++ compiling system.
This command compiles and optimizes prog.C, gives verbose progress reports, and creates an executable file a.out. Compiling and Creating a Shared Library aCC +z -c prog.C aCC -b -o mylib.sl prog.o The first line compiles prog.C, creates the object file prog.o, and puts the position-independent code (PIC) into the object file. The second line creates the shared library mylib.sl, and puts the executable code into the shared library.
Object Files (.o Files) Files with .o extensions are assumed to be relocatable object files that have to be included in the linking. The compiler invokes the linker to link the object files and create an executable file. Use the -c option to compile a C++ source file into a .o file. Library Files (.a and .so Files) Files ending with .a are assumed to be archive libraries. Files ending with .so are assumed to be shared libraries.
• “CXX_MAP_FILE Environment Variable” (page 29) • “TMPDIR Environment Variable” (page 29) aCC_FULL_PATHNAMES Environment Variable Exporting the aCC_FULL_PATHNAMES variable causes the compiler to include full path names for files in compiler messages. This feature is useful in debugging. aCC_MAXERR Environment Variable The aCC_MAXERR environment variable allows you to set the maximum number of errors you want the compiler to report before it terminates compilation. The default is 100.
When CCLIBDIR is set a in the above example, the following two commands are equivalent: aCC -L/mnt/proj/lib file.o aCC file.o NOTE: You can use the -Ldirectory option to specify additional directories for the linker to search for libraries. CCROOTDIR Environment Variable The CCROOTDIR environment variable causes aCC to invoke all subprocesses from an alternate aCC directory, rather than from their default directory. The default aCC root directory is /opt/ aCC.
export CCROOTDIR=/mnt/CXX2.1 In this example, HP aC++ searches the directories under /mnt/CXX2.1 (/mnt/CXX2.1/bin and /mnt/CXX2.1/lbin) for subprocesses rather than their respective default directories. CXX_MAP_FILE Environment Variable To facilitate easy migration of build environment from a different compiler to HP aC++, an option mapping support is provided. You can use the option mapping files to map the options in the third party compilers to HP aC++ equivalents.
HP aC++ By default, HP aC++ is installed under the /opt/aCC directory. In earlier releases, the compiler driver (aCC) looked for related files in subdirectories of the /opt/aCC directory. This prevented installation of more than one version of HP aC++ on the same system at the same time. Only files in /opt/aCC are affected by floating installation. Regardless of the HP aC++ driver you use, the compiler still uses the libraries, linker, and other files located in /usr/lib and /usr/ ccs.
2 Command-Line Options You can specify command-line options to the aCC command. They allow you to override the default actions of the compiler. Each option begins with either a - or a + sign. Any number of options can be interspersed anywhere in the aCC command and they are typically separated by blanks. Unless specified otherwise, all options are supported by C and C++ compilers. Default options can be set using option configuration files. See “Configuration Files (.conf Files)” (page 26).
Options to Control Code Generation The following options allow you to control the kind of code that the compiler generates: • -c • +DOosname • +DDdata_model • +DSmodel • -S -c You can use the -c option to compile one or more source files without entering the linking phase. When compiled, the compiler produces an object file (a file ending with .o) for each source file (a file ending with .c, .C, .s, or .i). Note that you must link object files before they can be executed. Example: aCC -c sub.
Examples: The following command generates code for the 64-bit data model: aCC +DD64 app.C The following command generates code for the 32-bit data model: aCC app.C +DSmodel The +DSmodel option performs instruction scheduling for a particular implementation of the Itanium®-based architecture. model can be one of the following values. blended Tune to run reasonably well on multiple implementations.
The following command compiles prog.C to assembly code rather than to object code, and puts the assembly code in the file prog.s. aCC -S prog.C Data Alignment and Storage This section describes default data storage allocation and alignment for HP compiler data types. Data storage refers to the size of data types, such as bool, short, int, float, and char*. Data alignment refers to the way the HP compiler aligns data structures in memory.
Table 3 Size and Alignment of HP Compiler Data Types (continued) Data Type Size (in bytes) Alignment *** struct and union alignment are same and follow strict alignment of any member. Padding is done to a multiple of the alignment size. -fshort-enums cc -Agcc -Wc,--fshort-enums foo.c aCC -Ag++ -Wc,--fshort-enums foo.
To suppress expansion of inline functions, use the +d option. -g1 Like the -g option, the -g1 option causes the compiler to generate minimal information for the debugger. It uses an algorithm that attempts to reduce duplication of debug information. To suppress expansion of inline functions, use the +d option. Differences Between -g, -g0, and -g1 Options The -g, -g0, and -g1 options generate debug information.
+[no]objdebug The +objdebug option generates debug information in object files and not in the executable. The HP WDB debugger then reads the object files to construct debugging information; they must be present when debugging. The +noobjdebug option generates debug information in object files which the linker places into the executable. The HP WDB debugger then reads the executable to construct debugging information. NOTE: With +objdebug, the object files or archive libraries must not be removed.
where: global_fixed_size • TABLE_SIZE specifies the size, expressed as the number of items (nnn), of the global path table. • FILE specifies the dumping output filename to use when the global path table is full. • FORMAT specifies the dumping format in either "binary or human-readable "text". Generates a fixed-size (65536 items) global path table and records basic block-execution information in it at runtime.
this list can be included in an options file and referenced using the +opts option to avoid listing them all directly on the command line. Example: The following command compiles file.C and reports errors but does not report any warnings. aCC -w file.C +w The +w option warns you about all questionable constructs and gives pedantic warnings. +w enables all checks except for the +wsecurity, +wendian, +wperfadvice, and+wlock warnings. Those need to be enabled explicitly if needed.
+We +We The +We option interprets all warning and future error messages as errors. Alternatively you can also use +We[arg1,...argn] option, where arg is a valid compiler warning message number. Use of arg is optional. +Weargs +Wearg1[,arg2,..,argn] The +Weargs option selectively interprets any specified warning or future error messages as errors. arg1 through argn are valid compiler warning message numbers. Example: aCC +We 600,829 app.C +Wv +Wv[d1,d2,..
The optional level 1, 2, 3,or 4 controls how verbosely the performance advisory messages are emitted. The higher the level, the more messages generated. Level 1 emits only the most important messages, while level 4 emits all the messages. If the optional level is not specified, it defaults to 2. +wsecurity The +wsecurity option enables compile-time diagnostics for potential security violations.
Specifying -ext, enables the following HP aC++ extensions to the C++ standard: • 64-bit integer data type support for: ◦ long long (signed 64-bit integer) ◦ unsigned long long (unsigned 64-bit integer) • Use this option to declare 64-bit integer literals and for input and output of 64-bit integers. • #assert, #unassert preprocessor directives, which allow you to set a predicate name or predicate name and token to be tested with a #if directive.
-fpeval -fpeval=precision The -fpeval option specifies the minimum precision to use for floating-point expression evaluation. This option does not affect the precision of parameters, return types, or assignments. The defined values for precision are: float Evaluates floating-point expressions and constants in their semantic type. double Evaluates float operations and constants using the range and precision of double, and evaluates all other floating-point expressions and constants in their semantic type.
Table 4 Options for +FP[flags] Flag Description V (v) Trap on invalid floating-point operations. Z (z) Trap on divide by zero. O (o) Trap on floating-point overflow. U (u) Trap on floating-point underflow. I (i) Trap on floating-point operations that produce inexact results. D (d) Enable sudden underflow (flush to zero) of denormalized values. To dynamically change these settings at runtime, see fesetenv(3M).
+O[no]rotating_fpregs +O[no]rotating_fpregs The +O[no]rotating_fpregs option specifies whether the compiler is allowed [not allowed] to make use of the rotating subset of the floating-point register file. The default is +Orotating_fpregs. +O[no]sumreduction +O[no]sumreduction This option enables [disables] sum reduction optimization. It allows the compiler to compute partial sums to allow faster computations. It is not technically legal to do this in C or C++ because of floating-point accuracy issues.
1. 2. 3. The directory of the source file containing the #include. The directory named in the -I option. The standard include directories /opt/aCC/include and /usr/include. For #include files that are enclosed in angle brackets (< >), the preprocessor searches in the following order: 1. The directory named in the -I option. 2. The standard include directories /opt/aCC/include and /usr/include. NOTE: The current directory is not searched when angle brackets (< >) are used with #include.
aCC -Idir1 -Idir2 -c a.C With view-pathing on, the following example searches for quoted include files in dir1 first and dir2 next, followed by the standard include directories, ignoring the directory of a.C. Angle-bracketed includes are searched for in dir2 first, followed by the standard include directories. aCC -Idir1 -I- -Idir2 -c a.C NOTE: Some of the compiler’s header files are included using double quotes.
To use a browser other than the default, first set the BROWSER environment variable to the alternate browser’s location: export BROWSER=AlternateBrowserLocation To invoke the online guide, use the command: aCC +help Inlining Options These options allow you to specify the amount of source code inlining done by HP aC++. +inline_level num +inline_level num The +inline_level option controls how C/C++ inlining hints influence aCC or cc.
Library Options Library options allow you to create, use, and manipulate libraries. -b -b The -b option creates a shared library rather than an executable file. Example: The following command links utils.o and creates the shared library utils.so. aCC -b utils.o -o utils.so For more information on shared libraries, see “Creating and Using Libraries” (page 175). -dynamic -dynamic The -dynamic option produces dynamically bound executables.
-L directory -L directory The directory parameter is the HP-UX directory where you want the linker to search for libraries your program uses before searching the default directories. The -L directory option causes the linker to search for libraries in directory in addition to using the default search path. See -lname option for default search path. The -L option must precede any -lname option entry on the command line; otherwise -L is ignored. This option is passed directly to the linker.
For details and system defaults, refer to the description of ld in the HP-UX Reference Manual or the ld(1) manpage for more information. -N -N The -N option causes the program file produced by the linker to be marked as unsharable. For details and system defaults, refer to the description of ld in the HP-UX Reference Manual or the ld(1) manpage for more information. +O[no]dynopt +O[no]dynopt Supported only on HP-UX 11.
+ild +ild The +ild option specifies incremental linking. If the output file does not exist, or if it was created without the +ild option, the linker performs an initial incremental link. The output file produced is suitable for subsequent incremental links. The incremental link option is valid for both executable and shared library links. It is not valid for relocatable links, options or tools that strip the output module, and certain optimization options.
The language value (refer to environ(5) for the LANG environment variable) is used to initialize the correct tables for interpreting comments, string literals, and character constants. The language value is also used to build the path name to the proper message catalog. For more information and description of the NLS model, refer to hpnls, lang, and environ in HP-UX Reference Manual. Handling Null Pointers Options The following options allow dereferencing of null pointers.
tunable will ensure that the compiler does not run out of virtual memory when compiling large files or functions. In addition, maxssiz_64bit should be set to 128 MB for very large or complex input files. (Normally a maxssiz_64bit setting of 64 MB will be sufficient.) See the kctune man page for more information on how to change kernel tunable parameters. -O -O The -O option invokes the optimizer to perform level 2 optimization. This option is equivalent to +O2 option. Example: This command compiles prog.
NOTE: Compiling with this optimization setting may require additional memory resources. Refer to the memory resource discussion above. Example: This command compiles prog.C and optimizes at level 3: aCC +O3 prog.C +O4 +O4 The +O4 option performs level 4 optimization. This includes level 3 optimizations plus full optimizations across the entire application program. Also, the defaults that depend on optimization will be the defaults for +O3.
-ipo The -ipo option enables interprocedural optimizations across files. The object file produced using this option contains intermediate code (IELF file). At link time,ld automatically invokes the interprocedural optimizer (u2comp), if any of the input object files is an IELF file. For optimization levels +O0 and +O1, this option is silently ignored. The-ipo option will get implicitly invoked with the +O4 and +Ofaster options to match current behavior (+O4 ==> +O3 -ipo).
+O[no]aggressive +O[no]aggressive The +Oaggressive option enables aggressive optimizations. The +Onoaggressive option disables aggressive optimizations. By default, aggressive optimizations are turned off. The +Oaggressive option is approximately equivalent to +Osignedpointers +Onoinitcheck +Ofltacc=relaxed. NOTE: This option is deprecated and may not be supported in future releases. Instead you can use +Ofastoption.
+O[no]cross_region_addressing +O[no]cross_region_addressing The +O[no]cross_region_addressing option enables [disables] the use of cross-region addressing. Cross-region addressing is required if a pointer, such as an array base, points to a different region than the data being addressed due to an offset that results in a cross-over into another region. Standard conforming applications do not require the use of cross-region addressing. The default is +Onocross_region_addressing.
+Ofltacc=level The defined values for level are: default Allows contractions, such as fused multiply- add (FMA), but disallows any other floating-point optimization that can result in numerical differences. limited Like default, but also allows floating-point optimizations which may affect the generation and propagation of infinities, NaNs, and the sign of zero.
+O[no]inline +O[no]inline The +Oinline option indicates that any function can be inlined by the optimizer. +Onoinline disables inlining of functions by the optimizer. This option does not affect functions inlined at the source code level. Use +O[no]inline at optimization levels 2, 3 and 4. The default is +Oinline at optimization levels 3 and 4. Usage: +O[no]inline=function1{,function2...] Enables [disables] optimizer inlining for the named functions.
+Olevel +Olevel=name1[,name2,...,nameN] The +Olevel option lowers optimization to the specified level for one or more named functions. level can be 0, 1, 2, 3, or 4. The name parameters are names of functions in the module being compiled. Use this option when one or more functions do not optimize well or properly. This option must be used with a basic +Olevel or -O option. Note that currently only the C++ mangled name of the function is allowed for name. This option works like the OPT_LEVEL pragma.
It is recommended that you use the -N option when linking OpenMP programs to avoid exhausting memory when running with large numbers of threads. NOTE: HP aC++ version A.06.00 does not support C++ constructs in OpenMP. Use the +legacy_v5 option to use this option. +opts +opts filename The file indicated by filename contains a list of options that are processed as if they had been specified on the command line at the point of the +opts option. The options must be delimited by a blank character.
The +O[no]promote_indirect_calls option uses profile data from profile-based optimization and other information to determine the most likely target of indirect calls and promotes them to direct calls. Indirect calls occur with pointers to functions and virtual calls. In all cases the optimized code tests to make sure the direct call is being taken and if not, executes the indirect call. If +Oinline is in effect, the optimizer may also inline the promoted calls.
+O[no]store_ordering +O[no]store_ordering The +O[no]store_ordering option preserves [does not preserve] the original program order for stores to memory that is visible to multiple threads. This does not imply strong ordering. The default is +Onostore_ordering. +Otype_safety +Otype_safety=kind The +Otype_safety option controls type-based aliasing assumptions. The defined values for kind are: off The default. Specifies that aliasing can occur freely across types. limited Code follows ANSI aliasing rules.
default. The name is generated as flow. if there is already a flow.datafile present in the current directory. Finally, recompile with the +Oprofile=use option (passing it the appropriate filename if necessary) to perform profile-based optimization. Example: aCC +Oprofile=collect -O -o prog.pbo prog.C The above command compiles prog.C with optimization, prepares the object code for data collection, and creates the executable file prog.pbo. Running prog.
-mt The -mt option enables multi-threading capability without the need to set any other flags, such as -l and -D. HP aC++ examines your environment and automatically selects and sets the appropriate flags. “Performance Options” (page 167). There are three possible sets of flags depending on your operating system and the libstd you use. Table 5 lists the option matrix for -mt. Table 5 Option Matrix for -mt Libraries Flags old-lib -D_REENTRANT libstd 1.2.
• _POSIX_C_SOURCE=199506L Required by pthread. • libpthread.* Kernel thread library used on 11.x systems See “Using Threads” (page 163) for more information. NOTE: Make sure that -mt is used consistently at compile and link times. When you link with -mt, everything must be compiled with -mt, even if you do not think your file will be used in a threaded application.
dynamic This is a less efficient mode in which thread local data outside the program startup set can be accessed as well. This is the default. Translation units compiled with different settings of this option may be freely mixed, even within the same load module. +wlock +wlock The +wlock option enables compile-time diagnostic messages for potential errors in using lock/unlock calls in programs that use pthread-library-based lock/unlock functions.
• +FPD • -Wl,+pi,1M • -Wl,+pd,1M • -Wl,+mergeseg This option is a synonym for -fast. NOTE: Do not use this option for programs that depend on IEEE standard floating point denormalized numbers. Otherwise, different numerical results may occur. See +Ofltacc=relaxed. +Ofaster +Ofaster The +Ofaster option is equivalent to +Ofast with an increased optimization level. The definition of +Ofaster may change, or the option may be deprecated in future releases.
Porting Options Use the following options as necessary when porting your code from other operating environments to HP-UX. -fast -fast The -fast option selects a combination of optimization options for optimum execution speed and reasonable build times. Currently chosen options are: • +O2 • +Ofltacc=relaxed • +Onolimit • +DSnative • +FPD You can override any of the options in -fast by specifying a subsequent option after it. This option is equivalent to +Ofast.
+w64bit The +w64bit option enables warnings that help detection of potential problems in converting 32-bit applications to 64-bit. The option is equivalent to the +M2 option. +wdriver The +wdriver option enables warnings for PA-RISC options that would otherwise be ignored silently on Integrity servers. With the addition of this option in version A.06.05, a number of warnings for PA options that had been reported by previous compiler versions were changed to be silently ignored by default.
Preprocessor Options The following options are accepted by the preprocessor: -C -C Using the -C option prevents the preprocessor from stripping comments. See the description of cpp in the cpp(1) manpage for details. -dM -dM When -dM is present, instead of normal preprocessor output the compiler lists the #define directives it encounters as it preprocesses the file, thus providing a list of all macros that are in effect at the start of the compilation.
make[d] +make[d] The +make[d] option directs a list of the quote enclosed (" ") header files upon which your source code depends to stdout. The list is in a format accepted by the make command. If +maked is specified, the list is directed to a .d file. The .d file name prefix is the same as that of the object file. The .d file is created in the same directory as the object file. Usage: Use +maked when you also specify the -E or the -P option.
-Uname -Uname name is the symbol name whose definition is removed from the preprocessor. This option undefines any name that has initially been defined by the preprocessing stage of compilation. A name can be a definition set by the compiler. This is displayed when you specify the -v option. A name can also be a definition that you have specified with the -D option on the command line. The -D option has lower precedence than the -U option.
Runtime Checking Options The +check options allow you to check your application for errors at runtime. +check +check=all|none|bounds|globals|lock|malloc|stack|thread|truncate|uninit The +check=xxx options provide runtime checks to detect many common coding errors in the user program. These options introduce additional instructions for runtime checks that can significantly slow down the user program. By default, a failed check will result in the program aborting at the end of execution at runtime.
and so on. The check can create significant run-time performance overhead. See +check=uninit and +check=malloc for their interaction with this option. • all - Enables out-of-bounds checks for both arrays and pointers. This is equal to +check=bounds:array +check=bounds:pointer. • none - Disables out-of-bounds checks. +check=bounds (with no suboption) is equal to +check=bounds:array. This may change in the future to also include +check=bounds:pointer.
i, lp[i], i+1, ip[i+1], j, ip[j]); ^ Catch out-of-bounds pointer access through an uninitialized variable (the uninitialized variable can be checked by +check=uninit): $ RTC_NO_ABORT=1 a.out 2 Runtime Error: out of bounds buffer pointed by 0x40010320 has 40 bytes (variable "a"), reading at 0x40010320-19824, 4 bytes ("rttest3.c", line 33) (0) 0x0000000004004770 _rtc_raise_fault + 0x560 at rtc_utils.c:164 [./a.out](1) 0x0000000004008790 _rtc_oob_check_unknown_bounds + 0x1f0 at rtc_bounds.c:465 [./a.
RTC_NO_ABORT=1 a.out 20 $Runtime Error: out of bounds buffer pointed by 0x40010350 has 10 bytes (variable "b"), writing at 0x40010350+0, 20 bytes ("memset", line 0) (0) 0x0000000004004770 _rtc_raise_fault + 0x560 at rtc_utils.c:164 [./a.out] (1) 0x00000000040089d0 _rtc_oob_check_unknown_bounds + 0x430 at rtc_bounds.c:480 [./a.out] (2) 0x60000000c5f52440 libc_mem_common + 0x280 at infrtc.c:3286 [lib/hpux32/librtc.so] (3) 0x60000000c5f53650 _memset + 0x80 at infrtc.c:3521 [lib/hpux32/librtc.
void *thread2(void *arg) { pthread_mutex_lock(&mutex2); things_done++; pthread_mutex_unlock(&mutex2); return 0; } int main(int argc, char *argv[]) { pthread_t th1, th2; pthread_create(&th1, NULL, thread1, (void*)NULL ); pthread_mutex_lock(&mutex1); things_done++; pthread_mutex_unlock(&mutex1); pthread_create(&th2, NULL, thread2, (void*)NULL ); sleep(10); return 0; } cc +check=lock simple_race.c -lpthread ./a.out Runtime Error: locking discipline violation: in file simple_race.
Please install the HP WDB bundled with the compiler or a more recent version of wdb to get full functionality. The default behavior of the +check=malloc option can be changed by users providing their own rtcconfig file. The user specified rtcconfig file can be in the current directory or in a directory specified by the GDBRTC_CONFIG environment variable.
• Different threads non-concurrently wait on the same condition variable, but with different associated mutexes. • The threads terminate execution without unlocking the associated mutexes or read-write locks. • The thread waits on a condition variable for which the associated mutex is not locked. • The thread terminates execution, and the resources associated with the terminated thread continue to exist in the application because the thread has not been joined or detached.
If the +check=bounds:pointer is on, +check=uninit will check pointer access for uninitialized memory read (UMR). To enable checking, the runtime system will initialize the heap objects and stack variables with a special pattern. If the pointer accesses an area containing the specified pattern for the specified length, then it assumes the read is UMR.
This option enables the Tru64 UNIX C++ Annotated Reference Manual (ARM) dialect. This dialect was the default for Tru64 UNIX C++ compilers through compiler version 5.x. Support of this dialect is intended only to ease porting of existing Tru64 UNIX applications to HP-UX, and not for development of new programs. For more information on the ARM dialect, refer to the The Annotated C++ Reference Manual, (Margaret A. Ellis and Bjarne Stroustrup, Addison-Wesley, ISBN 0-201-51459-1, 1990).
NOTE: • For HP aC++, the -Ae option must also be used. • This option will be removed in a future version of the compiler. Use the equivalent option +std=gcc to ensure that your builds do not break in future.
+std=c89|c99|c++98|c++11|gcc|g++|gnu +std=c89: This option invokes the compiler in ANSI C89 compilation mode. This option when specified with the -ext option, it invokes a part of ANSI C99 feature. This is equivalent to the '–AC89' option. +std=c99: This option invokes the compiler in ANSI C99 compilation mode with its features. This is the default C compilation mode. This is equivalent to the '–AC99' option. +std=c++98: This option invokes the compiler in ISO C++98 standard mode.
+tru64 +tru64 This option causes return types of unprototyped functions to be treated as long, instead of int, matching Tru64 C behavior. This can prevent segfaults in +DD64 mode, resulting from pointer truncation, for instance: long *a; long sub() { a = malloc(sizeof(long)); *a = 1234; return *a; } /* no prototype! */ /* segfault if +DD64 and no +tru64 */ A preferable solution is to provide the appropriate function prototypes. NOTE: This option is applicable to C language only.
namespace N { struct S {}; void f(S const&, int); } // (1) void f(N::S const&, long); // (2) int main() { N::S x; f(x, 1); } Subprocesses of the Compiler These options allow you to substitute your own processes in place of the default HP aC++ subprocesses, or pass options to HP aC++ subprocesses. -tx,name -tx,name The -tx,name option substitutes or inserts subprocess x, using name. The parameter, x, is one or more identifiers indicating the subprocess or subprocesses.
aCC -tf,/new/bin/c++filt file.C • Substituting for ecom: The following example compiles file.C and specifies that /users/proj/ecom should be used instead of the default /opt/aCC/lbin/ecom. aCC -tC,/users/proj/ecom file.C • Substituting for all Subprocesses: The following example compiles file.C and specifies that the characters /new/aCC should be used as a prefix to all the subprocesses of HP aC++. For example, /new/aCC/ecom runs instead of the default /opt/aCC/lbin/ecom. aCC -tx,/new/aCC file.
Passing Options to the Linker with -W The following example links file.o and passes the option -a archive to the linker, indicating that the archive version of the math library (indicated by -lm) and all other driver-supplied libraries should be used rather than the default shared library: aCC file.o -Wl,-a,archive -lm Passing Multiple Options to the Linker with -W The following example links file.o and passes the options -a , archive, -m, and -v to the linker: aCC -Wl,-a,archive,-m,-v file.
-Bextern:filename The file indicated by filename is expected to contain a list of symbols, separated by spaces or newlines. These symbols are assigned the default export class. -Bhidden -Bhidden The specified symbols, or all symbols if no symbols are specified, are assigned the hidden export class. The hidden export class is similar to the protected export class. In addition, hidden symbols will not be exported outside the current load module.
The -Bprotected_def option is the same as -Bprotected but only locally defined (non-tentative) symbols are assigned the protected export class. -Bsymbolic -Bsymbolic The -Bsymbolic option assigns protected export class to all symbols. This is equivalent to -Bprotected with no symbol list. NOTE: This option is deprecated as of version A.06.05 and if used, it issues a warning that -Bprotected_defis almost always what should be used in its place.
The +inst_implicit_include option specifies that the compiler use a process similar to that of the cfront source rule for locating template definition files. For the cfront based HP C++ compiler, if you are using default instantiation (that is, if you are not using a map file), you must have a template definition file for each template declaration file, and these must have the same file name prefix. This restriction does not apply in HP aC++.
-notrigraph The-notrigraph option inhibits the processing of trigraphs. In previous versions, [LINEBREAK]-notrigraph caused the legacy preprocessor to be invoked. Though this ignored trigraphs, trigraphs were still interpreted by the compiler in the preprocessed source. The -notrigraph option no longer invokes the legacy preprocessor, and also suppresses trigraphs from being interpreted. This option is not recommended. The proper portable solution is to quote the "?" as "\?".
Examples: • The aCC +time app.C command generates the following information: process: compiler process: ld • 0.94/u 0.37/u 0.65/s 0.76/s 4.35/r 3.02/r The aCC -v +time app.C command generates the following information: /opt/aCC/lbin/ctcom -inst compiletime -diags 523 -D __hppa -D __hpux -D __unix -D __hp9000s800 -D __STDCPP__ -D __hp9000s700 -D _PA_RISC1_1 -I /opt/aCC/include -I /opt/aCC/include/iostream -I /usr -I /usr/include -I /usr/include -inline_power 0 app.C file name: app.C file size: app.
aCC -V app.C aCC: HP aC++/ANSI C B3910B A.06.00 [Aug 25 2004] ld: 92453-07 linker ld HP Itanium(R) B.12.24 PBO 040820 (IPF/IPF) Concatenating Options You can concatenate some options to the aCC command under a single prefix. The longest substring that matches an option is used. Only the last option can take an argument. You can concatenate option arguments with their options if the resulting string does not match a longer option. Examples: Suppose you want to compile my_file.C using the options -v and -g1.
3 Pragma Directives and Attributes A pragma directive is an instruction to the compiler. You use a #pragma directive to control the actions of the compiler in a particular portion of a translation unit without affecting the translation unit as a whole. Put pragmas in your C++ source code where you want them to take effect. Unless otherwise specified, a pragma is in effect from the point where it is included until the end of the translation unit or until another pragma changes its status.
Copyright Notice and Identification Pragmas The following pragmas can be used to insert strings in code. COPYRIGHT #pragma COPYRIGHT "string” string is the set of characters included in the copyright message in the object file. The COPYRIGHT pragma specifies a string to include in the copyright message and puts the copyright message into the object file. If no date is specified (using pragma COPYRIGHT_DATE), the current year is used in the copyright message.
The LOCALITY_ALL pragma specifies a name to be associated with the linker procedures and global variables that should be grouped together at program binding or load time. These are written to a relocatable object module. All procedures and global variables following the LOCALITY_ALL pragma are associated with the name specified in the string. VERSIONID #pragma VERSIONID "string" string is a string of characters that HP aC++ places in the object file.
int i; char c2; // Offset 4, no padding // Offset 8, 3 bytes padding // sizeof(S1)==12, alignment 4 }; #pragma pack 1 struct S2 { char c1; int i; char c2; }; // // // // Offset 0, no padding Offset 1, no padding Offset 5, no padding sizeof(S2)==6, alignment 1 // S3 and S4 show that the pragma does not affect class fields // unless the class itself was defined under the pragma.
Basic Example The following example illustrates the pack pragma and shows that it has no effect on class fields unless the class itself was defined under the pragma: struct S1 { char c1; int i; char c2; }; // // // // Offset 0, 3 bytes padding Offset 4, no padding Offset 8, 3 bytes padding sizeof(S1)==12, alignment 4 // // // // Offset 0, no padding Offset 1, no padding Offset 5, no padding sizeof(S2)==6, alignment 1 #pragma pack 1 struct S2 { char c1; int i; char c2; }; // S3 and S4 show that the pra
NOTE: The alignment of specializations and partial specializations of templates is undefined and unsupported if either the primary template or the specialization is under the influence of a #pragma pack directive. Handling Unaligned Data Direct access to unaligned class fields is handled automatically by HP aC++. However, this results in slower access times than for aligned data. Indirect access (through pointers and references) to unaligned class fields is also handled automatically.
char c; int a; }; #pragma pack PS1::PS1(): a(1) { // There appears to be no pointer, but there // is an unaligned access, possibly through “this.” printf(“In constructor.\n”); } PS1::~PS1() { a = 0; // Misaligned access, possibly though “this” printf(“In destructor.\n”); } int main() { #if defined(RECOVER) allow_unaligned_data_access(); #endif PS1 s; } UNALIGN #pragma unalign [1|2|4|8|16] typedef T1 T2; T1 and T2 have the same size and layout, but with specified alignment requirements.
Optimization Pragmas Following are the optimization pragmas supported by the HP aC++ compiler: OPT_LEVEL Pragma #pragma #pragma #pragma #pragma #pragma #pragma OPT_LEVEL OPT_LEVEL OPT_LEVEL OPT_LEVEL OPT_LEVEL OPT_LEVEL 0 1 2 3 4 INITIAL When used with a numeric argument, the OPT_LEVEL pragma sets the optimization level to 0, 1, 2, 3, or 4. The INITIAL argument causes the optimization level in effect at the start of the compilation, whether by default or specified on the command line, to be restored.
This pragma informs the compiler that the specified functions may enable floating-point trap handling. When the compiler is so informed, it will not perform loop invariant code motion (LICM) on floating-point operations in the functions named in the pragma. This pragma is required for proper code generation when floating-point traps are enabled. NOTE: This pragma is not supported in C++. It is deprecated for HP C and C++ C-mode. You should use#pragma STDC FENV_ACCESS ON instead.
IVDEP Pragma #pragma IVDEP For the associated loop, this pragma directs the compiler to ignore any apparent loop dependencies involving references to array-typed entities. NODEPCHK Pragma #pragma NODEPCHK For the associated loop, this pragma directs the compiler to ignore all loop dependencies (regardless of type) except for induction variables and some other scalar loop dependencies as determined by the compiler implementation. NO_RETURN Pragma #pragma NO_RETURN function1, [function2, . . .
#pragma assert non_zero(sizeof(a) == 12) "a is the wrong size" In this example, if the compiler determines that sizeof(a) is not 12, the following diagnostic message is output: "foo.c", line 10: error #2020: The assertion "(sizeof(a) == 12)" was not true. a is the wrong size Consider the following example that verifies both the size of a struct and the offset of one of its elements: #include
behavior is undefined. FREQUENTLY_CALLED pragma is independent of +Oprofile=use in that it overrides any dynamically obtained profile information. HDR_STOP Pragma #pragma HDR_STOP This pragma instructs the compiler to stop precompiling headers. HIDDEN Pragma #pragma hidden [symbol{,symbol}] The specified symbols, or all symbols (if no symbols are specified), are assigned the hidden export class. The hidden export class is similar to the protected export class.
POP Pragma #pragma POP The last pushed pragma is removed from the pragma stack and state is restored. The binding state reverts to the binding state prior to the last push. Note that this pragma can only be used with the blanket binding pragmas. Pragma (once) _Pragma ("once") The _Pragma ("once") operator is equivalent to #pragma once. This operator ensures that the source file is included only once during compilation.
STDC CX_LIMITED_RANGE Pragma #pragma STDC CX_LIMITED_RANGE ON #pragma STDC CX_LIMITED_RANGE OFF This pragma enables limited range mathematical behavior for specific blocks of code. Note that, this pragma applies to complex arithmetic only. Also see the ISO/IEC 9899 Standard. This pragma can occur outside an external declaration or within a compound statement.
STDC FENV_ACCESS Pragma #pragma STDC FENV_ACCESS ON #pragma STDC FENV_ACCESS OFF This pragma provides a means to inform the compiler when a program might access the floating-point environment to test flags or run under non-default modes. Use of the pragma allows certain optimizations that could subvert flag tests and mode changes such as global common sub expression elimination, code motion, and constant folding.
The atomic directive ensures that a specific memory location is updated atomically, rather than exposing it to the possibility of multiple, simultaneous writing threads. OMP BARRIER Pragma #pragma omp barrier The barrier pragma synchronizes all the threads in a team. When encountered, each thread waits until all the threads in the team have reached that point. The smallest statement to contain a barrier must be a block or a compound statement.
• at exit from single • at exit from for • at exit from sections NOTE: The directive is not implied if a nowait clause is present. OMP MASTER Pragma #pragma omp master structured-block The master pragma directs that the structured-block following it should be executed by the master thread (thread 0) of the team. Other threads in the team do not execute the associated block.
OMP PARALLEL SECTIONS Pragma #pragma omp parallel sections [clause1, clause2, ...] { [#pragma omp section ] structured-block [#pragma omp section structured-block ] . . .} where [clause1, clause2, ...] indicates that the clauses are optional. There can be zero or more clauses. The parallel sections pragma is a shortcut for specifying a parallel clause containing a single sections pragma.
where [clause1, clause2, ...] indicates that the clauses are optional. There can be zero or more clauses. clause may be one of the following: • if (scalar-expression)) • untied • default (shared | none) • private (list) • firstprivate (list) • shared (list) The TASK directive defines an explicit task. OMP TASKWAIT Pragma #pragma omp taskwait new-line The TASKWAIT directive specifies a wait on the completion of child tasks generated since the beginning of the current task.
When lastprivate clause is specified in a loop or section, the value of the lastprivate variable from either the sequentially last iteration of the associated loop, or the lexically last section directive is assigned to the variable’s original object. The lastprivate clause provides a superset of the functionality provided by the private clause. Variables specified in the list have private clause semantics described earlier.
ordered ordered The ordered clause must be present when ordered directives bind to the for construct. schedule schedule(kind[,chunksize]) The schedule clause specifies how iterations of the for loop are divided among threads of the team. The kind of schedule can be: static, dynamic, guided, or runtime. chunksize should be a loop invariant integer expression. num_threads num_threads(interger-expression) The num_threads clause allows a user to request a specific number of threads for a parallel construct.
1. 2. 3. The return value of a call to such a function points to a memory location or can be a null pointer. On return of such a call (before the return value is assigned to another variable in the caller), the memory location mentioned in 1. can be referenced only through the function return value; e.g., if the pointer value is saved into another global variable in the call, the function is not qualified for the malloc attribute.
Similar to the NO_RETURN pragma, this attribute asserts to the optimizer that this function never returns to the call site. This allows the optimizer to delete any code after the function call. A C++ function marked with this attribute may still throw an exception unless it has an empty throw list.
4 Preprocessing Directives HP aC++ has its own, internal, preprocessor which is similar to the HP C preprocessor described in the HP C/HP-UX Reference Manual. When you issue the aCC command, your source files are automatically preprocessed.
• A preprocessor directive is terminated by a newline character. • Preprocessor directives, as well as normal source lines, can be continued over several lines. End the lines that are to be continued with a backslash (\). • Some directives can take actual arguments or values. • Comments in the source file that are not passed through the preprocessor are replaced with a single white space character (ASCII character number decimal 32).
Examples #include #include "myheader.h" #ifdef MINE # define filename "file1.h" #else # define filename "file2.h" #endif #include filename The #include_next preprocessor directive is similar to the #include directive, but tells the preprocessor to continue the include-file search beyond the current directory, and include the subsequent instance found in the file-search path. Macro Replacement (#define, #undef) You can define C++ macros to substitute text in your source file.
#define identifier( [identifier-list] ) [replacement-list] The macro name is identifier. The formal parameters are provided by the identifier-list enclosed in parentheses. The open parenthesis ( ‘(’ ) must immediately follow the identifier with no intervening white space. If there is a space between the identifier and the parenthesis, the macro is defined as if it were the first form and the replacement-list begins with the ( character. The formal parameters to the macro are separated with commas.
Example 2 You can use the # and ## operators together: #include #define show_me(arg) int var##arg=arg;\ cout << "var" #arg " is " << var##arg << "\n"; int main() { show_me(1); } Preprocessing this example yields the following code for the main procedure: int main() { int var1=1; cout << "var" "1" " is " << var1 << "\n"; } After compiling the code with aCC and running the resulting executable file, you get the following results: var1 is 1 Spaces around the # and ## are optional.
#define FALSE 0 #define TRUE 1 The following macro is more complex. It has two parameters and produces an inline expression which is equal to the maximum of its two parameters: #define MAX(x,y) ((x) > (y) ? (x) : (y)) Parentheses surrounding each argument and the resulting expression ensure that the precedences of the arguments and the result interact properly with any other operators that might be used with the MAX macro. Using a macro definition for MAX has some advantages over a function definition.
int i1 = 3, i2 = 3; ; printf("Distance from macro : %d\n", distance1(i1,i2) ) printf("Distance from inline function : %d\n", distance2(i1,i2) ); } Predefined Macros In addition to __LINE__ and __FILE__, HP aC++ provides the following predefined macros. The list describes the complete set of predefined macros that produce special information. They cannot be undefined nor changed.
HP aC++ predefines the following predicates: • #assert system(unix) • #assert model(lp64) // when +DA2.0W is used • #assert model(ilp32) // default • #assert endian(big) Example: int main() { #assert dimensions(three) // Set predicate and token to true. #if #dimensions(two) #error "May not compile in 2 dimensions" #endif #if #dimensions(three) int x, y, z; #endif #unassert dimensions } // Set predicate and all tokens to false. Conditional Compilation (#if, #ifdef, ..
... #endif Using the defined Operator You can use the defined operator in the #if directive to use expressions that evaluate to 0 or 1 within a preprocessor line. This saves you from using nested preprocessing directives. The parentheses around the identifier are optional. Below is an example: #if defined (MAX) && ! defined (MIN) ...
Examples The following examples show valid combinations of conditional compilation directives: #ifdef SWITCH #else #endif // compiled if SWITCH is defined // compiled if SWITCH is undefined // end of if #if defined(THING) #endif // compiled if THING is defined // end of if #if A>47 #else #if A < 20 #else // compiled if A is greater than 47 #endif #endif // // // // // compiled if A is less than 20 compiled if A is greater than or equal to 20 and less than or equal to 47 end of if, A is less than 20
IOSTREAM Performance Improvement Pragma The -AA -D_HP_NONSTD_FAST_IOSTREAM Performance Improvement macro can be used to improve the -AA iostream performance. Syntax: #define _HP_NONSTD_FAST_IOSTREAM 1 (or) aCC options -D_HP_NONSTD_FAST_IOSTREAM This macro enables the following non-standard features: • Sets std::ios_base::sync_with_stdio(false), which disables the default synchronization with stdio • Sets std::cin.tie(0). which unties the cin from other streams.
Error Directive (#error) The #error directive causes a diagnostic message, along with any included token arguments, to be produced by HP aC++. Syntax error-directive ::= #error [preprocessor tokens] Example // This directive will produce the diagnostic // message "FLAG not defined!". #ifndef FLAG #error "FLAG not defined!" #endif // This directive will produce the diagnostic // message "TABLE_SIZE must be a multiple of 256!".
??=line 5 "myfile" When this line is compiled it becomes: #line 5 "myfile” Overview of the Preprocessor 131
5 Using HP aC++ Templates The following sections overview template processing and describe the instantiation coding methods available to you.
Explicit Instantiation You request explicit instantiation by using the explicit template instantiation syntax (as defined in the ANSI/ISO C++ International Standard) in your source file. You can request explicit instantiation of a particular template class or a particular template function. In addition, member functions and static data members of class templates may be explicitly instantiated.
// // // // class which results in implicit instantiation Function Template Following are examples of explicit and implicit instantiation syntax for a function template: template void sort(Array &); // // // // // declaration for the sort() function template template void sort(Array &v) {/* // // // // // ...
Why Use Compile-Time Instantiation Compile-time instantiation is the default. It is easy to use. Your code may compile faster when using compile-time instantiation. If your development environment uses a version control system that is sensitive to file modifications, you may want to use the current default, compile-time instantiation, to avoid major code rebuilds. NOTE: If you have used automatic instantiation with earlier versions of HP aC++ there may be some migration issues.
For example, when your archive library is linked with an application, library objects in the link may be different than those used when linking the library in a prior release. Following are two examples of building an archive library; one built with +inst_auto/+inst_close (the prior default), and the other built with the current (compile-time) default: Building an Archive Library with +inst_auto/+inst_close Suppose for lib.inst_auto.a, the linker chooses foo2.o to resolve symbol x, and foo3.
int top; }; Class template member functions and member data use the formal parameter type, T, and the formal parameter expression, size. When you declare an instance of the class Stack, you provide an actual type and a constant expression. The object created uses that type and value in place of T and size, respectively. For example, the following program uses the Stack class template to create a stack of 20 integers by providing the type int and the value 20 in the object declaration.
6 Standardizing Your Code HP aC++ largely conforms to the ISO/IEC 14882 Standard for the C++ Programming Language (the international standard for C++).
b=false; // Set it to false. } dynamic_cast Keyword The keyword dynamic_cast is used in expressions to check the safety of a type cast at runtime. It is the simplest and most useful form of runtime type identification. You can use it to cast safely within a class hierarchy based on the runtime type of objects that are polymorphic types (classes including at least one virtual function). At runtime, the expression being cast is checked to verify that it points to an instance of the type being cast to.
If you attempt a dynamic cast from a non-polymorphic type, you will also get a compile-time error. For example: class Base { // class details omitted }; class Derived : public Base { // class details omitted }; int main() { Base *p; Derived *q; Base b; p = &b; q = dynamic_cast (p); } The above generates a compile-time error: Dynamic down-casts and cross-casts must start from a polymorphic class (one that contains or inherits a virtual function); but class Base is not polymorphic.
class Base1 { // Not a polymorphic type. // additional class details omitted }; class Base2 { virtual void f(); // Make Base2 polymorphic. // additional class details // omitted }; void Base2::f() { // Define Base2 function. } class Derived : public virtual Base1, public virtual Base2 { // additional class details omitted }; int main() { Base1 *bp1; Base2 *bp2; Derived *dp; bp1 = new Derived; bp2 = new Derived; // dp = (Derived *) bp1; // Problem: compile time error // Can’t cast from virtual base.
explicit C(int); }; C::C(int) { // empty definition } int main() { C c(5); c = C(10); // c = 15; // c + 20; // // // // // Legal Legal Produces a compile time error: Message: Cannot assign ‘C’ with ‘int’.
mutable Keyword The mutable keyword is used in declarations of class members. It allows certain members of constant objects to be modified in spite of the const of the containing object. Usage Often some class members are part of the implementation of the object, not part of the actual information stored by the object. Although the information in the object needs to stay unmodified in a const object, the implementation members may need to change. These are declared mutable.
namespace and using Keywords Namespaces were introduced into C++ primarily as a mechanism to avoid naming conflicts between various libraries. The following example illustrates how this is achieved:Every namespace introduces a new scope. By default, names inside a namespace are hidden from enclosing scopes. Selection of a particular name can be achieved using the qualified-name syntax. Namespaces can be nested very much like classes. #include
namespace N { // An extension of the first part of namespace N char const* f(int); // Leave the implementation to another } // translation unit. int main() { printf(“Calling: %s.\n”, N::f()); // OK, declared and defined above printf(“Calling: %s.\n”, N::f(7)); // OK, declared above (defined elsewhere) printf(“Calling: %s.\n”, f(3.
Using namespace directives can be a powerful means to migrate code to libraries that use namespaces. Occasionally, however, they may silently make unwanted names visible. It is therefore often suggested not to use using-directives unless the alternatives are very inconvenient. #include namespace N { char const* f() { return “N::f()”; } char const* f(double) { return “N::f(double)”; } char const* g() { return “N::g()”; } } char const* g(double) { using N::f; return f(2.
// Define function from Base. } int main () { Base *p; // Code which does either // p = new Base; or // p = new Derived; // Note that this is NOT a good design for this // functionality Virtual functions would be better.
// be a polymorphic type. // additional class details omitted }; class Derived : public Base { // class details omitted }; void Base::f() { // Define function from Base. } int main () { Base *p; // code which does either // p = new Base; or // p = new Derived; if (dynamic_cast (p)) cout << “Derived (or class derived from Derived) Object\n”; else cout << “Base Object\n”; } volatile Keyword The volatile keyword is used in declarations.
wchar_t Keyword Wide (or multi-byte) characters can be declared with the data type wchar_t. It is an integral type that can represent all the codes of the largest character set among the supported locales defined in the localization library. This keyword was a typedef of the ANSI C standard. Usage This type was added to maintain ANSI C compatibility and to accomodate foreign (principally Oriental) character sets.
// Message: ‘C2’ is used as a type, but // has not been defined as a type. typename T::C2 *p; // Solution: the keyword typename flags // the qualified name T::C2 as a type. }; class C { // details omitted class C2 { //details omitted }; }; int main () { C1 c; } In a template, a name is not taken to be a type unless it is explicitly declared as one.
overloading was done for efficiency, it may be that for arrays the default operator is the most efficient. Example # include
Standard Exception Classes Classes are provided in the Standard C++ Library to report program errors. These classes are declared in the header. All of these classes inherit from a common base class named exception. The two classes logic_error and runtime_error inherit from exception and serve as base classes for more specific errors. These classes provide a common framework for the way errors are handled in a C++ program.
Exceptions Thrown by the Standard C++ Library The following exceptions are thrown by the Standard C++ Library: • operator new () and operator new [ ] throw a bad_alloc exception when they cannot obtain a block of storage. • A dynamic_cast expression throws a bad_cast exception when a cast to a reference type fails. • Operator typeid throws a bad_type exception when a pointer to a typeid expression is zero.
// of this class. cout << “Base Object\n”; cout << typeid(*p).name() << ‘\n’; // Standard requires // access to the name // of the type. } The standard requires the class type_info to be polymorphic. You cannot assign or copy instances of the class (the copy constructor and assignment operators are private).
Table 11 Unsupported Functionality (continued) Functionality Rogue Wave Rogue Wave Standard C++ Standard C++ Library Library 1.2.1 2.2.
7 Optimizing HP aC++ Programs HP C/HP aC++ provides options to the aCC command and pragmas to control optimization.
• Software pipelining. • Register reassociation. Level 2 can produce faster runtime code than level 1 if programs use loops extensively. Loop-oriented floating-point intensive applications may see run times reduced by 50%. Operating system and interactive applications that use the already optimized system libraries can achieve 30% to 50% additional improvement. Level 2 optimization produces faster programs than level 1 and compiles faster than level 3 optimization.
Enabling Only Conservative Optimizations You can enable only conservative optimizations at the second, third, or fourth optimization levels by using the +Ofltacc=strict +Ofenvaccess option, as follows: aCC +O2 +Ofltacc=strict +Ofenvaccess sourcefile.C or: aCC +O3 +Ofltacc=strict +Ofenvaccess sourcefile.C or: aCC +O4 +Ofltacc=strict +Ofenvaccess sourcefile.C This option disables all but the most conservative optimizations at each level.
When using profile-based optimization, please note the following: • Numerical applications that perform the same calculations independent of the input data will only see a small performance boost. • Profile-based optimization has the greatest impact on application performance when used with level 2 or greater optimizations.
Example 1 In the following example, the FLOW_DATA environment variable is used to override the flow.data file name. The profile data is stored instead in /users/profiles/prog.data. export FLOW_DATA=/users/profiles/prog.data aCC -c +Oprofile=collect sample.C aCC -o sample.exe +Oprofile=collect sample.o sample.exe < input.file1 aCC -o sample.exe +Oprofile=use +O3 sample.C Example 2 In this example, the +Oprofile=use:filename option is used to override the flow.
8 Exception Handling Exception handling provides a standard mechanism for coding responses to runtime errors or exceptions.
Exception Handling as Defined by the ANSI/ISO C++ International Standard The Standard C++ Library provides classes that C++ programs can use for reporting errors. These classes are defined in the header file and described in the ANSI/ISO C++ International Standard. • The class, exception, is the base class for object types thrown by the Standard C++ Library components and certain expressions. • The class, runtime_error, defines errors due to events beyond the scope of the program.
A::A() try : _member(fx()) { cout << _member << ‘\n’; } catch (runtime_error& r) { cout <
Note that conditional compilation may be necessary to accommodate both the user threads and the kernel threads interfaces, as in the above example. An alternative might be to compose a buffer with an ostrstream and output with one write. The following example could be used with the cfront compatiblelibstream: ostrstream ostr; ostr << “something” /*...*/ ; ostr << “ or another” /*...*/ << endl; cout.write(ostr.str(), ostr.pcount()); ostr.
Limitations In most cases, thread safety does not imply that the same object can be shared between threads. In particular, when objects have user visible state, it would not make sense to share them between threads. Consider the following: void f(ostream &out, int x, int y) { out << setw(3) << x << setw(10) << y; } This function would not be thread safe if called from multiple threads with the same object, since the width in the shared object could be changed at any time.
Exception Handling It is illegal to throw out of a thread. The following example illustrates that you cannot catch an object which has been thrown in a different thread. To do so will result in a runtime abort since HP aC++ finds no available catch handler and terminate is called. #include
void* foo(void*) { pA = new A(); B ob; pthread_cleanup_push(reinterpret_cast(thread_specific_destroy),pA); pthread_cleanup_pop(1); ob.~B(); // potential problem when the thread is canceled. pthread_exit(0); return 0; } int main() { //A oa; exit(0); //dtor for oa won’t be called if line above is uncommented. pthread_t thread_id; for (int i = 0; i < 3; i++) pthread_create(&thread_id, 0, &foo, 0); pthread_join(thread_id, 0); } NOTE: vector::clear does not free all of the memory.
bit process, the stack space for each thread is allocated from the heap. The heap defaults 1 gigabyte, and the default stack size is 8 megabytes. See the linker option-N for increasing data area size to 2 gigabytes. If the dynamic threads mechanism is disabled, requests for additional threads will result in no additional threads being created. Programs should not assume that a request will result in additional threads for all requests.
+O[no]openmp Command Line Option The +Oopenmp option is accepted at all optimization levels. The +Oopenmp option enables the recognition of OpenMP pragmas. Using the +Onoopenmp option will ignore all OpenMP directives silently. See Chapter 3: “Pragma Directives and Attributes” (page 96) for more information on OpenMP pragmas. _OPENMP Macro The _OPENMP macro name is defined by OpenMP compliant implementation as the decimal constant 200203.
OMP_DYNAMIC export OMP_DYNAMIC=value setenv OMP_DYNAMIC value The OMP_DYNAMIC environment variable enables or disables dynamic adjustment of the number of threads available for execution of parallel regions. The value must be either TRUE or FALSE. The default value is FALSE. If the value is set to FALSE, dynamic adjustment is disabled. If the value is set to TRUE, the number of threads that are used for executing parallel regions may be adjusted by the runtime environment to best utilize system resources.
omp_set_num_threads #include void omp_set_num_threads(int num_threads); The omp_set_num_threads function sets the number of threads to use for subsequent parallel regions. The value of the parameter num_threads must be positive. Its effect depends upon whether dynamic adjustment of the number of threads is enabled.
The omp_in_parallel function returns non-zero if it is called within the dynamic extent of a parallel region executing in parallel; otherwise, it returns 0. This function returns non-zero from within a region executing in parallel, including nested regions that are serialized. omp_set_dynamic #include void omp_set_dynamic(int dynamic_threads); The omp_set_dynamic function enables or disables dynamic adjustment of the number of threads available for execution of parallel regions.
This variable must only be accessed through these functions. All lock functions require an argument that has a pointer to omp_lock_t type for lock functions and omp_nest_lock_t for nestable lock functions. • omp_init_lock and omp_init_nest_lock • omp_destroy_lock and omp_destroy_nest_lock • omp_set_lock and omp_set_nest_lock • omp_unset_lock and omp_unset_nest_lock • omp_test_lock and omp_test_nest_lock omp_init_lock and omp_init_nest_lock #include
For a nestable lock, the omp_unset_nest_lock function decrements the nesting count, and releases the thread executing the function from ownership of the lock if the resulting count is zero. omp_test_lock and omp_test_nest_lock Functions #include int omp_test_lock(omp_lock_t *lock); int omp_test_nest_lock(omp_nest_lock_t *lock); These functions attempt to set a lock but do not block execution of the thread. The argument must point to an initialized lock variable.
9 Tools and Libraries This chapter discusses tools and libraries bundled with HP aC++. It discusses the following topics: • “HP Specific Features of lex and yacc” (page 175) • “Creating and Using Libraries” (page 175) • “HP aC++ File Locations” (page 186) HP Specific Features of lex and yacc lex and yacc are bundled with HP aC++.
• Advanced Shared Library Features • Standard HP-UX Libraries and Header Files • Allocation Policies for Containers For more information, see HP-UX Online Linker and Libraries User’s Guide. HP aC++ Libraries In addition to standard HP-UX system libraries, HP aC++ provides the following C++ libraries: • • Standards Based Libraries ◦ Standard C++ Library ◦ Tools.
The key is to use the right tool for each task. For a majority of programming tasks, object-oriented techniques is the preferred approach. Products such as Rogue Wave’s Tools.h++ Library, which encapsulate the Standard C++ Library with a familiar object-oriented interface, provide the power and advantages of object-orientation. Use Standard C++ Library components directly when you need flexibility or highly efficient code.
Smaller Source Code There are approximately 50 different algorithms and about a dozen major data structures. This separation reduces the source code size, and decreases the risk of similar activities with dissimilar interfaces. In the absense of this separation, each algorithm must be implemented in each data structure. This requires additional member functions apart from those in the present scheme.
The following program uses the times function object: // test.c int times; #include //user defined variable //multiplies can be used in int main() {} // end of test.c Compile this program using the following command: aCC -D__HPACC_USING_MULTIPLIES_IN_FUNCTIONAL test.c Depending on the existence of the conditional compilation flag, functional defines either times, or multiplies, not both.
Linking to C++ Libraries You can compile and link any C++ module to one or more libraries. HP aC++ automatically links the following libraries with a C++ executable. • /usr/lib/hpux##/libCsup.so (the HP aC++ runtime support library) • /usr/lib/hpux##/libstd_v2.so (standard C++ library: -AA) • /usr/lib/hpux##/libc.so (the HP-UX system library) • /usr/lib/hpux##/libdl.so (routines to manage shared libraries) • /usr/lib/hpux##/libunwind.so (routines to unwind exceptions) • /usr/lib/hpux##/libm.
Creating a Shared Library To create a shared library from one or more object files, use the -b option at link time. (The object files must have been compiled with +z or +Z.) The -b option creates a shared library rather than an executable file. NOTE: Use the aCC command to create a C++ shared library. This ensures that static constructors and destructors are executed at appropriate times. Example The following example links util.o and creates the shared library util.so. aCC -b -o util.so util.
Syntax -Wl,-a,{archive|shared|shared_archive|archive_shared|default} where, -Wl,-a,archive Selects archive libraries. If the archive library does not exist, the linker generates a warning message and does not create the output file. -Wl,-a,archive_shared If archive_shared is active, the archive form is preferred, but the shared form is allowed. -Wl,-a,shared Selects shared libraries. If shared libraries do not exist, the linker generates a warning message and does not create the output file.
Binding Times Because shared library routines and data are not actually contained in the a.out file, the dynamic loader must attach the routines and data to the program at run time. To accelerate program startup time, routines in a shared library are not bound until referenced. (Data items are always bound at program startup.
Adding New Versions to a Shared Library To rebuild a shared library with new versions of some of the object files, use the aCC command and the -b option with the old object files and the newly compiled object files. The new source files should use the HP_SHLIB_VERSION pragma. Refer to HP-UX Online Linker and Libraries User’s Guide for more information. Standard HP-UX Libraries and Header Files HP-UX includes Several libraries that provide system services.
For -AA Standard Library The following 4 defines can change the container initial allocation and growth ratio: For an arbitrary container type: # define _RWSTD_MINIMUM_NEW_CAPACITY size_t(32) # define _RWSTD_NEW_CAPACITY_RATIO float(1.618) For a string type: # define _RWSTD_MINIMUM_STRING_CAPACITY size_t(128) # define _RWSTD_STRING_CAPACITY_RATIO float(1.618) For more precise control of containers, the following explicit specialization can be used.
printf("%d\n", count); }int printMallocInfo(const char* title) { static long lastValue; struct mallinfo info; info = mallinfo(); printf("%s\n",title); printf("Memory allocation info:\n"); printf(" total space in arena = %d\n", info.arena); #ifdef DETAILS printf(" number of ordinary blocks = %d\n", info.ordblks); printf(" number of small blocks = %d\n", info.smblks); printf(" space in holding block headers = %d\n", info.hblkhd); printf(" number of holding blocks = %d\n", info.
HP aC++ Runtime Libraries and Header Files Following lists the HP aC++ runtime libraries and locations: • • Standard C++ Library — /usr/lib/hpux32/libstd.so - 32-bit shared version — /usr/lib/hpux32/libstd.a - 32-bit archive version — /usr/lib/hpux64/libstd.so - 64-bit shared version — /usr/lib/hpux64/libstd.a - 64-bit archive version HP aC++ Runtime Support Library — /usr/lib/hpux##/libCsup.so — /usr/lib/hpux##/libCsup11.so — ISO C++11 standard compliant — /usr/lib/hpux##/libstd.
10 Mixing C++ with Other Languages This chapter provides guidelines for linking HP aC++ modules with modules written in HP C and HP FORTRAN 90 on HP 9000 Series 700/800 systems.
It is the use of these features, as opposed to whether the class keyword is used rather than struct, that introduces incompatibilities with C structs. HP aC++ Calling HP C Calling between C and C++ is a normal operation, since C++ is for the most part a superset of C.
Although the string literal following the extern keyword in a linkage directive is implementation-dependent, all implementations must support C and C++ string literals. Refer to linkage specifications in The C++ Programming Language, Third Edition for more information. Differences in Argument Passing Conventions When your C++ code calls functions written in C, ensure that the called C functions do not use function prototypes that suppress argument widening.
/* by compiling the “calling_c.C” module must be */ /* linked to create an executable file. */ /****************************************************/ #include #include “string.h” char* get_name() { static char name[80]; printf(“Enter the name: “); scanf(“%s”,name); return name; } /****************************************************/ Running the Example Following is a sample run of the executable file that results when you link the object modules generated by compiling calling_c.C and get_name.
// C interface routine to initialize an // object by calling the constructor. void initialize_obj(obj_ptr& p) { p = new obj; } // C interface routine to destroy an // object by calling the destructor. void delete_obj(obj_ptr p) { delete p; } // C interface routine to display // manipulating the object.
aCC -oexecutable cfilename.o C++filename.o NOTE: During the linking phase, the aCC driver program performs several functions to support the C++ class mechanism. Linking programs that use classes with the C compiler driver cc leads to unpredictable results at run time.
int main( void ) { // declare a reference variable extern void pas_func( short & ); short x; ... pas_func( x ); // pas_func should accept ... // its parameters by reference } Using extern "C" Linkage To mix C++ modules with HP FORTRAN 90 modules, you must use extern "C" linkage to declare any C++ functions that are called from a non-C++ module and to declare the FORTRAN routines. Strings HP aC++ strings are not the same as HP FORTRAN 90 strings. In FORTRAN 90, the strings are not null terminated.
11 Distributing Your C++ Products Distribute your products in such a way that your customer does not need to use the HP aC++ compiler or driver. That is, only distribute executables and shared libraries. If you write code in HP aC++ and distribute any of the following C++ files to your customers, read the following sections for recommendations and legal requirements. • Shared libraries containing C++ code with the exception of the following libraries: ◦ /usr/lib/hpux##/libCsup.
NOTE: If you distribute either executable files or shared libraries as part of your product, do not ship these HP aC++ runtime libraries with your product in such a way that it results in overwriting a newer library version with an older, incompatible version. Ensure that an older library version is not installed over a newer one. Linking Your HP aC++ Libraries with Other Languages The C++ language requires that non-local static objects be initialized before any function or object is used.
Terms for Distribution of HP aC++ Files Permission to distribute the above mentioned HP aC++ runtime shared libraries is based on the following terms and conditions: • These HP aC++ components cannot be redistributed as part of a C++ compiler, linker, or interpreter product. • All copyright notices in the code must be retained. • The HP aC++ executable components can only be redistributed by HP aC++ customers.
12 Migrating from HP C++ (cfront) to HP aC++ This chapter discusses differences in syntax and functionality that you need to consider when migrating from HP C++ (cfront) to HP aC++.
Writing Code for both Compilers Use the __cplusplus macro (defined by the draft standard) to write code that can be compiled by both HP C++ and HP aC++. Example: #if __cplusplus >= 199707L // HP aC++ code #else // HP C++ code #endif // __cplusplus >= 199707L Explicit Loading and Unloading of Shared Libraries HP aC++ uses system calls rather than C++ function calls to explicitly load and unload shared libraries.
Table 12 New Command-Line Options (continued) Option Description Precompiled Header File Options Reduces compilation time and executable file size by precompiling common include (header) files. Template Options There are new options and new functionality for template processing. For more information about HP aC++ templates, see Chapter 5: “Using HP aC++ Templates” (page 132). Obsolete Command-Line Options Table 13 describes obsolete command-line options for HP aC++.
Table 13 Obsolete Command-Line Options (continued) Option Description -pts Splits template instantiations into separate object files. -ptS"list" Specifies file name extensions for template definition files. -ptv Provides verbose information about template processing. For HP aC++, use the +inst v option. Translator Mode Options +a0 Causes the translator to produce Classic C style declarations. +a1 Causes the translator to produce ANSI C style declarations.
Table 14 Changed Command-Line Options (continued) Option Description • P - patch tool, c++patch • r - Compile-time template processor, c++ptcomp -Wx,args The following values for x are related to translator mode and template subprocesses and are not supported in HP aC++.
calls made through a callback mechanism). If such calls do exist, and an exception is thrown, the unwinding can cause: • non-destruction of local objects (including compiler generated temporaries) • memory leaks when destructors are not executed • runtime errors when no catch clause is found Memory Allocation Failure and operator new In HP aC++ programs, when either operator new ( ) or operator new [ ] cannot obtain a block of storage, a bad_alloc exception results.
In HP aC++, a try block begins following the first call after the try keyword. This conforms to the standard that a legal exception cannot be thrown prior to the first call. The current handlers of try block are considered candidates to catch the exception. In HP C++ the try keyword defines the beginning of a try block.
int x = 1000; void my_unexpected_handler() { throw; } void foo() throw( int * ) { throw 1000; } int main() { set_unexpected( my_unexpected_handler ); try { foo(); } catch(...) { printf(“fail - not legal in aCC\n”); } return 0; } Unreachable catch Clauses Unreachable catch clauses are diagnosed by HP C++ but not by HP aC++. For example, class C { // ... }; class D : public C { // ... }; ... catch(C) { } catch(D) { // Unreachable since previous catch masks this one.
class D2 : public C { public: D2() {}; }; class E: public D1, public D2 { public: E() {}; }; int main() { E e; try { throw e; } catch(C) { printf(“caught } catch(D1) { printf(“caught } catch(D2) { printf(“caught } catch(E) { printf(“caught } try { throw & e; } catch(C*) { printf(“caught } catch(D1*) { printf(“caught } catch(D2*) { printf(“caught } catch(E*) { printf(“caught } return 0; } a C object\n”); a D1 object\n”); a D2 object\n”); an E object\n”); ptr to C object\n”); ptr to D1 object\n”); ptr
HP C++ (cfront) Compatibility Libraries HP aC++ provides the following library, whose functionality is part of the HP C++ (cfront) compiler. This library is not Standards based. • IOStream Library IOStream Library The shared version of this library is located at /usr/lib/hpux##/libstream.so. The archive version is at /usr/lib/hpux##/libstream.a. (## is 32 or 64 - provided as part of the HP-UX core system). Manpages The following manpages are located in the /opt/aCC/share/man/man3.Z directory: • IOS.
Standard Components Library Not Provided The Standard Components Library is not provided with the HP aC++ compiler for Integrity servers. HP recommends that you use the similar features of the Standard C++ Library in place of the Standard Components Library. HP C++ (cfront) Complex Library Not Supported The Complex library which is part of the cfront based HP C++ compiler product is not included with HP aC++.
Obsolete Preprocessor Options HP aC++ provides support for ANSI/ISO C++ International Standard preprocessing. Since the standard categorizes support of pre-ISO preprocessing as an anachronism, the ANSI preprocessing options of HP C++ (cfront) are not supported. For a list of obsolete preprocessor options, see Table 13: “Obsolete Command-Line Options” (page 200).
Overload Resolution Ambiguity of Subscripting Operator HP C++ and HP aC++ have different overload resolution models. When you migrate to HP aC++, you may see an overload resolution ambiguity for the subscripting operator. The following code illustrates the problem: struct String { char& operator[](unsigned); operator char*(); // ...
Example: aCC file1.o file2.o lib1.so lib2.so lib3.so In this scenario, cfront would initialize file2.o first, and then file1.o, while HP aC++ initializes file1.o and then file2.o. You must take this into account in your cfront code to avoid link problems with HP aC++. More Frequent Inlining of Inline Code HP C++ does not inline some functions even when you request for it. This happens when the function is too complex.
void f(const parm); const n = 3; main() The equivalent, valid HP aC++ code follows: void f(const int parm); const int n = 3; int main() The for Statement, New Scoping Rules In HP C++, variables declared in the initializer list are allowed after the for statement. In the ANSI/ISO C++ International Standard, variables declared in the initializer list are not allowed after the for statement.
CC: "DDB4325.C", line 3: error: T of type any redeclared as struct (1479) This code compiles without error with HP aC++. Base Template Class Reference Syntax Change In HP C++, you can reference a member of a base template class without qualifying the member. In HP aC++, when you reference a member of a base template class, you must qualify the member by adding this->. Adding this-> defers name resolution until instantiation. This allows the compiler to find members in template base classes.
Compiling the following code with HP C++ causes a warning. Compiling with HP aC++ generates an error stating that overload is used as a type, but has not been defined as a type. int f(int i); overload int f(float f); int main () { return 1; } // Remove the word overload. Dangling Comma in enum In HP C++, a comma following the last element in an enum list is ignored. In HP aC++, a comma following the last element in an enum list generates an error.
return 1; } Incorrect Syntax for Calls to operator new In HP C++, you can use incorrect syntax to call operator new. In HP aC++, an error is generated when incorrect syntax for operator new is used. To change this, add parentheses around the use of operator new. This code compiles correctly with both HP C++ and HP aC++. Example: Compiling the following code on HP C++ does not generate a warning or an error.
b.g(); // Error? } The ambiguity in the example code is whether b is declared as: • A function with one argument (named p) returning an object of type B. • An object of type B initialized with a temporary object of type A. HP C++ compiles this code successfully and assumes b is an object. Compiling the code with HP aC++ generates the following error: Error: File “objDeclaration.c”, Line 5 Left side of ‘.’ requires a class object; type found was a function ‘B (A)’.
initialization of a reference type generates an error and the program does not compile. To avoid this error, use a constant reference. Example: void f() { char c = 1; int & r = c; } Compiling the above code with HP C++ generates the following warning: C: “nonConstRef.C”, line 6: warning: initializer for non-const reference not an lvalue (anachronism) (235) Compiling the code with HP aC++ generates an error like the following: Error: File “nonConstRef.
Error: File “DDB4270.C”, Line 7 A pointer to member cannot be created from a parenthesized or unqualified name. To successfully compile the code, remove the parentheses from the last line. Example: class A { public: int i; static int (A::*p); }; int (A::*(A::p)) = &A::i; &qualified-id Required in Static Member Initialization List In HP C++, you can use an unqualified function name in a static member initialization list.
To successfully compile the code with either compiler, use one of the two alternatives shown below: void f(const int &); int main () { f(3); return 0; } // Use a constant reference. Or void f(int &); int i; int main () { i=3; f(i); return 0; } // Use an lvalue for reference initialization. Digraph White Space Separators HP C++ does not support alternative tokens (digraphs). In HP aC++, digraphs are supported and legal C++ syntax can be considered an error because of digraph substitution.
Common Template Migration Syntax Changes You must use the keyword typname to distinguish types in template code in HP aC++. Also, use the this-> notation to reference data members. The cfront Implicit Include Convention The preferred method for specifying template declarations and definitions in HP aC++ is to put declarations and definitions in the same file. In HP C++ (cfront), for any .h file that contains template declarations, there is a .c file that contains definitions for those templates.
13 Documentation feedback HP is committed to providing documentation that meets your needs. To help us improve the documentation, send any errors, suggestions, or comments to Documentation Feedback (docsfeedback@hp.com). Include the document title and part number, version number, or the URL when submitting your feedback.
A Diagnostic Messages The aC++ compiler can issue a large variety of diagnostics in response to unexpected situations or suspicious constructs. This appendix presents a summary of these diagnostics organized into the following sections: • “aC++ Message Catalog” (page 222) • “Frequently Encountered Messages” (page 222) aC++ Message Catalog The aC++ message catalog is located in the following directory: /opt/aCC/lib/nls/msg/C/ecc.
Glossary A aggressive optimization Optimization that changes the behavior of structured code. This is a superset of basic optimizations. anachronistic constructs Elements of the C++ language that are not supported in future releases. archive library A collection of object files grouped using the ar command. At link time, only object files with symbols are extracted from the library. argument declaration file A file containing the declaration of a class, struct, union, or enum types for templates.
E exception An exception is a runtime error condition. Exception handling is a C++ mechanism that allows the error detector to pass the error condition to the exception handler. An exception is raised by a throw statement within a try block and handled by a catch clause. The ANSI/ISO C++ International Standard defines only synchronous exceptions. explicit instantiation A method of instantiation that instantiates a template at the point of its use.
name mangling The process of generating unambiguous internal identifiers from C++ identifiers to resolve the scope of variables, overloaded operators, and overloaded functions. Also see name demangling. O object An instance of a class P parameterized type See template. position-independent code (PIC) Object code that contains no absolute addresses. All addresses are relative to the program counter. Position-independent code is used to create shared libraries.
translation unit The standard term for a compilation unit. It refers to a single source file submitted to the compiler along with all files included by the compilation of that single source file. A translation unit normally results in a single object file. It is also a variable name explicitly declared static has the scope of its translation unit and can be used as a name for other objects, functions, and so on in other translation units in the same application.
Index Symbols # operator, 122 ## operator, 122 .
+tru64, 86 +ub, 70 +uc, 70 +unum, 35 +w, 39 +w64bit, 71 +Wargs, 39 +Wcontext_limit, 39 +We, 40 +Weargs, 40 +wendian, 71 +wlint, 40 +wlock, 68 +Wmacro, 40 +wn, 39 +wperfadvice, 40 +wsecurity, 41, 93 +Wv, 40 +Wwargs, 40 -.
H level 2, 156 level 3, 157 level 4, 157 pragmas, 160 profile-based, 158 HP Code Advisor, 23 HP WDB, 23 I #include, 120 instantiation, 132 command-line, 134 compile-time, 134 explicit, 133 K keywords, 138 L #line, 128 languages, 188 lex, 175 libraries, 175 containers, 184 HP aC++ Run-time Support Library, 179 IOStream, 179 shared libraries, 180 Standard Components Library, 179 standard HP-UX libraries, 184 Tools.
STDC CX_LIMITED_RANGE, 109 STDC FENV_ACCESS, 110 STDC FLOAT_CONST_DECIMAL64, 109 STDC FP_CONTRACT, 109 UNALIGN, 102 UNROLL_FACTOR, 110 VERSION_ID, 98 predefined macros, 125 __cplusplus, 125 __DATE__, 125 __FILE__, 125 __HP_aCC, 125 __hpux, 125 __ia64__, 125 __LINE__, 125 __LP64__, 125 __STDCPP__, 125 __TIME__, 125 __unix, 125 _ILP32, 125 _LP64, 125 preprocessor, 119 S standard exception classes, 152 T threads, 163 timing functions, 174 TMPDIR, 29 trigraph sequences, 130 U #undefine, 121 W #warning, 130