HP C/aC++ for PA-RISC Software manual Creating a Shared Library, Using a Shared Library

Page 181

Creating a Shared Library

To create a shared library from one or more object files, use the -boption at link time. (The object files must have been compiled with +z or +Z.) The -boption 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.o

Using a Shared Library

To use a shared library, include the name of the library in the aCC command line or use the-loption.

The linker links the shared library to the executable file it creates. Once you create an executable file that uses a shared library, do not move the shared library as the dynamic loader (dld.so) cannnot find it.

NOTE: Use the aCC command to link any program that uses a C++ shared library. This ensures that static constructors and destructors in the shared library are executed at appropriate times.

Example

The following example compiles prog.C, links it with the shared library util.so, and creates the executable file a.out.

aCC prog.C util.so

Example of Creating and Using a Shared Library

The following command compiles the two files, Strings.C and Arrays.C, and creates the two object files, Strings.o and Arrays.o. These object files contain position-independent code (PIC):

aCC -c +z Strings.C Arrays.C

The following command builds the shared library, libshape.so, from the object files Strings.oand Arrays.o:

aCC -b -o libshape.so Strings.o Arrays.o

The following command compiles a program, draw_shapes.C, that uses the shared library, libshape.so:

aCC draw_shapes.C libshape.so

Linking Archive or Shared Libraries

When an archive and shared version of a particular library reside in the same directory, the linker links in the shared version by default. You can override this behavior with the -alinker option.

NOTE: Use the +A option when using only archive libraries to create a completely archived executable.

The -aoption identifies the library type for the linker. The -aoption is positional and applies to all subsequent libraries specified with the -loption until the end of the command line or until the next -aoption is encountered. Pass the -aoption to the linker with the -Wx,argsoption.

Creating and Using Libraries 181

Image 181
Contents HP aC++/HP C A.06.28 Programmers Guide Page Contents +FP Contents Contents Contents Initialization and Termination Pragmas Pragma Directives and AttributesCopyright Notice and Identification Pragmas Data Alignment PragmasContents Preprocessing Directives 119 Standardizing Your Code 138 Using HP aC++ Templates 132Exception Handling 161 Optimizing HP aC++ Programs 156170 Tools and Libraries 175Mixing C++ with Other Languages 188 Migrating from HP C++ cfront to HP aC++ 198 Distributing Your C++ Products 195Strings 194 Arrays Files in Fortran Glossary 223 Index 227 Documentation feedback 221 Diagnostic Messages 222HP secure development lifecycle Intended Audience About This DocumentWhat’s in This Document This document uses the following conventions Typographical ConventionsRelated Documents Publishing HistoryHP-UX Release Name and Release Identifier HP-UX 11i ReleasesFollowing is a list of documents available with this release HP Encourages Your CommentsComponents of the Compilation System Getting Started with HP aC++C89 C99 ecom Ctcom Other HP aC++ executable files areCompiling a Simple Program Using the aCC CommandExecuting the Program Debugging ProgramsExamples of the aCC Command Compiler Command Syntax and Environmental VariablesAssembly Language Source Files .s Files Files on the aCC Command Line++ Source File .C file Preprocessed Source Files .i FilesEnvironment Variables Configuration Files .conf FilesObject Files .o Files Library Files .a and .so FilesACCMAXERR Environment Variable ACCFULLPATHNAMES Environment VariableCxxopts Environment Variable Cclibdir Environment VariableACC -L/mnt/proj/lib file.o ACC file.o Ccrootdir Environment VariableCxxmapfile Environment Variable Floating InstallationTmpdir Environment Variable Export CCROOTDIR=/mnt/CXX2.1HP aC++ Setting up Floating InstallationCommand-Line Options ACC -c sub.C prog.C Options to Control Code GenerationACC +DO11.22 +O3 app.C ILP32 Data Model and LP64 Data ModelCompiling in Networked Environments Using +DS to Specify Instruction SchedulingACC -S prog.C Data Alignment and StorageSize and Alignment of HP Compiler Data Types Fshort-enums Debugging Options+expandtypesindiag ACC +u1 app.CDifferences Between -g, -g0, and -g1 Options When to use -g, -g0, and -g1G1 Algorithm +macrodebug+pathtrace +noobjdebug+pathtrace=kind LocalNone Error Handling+pathtrace=globallocal ACC +p file.C+Wargs +wn+Wcontextlimit +We +wperfadvice+Weargs +WvExtensions to the Language Exception Handling+wsecurity +noehFloating-Point Processing Options +Onofenvaccess+Onocxlimitedrange Fpevaldec FpevalNofpwidetypes +decfp+Onolibmerrno +FPmode+Oprefetchlatency +OnopreservedfpregsHeader File Options ACC -I include file.C Idirs -I- -Idirs +help Online Help Option+inlinelevel num Inlining OptionsDynamic Library OptionsExec LnameMinshared Linker Options+nostl +Onolibcalls=Usymbol Usymbol+Onodynopt +OnodynoptNative Language Support Option Options for Naming the Output File+ild +ildrelinkCode Optimizing Options Handling Null Pointers OptionsBasic Optimization Level Options ACC -z file.C+O1 +O0+O2 +O3+O4 Additional Optimization Options for Finer ControlACC +O3 prog.C +O4+nonrv Ipo+Onofailsafe +Onoaggressive Advanced +Ooptimization Options+Onolimit +Onoptrstoglobals=list+Onodatalayout +Onocrossregionaddressing+Onodataprefetch +Onofltacc+Onoinitcheck +Ofrequentlycalled+Olit +Onoinline+Ointegeroverflow +Onolooptransform +Olevel+Onoloopunroll +Onoopenmp+Onoparminit +opts+Onoparmsoverlap +Onoprocelim+Onosignedpointers +Orarelycalled+Oshortdata Profile-Based Optimization Options +Otypesafety+Onostoreordering +OunrollfactorInformation Embedding Options Parallel Processing OptionsDisplaying Optimization Information Annotate=structsRequired if -DPOSIXCSOURCEis used Option Matrix for -mt+tls=staticdynamic +Onoautopar+wlock Performance OptionsFast +Ofast+Onotlscallschangetp +Ofaster+nosrcpos +DSmodel+sb Porting Options+ub +uc+wdriver +w64bit+wendian This warning can be suppressed by adding an extra castDname Preprocessor OptionsRedirecting Output From This Option +Maked Maked+maked ExamplesUname Profiling Code Options+profilebucketsize +check Runtime Checking Options+check=all +check=noneCompiling with +check=boundspointer +check=boundsarray +check=boundspointerCheck off by any number out-of-bounds access Check off by one out-of-bounds access+check=lock +check=globals+check=malloc +check=thread +check=stackframevariablesnone+check=uninit +check=truncateexplicitimplicitCh = intval & 0xff +check=truncateexplicit +check=truncateimplicitAarm Standards Related OptionsAarm AC99 AC89Ag++ Agcc+legacycpp AOa and -AOe+legacyv5 +stl=rwnone +std=c89c99c++98c++11gccg++gnuWc,-ansiforscope,onoff +tru64Wc,-koeniglookup,onoff +tru64Tx,name Subprocesses of the CompilerMore Examples of -t Tx,nameWx,args Bdefault Symbol Binding OptionsBextern Passing Options to the Linker with -WBhiddendef BhiddenBprotected BprotecteddataTemplate Options +instincludesuffixes Trigraph Processing Suppression OptionVerbose Compile and Link Information Process Compiler 94/u 65/s 35/r 37/u 76/s 02/r ACC -V app.C Concatenating OptionsACC myfile.C -v -g1 ACC myfile.C -vg1 ACC -vg1 myfile.C Initialization and Termination Pragmas Pragma Directives and AttributesCopyright Notice and Identification Pragmas #pragma Versionid string Data Alignment Pragmas#pragma Versionid Software Product, Version 12345.A.01.05 #pragma align NData Alignment Pragmas Template Example Basic ExampleHandling Unaligned Data Implicit Access to Unaligned DataInteraction between pack and unalign pragmas is as follows #pragma unalign Typedef T1 T2Optlevel Pragma Optimization PragmasOptimize Pragma Floattrapson PragmaNoinline Pragma Other Pragmas Diagnostic PragmasBinding Pragma Defaultbinding PragmaEstimatedfrequency Pragma Extern PragmaHidden Pragma Hdrstop PragmaHpdefinedexternal Pragma Hpdefinedinternal PragmaPragma once POP PragmaProtected Pragma Ptrsstronglytyped PragmaStdc Cxlimitedrange Pragma #pragma Stdc FLOATCONSTDECIMAL64 on OFF DefaultStdc FLOATCONSTDECIMAL64 Pragma Stdc Fpcontract PragmaUnrollfactor Pragma Stdc Fenvaccess PragmaOMP Atomic Pragma OMP Critical Pragma OMP Barrier PragmaOMP for Pragma OMP Flush PragmaOMP Ordered Pragma OMP Master PragmaOMP Parallel Pragma OMP Parallel for PragmaOMP Sections Pragma OMP Parallel Sections PragmaOMP Single Pragma OMP Task PragmaOpenMP Clauses Copyprivate DefaultShared CopyinAttributes Attribute noreturn Attribute nonexposingAttribute nonexposing Attribute noreturnAttribute visibility Attribute formatAttribute warnunusedresult Overview of the Preprocessor Preprocessing DirectivesSyntax Usage GuidelinesSyntax Source File Inclusion #include, #includenextDescription Assertions #assert, #unassert#define mac very very long\ Replacement string Macro Replacement #define, #undefExamples Macros with ParametersConcatenating Tokens with the ## Operator Specifying String Literals with the # OperatorExample Following illustrates the ## operatorOther Macros Using Macros to Define ConstantsVar1 is #define Arraysize 1000float xARRAYSIZEUsing Constants and Inline Functions Instead of Macros Predefined Macros Assertions #assert, #unassertHP aC++ predefines the following predicates Conditional Compilation #if, #ifdef, .. #endifCode that compiles if the expression evaluates to zero Using the #if Directive Using the defined OperatorUsing the #ifdef and #ifndef Directives Using the #else DirectiveExample Line Control #line#line 5 myfile Iostream Performance Improvement Pragma This macro enables the following non-standard featuresPragma Directive #pragma and Pragma Operator See page 96 for more information on pragmasTrigraph Sequences Error Directive #errorExamples Line below contains the trigraph sequence ??=??=line 5 myfile When this line is compiled it becomesInvoking Compile-Time Instantiation Using HP aC++ TemplatesScope and Precedence Template ProcessingUsage Explicit InstantiationPerformance Template class TablecharCompile-Time Instantiation Command-Line Option InstantiationFunction Template ACC -c +instcompiletime a.C ACC -c a.CPossible Duplicate Symbols in Shared Libraries Why Use Compile-Time InstantiationPossible Duplicate Symbols in Archive Libraries ScopeClass Templates ++ Template TutorialBuilding an Archive Library with +instauto/+instclose Building an Archive Library with Compile-time InstantiationFunction Templates HP aC++ Keywords Standardizing Your CodeBool Keyword HP aC++ KeywordsDynamiccast Keyword Compile time error message isAbove generates a compile-time error Explicit Keyword Classic example of this problem is an array class Mutable Keyword Connections Across Translation Units Namespace and using KeywordsUsing Nx // Where N is a namespace, x is a name in N Using- declarations and using- directivesAn Auxiliary Translation Unit IntPage Class Base Virtual void f Must have a virtual function to Volatile Keyword Template Keyword Wchart KeywordTypename Keyword Use it as the name of the template C below Overloading new and delete for ArraysDeclare a class as a member of the class template C2 below Example Standard Exception Classes RangeerrorInvalidargument Typeinfo Class Exceptions Thrown by the Standard C++ LibraryFollowing exceptions are thrown by the Standard C++ Library Int before const typeinfo& const Unsupported FunctionalityMemfun1reft Memfunreft Iostream Optimizing HP aC++ Programs Setting Basic Optimization LevelsRequesting Optimization Level 1 OptimizationLevel 3 Optimization Additional Options for Finer ControlLevel 4 Optimization Enabling Aggressive OptimizationsProfile-Based Optimization Removing Compilation Time Limits When OptimizingEnabling Only Conservative Optimizations Limiting the Size of Optimized CodeCollecting Data for Profiling InstrumentationMaintaining Profile Data Files Sample.exe input.file1 Sample.exe input.file2Performing Profile-Based Optimization Pragmas That Control OptimizationACC -o sample.exe +Oprofile=use +O3 sample.C See Optimization Pragmas page 103 for more informationException Handling in C++ Exception HandlingFunction Try Block Examples Basic Exception Handling ExampleUsing Locks Using ThreadsDebugging Exception Handling Performance Considerations Rogue Wave Standard C++ LibraryRogue Wave Standard C++ Library Required Command-line OptionsRogue Wave Standard C++ Library 1.2.1 and Tools.h++ LpthreadThis option applies only to kernel threadsUsing -DHPACCTHREADSAFERBTREE Using -DTHREADSAFE with the cfront Compatible libstreamLimitations Cout endlException Handling Pthreads Posix ThreadsACC -mt prog.c Function Scoping Parallel Programming Using OpenMPOpenMP Implementation OpenMP Library OpenMP Header FileOpenMP APIs are defined in the library libomp Environment Variables in OpenMP +Onoopenmp Command Line OptionOpenmp Macro Where, kind is either of of static, dynamic, or guidedExecution Environment Functions Runtime Library Functions in OpenMPExport OMPDYNAMIC=value Setenv Ompdynamic value Export OMPNESTED=value Setenv Ompnested valueOmpgetnumthreads OmpsetnumthreadsOmpgetmaxthreads OmpgetthreadnumOmpsetdynamic Lock FunctionsOmpgetdynamic OmpsetnestedOmpdestroylock and ompdestroynestlock Ompinitlock and ompinitnestlockOmpsetlock and ompsetnestlock Ompunsetlock and ompunsetnestlockOmptestlock and omptestnestlock Functions Timing FunctionsOmpgetwtime OmpgetwtickCreating and Using Libraries HP Specific Features of lex and yaccTools and Libraries Locale directive for lexHP aC++ Libraries Introduction to Using the Standard C++ LibraryStandard C++ Library IntroductionNon-Object-Oriented Design of the Standard C++ Library Differences between Standard C++ Library and Other LibrariesIncompatibilities Between the Library and the Standard Standard C++ Library ReferenceTools.h++ Library ACC -DHPACCUSINGMULTIPLIESINFUNCTIONAL test.cHP aC++ Runtime Support Library IOStream LibraryLinking to C++ Libraries Creating and Using Shared LibrariesLinking with Shared or Archive Libraries Specifying Other LibrariesExample of Creating and Using a Shared Library Using a Shared LibraryCreating a Shared Library Linking Archive or Shared LibrariesForcing the Export of Symbols in main Advanced Shared Library FeaturesUpdating a Shared Library Side Effects of C++ Shared Libraries Binding TimesRoutines and Options to Manage C++ Shared Libraries Linker Options to Manage Shared LibrariesAllocation Policies for Containers Standard HP-UX Libraries and Header FilesFor a string type For -AA Standard LibraryHP aC++ Executable Files HP aC++ File LocationsUsr/lib/hpux##/libCsup.so HP aC++ Runtime Libraries and Header FilesUsr/lib/hpux##/libCsup11.so ISO C++11 standard compliant Calling Other Languages Mixing C++ with Other LanguagesData Compatibility between C and C++ HP aC++ Calling HP C Using the extern C Linkage SpecificationSyntax of extern C Examples of extern CMain Function Differences in Argument Passing ConventionsExamples HP aC++ Calling HP C Running the Example HP C Calling HP aC++Enter the nameJoann Joann has a balance Compiling and Running the Sample Programs To compile the example, run the following commandsCalling HP Fortran 90 from HP aC++ Using Reference Variables to Pass ArgumentsFunction Naming Conventions Example of Reference Variables as ArgumentsStrings Using extern C LinkageArrays Files in FortranApplications that use HP aC++ Shared Libraries Distributing Your C++ ProductsLinking Your HP aC++ Libraries with Other Languages Installing your ApplicationHP aC++ Files You May Distribute Terms for Distribution of HP aC++ Files General Guidelines for Migration Migrating from HP C++ cfront to HP aC++Getting Started with Migration CC +p cfrontfile.CNew Command-Line Options Command-Line DifferencesWriting Code for both Compilers Explicit Loading and Unloading of Shared LibrariesDescribes obsolete command-line options for HP aC++ Obsolete Command-Line OptionsPtv Changed Command-Line OptionsMigration Considerations when Using Exception Handling Migration Considerations when DebuggingException Handling is the Default See Debugging Options page 35 for complete informationMemory Allocation Failure and operator new Possible Differences when Exiting a Signal HandlerCalling unexpected Differences in setjmp/longjmp BehaviorThrowing an Object having an Ambiguous Base Class Unreachable catch ClausesStandards Based Libraries Migration Considerations when Using LibrariesFstream3C++ iostream and streambuf specialized to files HP C++ cfront Compatibility LibrariesManip3C++ iostream manipulators Man 3s filebufHP C++ cfront Complex Library Not Supported Migration Considerations Related to PreprocessingHP C++ cfront Task Library Not Supported Replace #include with complexObsolete Preprocessor Options Migration Considerations Related to StandardizationChanges in C++ Semantics Implicit Typing of Character String LiteralsExecution Order of Static Constructors in Shared Libraries Overload Resolution Ambiguity of Subscripting OperatorMore Frequent Inlining of Inline Code Changes in C++ SyntaxExplicit int Declaration Struct as Template Type Parameter is Permitted For Statement, New Scoping RulesEquivalent, valid HP aC++ code follows WC,-ansiforscope,onBase Template Class Reference Syntax Change This code compiles without error with HP aC++Tokens after #endif Overload not a KeywordStatic Member Definition Required Dangling Comma in enumDeclaring friend Classes Incorrect Syntax for Calls to operator new Using in Class DefinitionsDuplicate Formal Argument Names Ambiguous Function or Object DeclarationReference Initialization Overloaded Operations ++On HP aC++, the following error is generated Using operator new to Allocate ArraysCompiling this code HP aC++ generates the following error Parentheses in Static Member Initialization ListNon-constant Reference Initialization Qualified-id Required in Static Member Initialization ListVerbose Template Processing Information Migration Considerations when Using TemplatesDigraph White Space Separators CA aCommon Template Migration Syntax Changes Converting Directed Mode to Explicit InstantiationCfront Implicit Include Convention Documentation feedback AC++ Message Catalog Diagnostic MessagesFrequently Encountered Messages Aggressive GlossaryInternational Standard defines only synchronous exceptions See template Glossary Index SymbolsCrootdir FLOATTRAPSON, 103 FREQUENTLYCALLED, 106 HDRSTOP, 107 Hidden Index
Related manuals
Manual 15 pages 49.53 Kb