HP UX Linker and Libraries User Manual

HP-UX Linker and Libraries User's Guide

Version (For PA32 and PA64 Systems) B.11.72 Version (For Integrity Systems) B.12.57
HP Part Number: B2355-91150 Published: October 2012 Edition: 2
© Copyright 2011 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. The only warranties for HP products and services are set forth in the express warranty statements accompanying such products and services. Nothing herein should be construed as constituting an additional warranty. HP shall not be liable for technical or editorial errors or omissions contained herein. UNIX is a registered trademark of The Open Group.
Itanium® is a trademark of Intel Corporation in the U.S. and other countries.

Contents

About This Document...................................................................................13
Intended Audience..................................................................................................................13
Document conventions and symbols..........................................................................................13
Related Information.................................................................................................................13
HP Encourages Your Comments................................................................................................14
Document Organization..........................................................................................................14
1 Compiling and Linking Programs on HP-UX..................................................16
Compiling Programs on HP-UX: An Example..............................................................................16
Overview..........................................................................................................................16
Looking Inside a Compiler...................................................................................................18
What is an Object File?.................................................................................................18
Local Definitions.......................................................................................................19
Global Definitions....................................................................................................19
External References...................................................................................................19
Compiler-Linker Interaction..................................................................................................19
Linking Programs on HP-UX......................................................................................................21
The crt0.o Startup File........................................................................................................21
The Program's Entry Point...............................................................................................22
The a.out File....................................................................................................................22
Magic Numbers (PA-RISC ONLY).........................................................................................22
File Permissions..................................................................................................................23
Linking with Libraries...............................................................................................................23
Library Naming Conventions...............................................................................................24
Default Libraries.................................................................................................................24
The Default Library Search Path.......................................................................................24
Link Order........................................................................................................................24
Running the Program...............................................................................................................25
Loading Programs: exec......................................................................................................25
Binding Routines to a Program.............................................................................................25
Deferred Binding is the Default............................................................................................25
Linker Thread-Safe Features......................................................................................................26
Shared library loading and unloading in multi-threaded applications.......................................26
2 Determining How to Link Programs or Libraries (Linker Tasks)..........................27
Using the Compiler to Link.......................................................................................................28
Changing the Default Library Search Path with -Wl, -L.............................................................28
Example Using -Wl, -L....................................................................................................28
Getting Verbose Output with -v............................................................................................29
Passing Linker Options from the Compiler Command with -Wl..................................................29
Example Using -Wl........................................................................................................29
Renaming the Output File with -o..........................................................................................29
Specifying Libraries with -l...................................................................................................29
Linking with the crt0.o Startup File in 32-bit mode (PA-RISC)................................................30
Suppressing the Link-Edit Phase with -c..................................................................................30
Using Linker Commands..........................................................................................................30
Linking with the crt0.o Startup File........................................................................................30
Changing the Default Library Search Path with -L, LPATH, and $ORIGIN....................................30
Overriding the Default Linker Search Path with LPATH.........................................................30
Augmenting the Default Linker Search Path with -L..............................................................31
Augmenting the Default Linker Search Path with +origin......................................................31
Using $ORIGIN.................................................................................................................31
Contents 3
Changing the Default Shared Library Binding with -B..............................................................32
Example Using -B immediate..........................................................................................32
Nonfatal Shared Library Binding with -B nonfatal..............................................................32
Restricted Shared Library Binding with -B restricted.............................................................32
Direct Shared Library Binding with -B direct......................................................................33
Shared Library Binding with -B group...............................................................................33
Lazydirect Shared Library Binding with -B lazydirect...........................................................33
Shared Library Binding with -B nodelete...........................................................................33
-B nodirect....................................................................................................................33
Improving Shared Library Performance with -B symbolic...........................................................34
Example Using -B symbolic.............................................................................................34
Comparing -B symbolic with -h and +e.............................................................................34
Case 1: Building a Shared Library with -B symbolic.......................................................34
Case 2: Building a Shared Library with -h or +e...........................................................35
Choosing Archive or Shared Libraries with -a.........................................................................36
Option Settings to -a......................................................................................................36
Example Using -a ....................................................................................................36
Linking Shared Libraries with -dynamic..................................................................................36
Linking Archived Libraries with -noshared..............................................................................37
Exporting Symbols with +e..................................................................................................37
Example Using +e.........................................................................................................37
When to use -h versus +e...............................................................................................37
Emitting debug information in a separate file.........................................................................38
Exporting Symbols with +ee................................................................................................38
Exporting Symbols from main with -E....................................................................................38
Hiding Symbols from Export with +hideallsymbols..................................................................39
Hiding Symbols with -h.......................................................................................................39
Example Using -h..........................................................................................................39
Tips on Using -h............................................................................................................39
Hiding and Exporting Symbols When Building a Shared Library.........................................40
Hiding Symbols when Combining .o Files with the -r Option...............................................40
Hiding and Exporting Symbols when Creating an a.out File................................................40
Not Recording Link Time Paths with +nodefaultrapth...............................................................41
Moving Libraries after Linking with +b..................................................................................41
Specifying a Path List with +b..........................................................................................41
Concatenating Search Paths Specified by Multiple +b path_list on PA64 and Integrity
Systems........................................................................................................................42
The Path List..................................................................................................................42
Moving Libraries After Linking with +s and SHLIB_PATH..........................................................43
Specifying a Path List with +s and SHLIB_PATH..................................................................43
For more information: ...............................................................................................43
Ignoring Dynamic Path Environment Variables with +noenvvar.................................................43
Controlling Archive Library Loading with +[no]forceload.........................................................44
Passing Linker Options in a file with -c..................................................................................44
Passing Linker Options with LDOPTS.....................................................................................44
Specifying Libraries with -l and -l:.........................................................................................45
Specifying Libraries (-l)...................................................................................................45
Using the -l: option........................................................................................................45
Example Using -l:..........................................................................................................45
Flagging Unsatisfied Symbols with +[no]allowunsats...............................................................45
Stripping Symbol Table Information from the Output File with -s and -x......................................46
Controlling Output from the Unwind Table with +strip unwind..................................................46
Using the IPF Linker with +compat or +std.............................................................................46
Using the Linker with +compat for Compatibility Mode.......................................................46
Using the Linker with +std for Standard Mode...................................................................47
4 Contents
Linking in PA-64 Mode with +std..........................................................................................48
Linking in PA-32 Mode with +compat...................................................................................48
Changing Mapfiles with -k and +nodefaultmap......................................................................48
Selecting Verbose Output with +vtype...................................................................................48
Turning on the linkage table protection with +protect..............................................................50
Creating read-only text segment in MPAS executable..............................................................50
Allocating Storage for Uninitialized Data with +nobss.............................................................50
Initializing Floating Point Environment with +FP .....................................................................50
Allocating Storage for Hidden Common Symbols with +alloc_hidden_commons.........................51
Turn Off Linker Warnings with -w.........................................................................................52
Preserving Compiler Generated Relocation Sections with -emit_relocs........................................52
3 Linker Tools for Itanium-Based Systems.........................................................53
Changing a Program's Attributes with chatr(1)............................................................................53
Viewing Symbols in an Object file with nm(1).............................................................................56
Viewing the Contents of an Object File with elfdump(1)................................................................58
Viewing Library Dependencies with ldd(1)..................................................................................60
Listing Dynamic Libraries with pldd(1)........................................................................................61
Printing a Stack Trace with pstack(1)..........................................................................................62
Viewing the Size of Object File Elements with size(1)....................................................................65
Reducing Storage Space with strip(1).........................................................................................65
Improving Program Start-up with fastbind(1)................................................................................66
Finding Object Library Ordering Relationships with lorder(1).........................................................67
Tracing Inter-Module Procedure Calls with ltrace(1)......................................................................67
4 Linker Tools for PA-RISC Systems.................................................................69
Changing a Program's Attributes with chatr(1)............................................................................69
Using chatr for 32-bit Program Attributes...............................................................................69
Using chatr for 64-bit Program Attributes...............................................................................70
Viewing Symbols in an Object file with nm(1).............................................................................71
Viewing the Contents of an Object File with elfdump(1)................................................................72
Viewing library dependencies with ldd(1)...................................................................................74
Viewing the Size of Object File Elements with size(1)....................................................................75
Reducing Storage Space with strip(1).........................................................................................76
Improving Program Start-up with fastbind(1)................................................................................76
Finding Object Library Ordering Relationships with lorder(1).........................................................77
5 Linker Toolset Differences Between PA-RISC and Itanium-Based Systems............79
Linker Toolset Compatibility with De Facto Industry Standards.......................................................79
ELF Object File Format .......................................................................................................79
PA-RISC Changes in Hardware Compatibility.............................................................................79
PA-RISC 2.0 Compatibility...................................................................................................80
PA-RISC Architectures and Their System Models......................................................................80
Link-time Differences Between SOM (PA32) and ELF (PA64 and Itanium)........................................80
Run-time Differences Between SOM (PA32) and ELF (PA64 and Itanium)........................................82
PA64 Mode Linker Options......................................................................................................82
Linker-Defined Symbols............................................................................................................82
Dynamic Path Searching for Shared Libraries..............................................................................83
Symbol Searching in Dependent Libraries..............................................................................86
System Libraries - Locations and Library Name Extension..............................................................87
System Library Location.......................................................................................................87
Shared Library Extension (suffix)...........................................................................................87
Statically-bound programs (archive-bound programs)..............................................................88
6 Creating and Using Libraries......................................................................89
Overview of Shared and Archive Libraries..................................................................................89
What are Archive Libraries?.....................................................................................................90
Contents 5
What are Shared Libraries?.....................................................................................................91
The Dynamic Loader ..........................................................................................................91
Default Behavior When Searching for Libraries at Run Time.....................................................91
Caution on Using Dynamic Library Searching........................................................................92
Running setuid Programs.....................................................................................................92
Example Program Comparing Shared and Archive Libraries.........................................................92
Shared Libraries with Debuggers, Profilers, and Static Analysis.....................................................94
Profiling Shared Libraries with gprof(1) .................................................................................94
Creating Archive Libraries........................................................................................................94
Overview of Creating an Archive Library...............................................................................95
Contents of an Archive File..................................................................................................95
Example of Creating an Archive Library................................................................................96
Replacing, Adding, and Deleting an Object Module..............................................................97
Replacing or Adding an Object Module...........................................................................97
Deleting an Object Module............................................................................................97
Summary of Keys to the ar(1) Command................................................................................97
Useful ar Keys...............................................................................................................97
crt0.o..........................................................................................................................98
Archive Library Location (IPF) ..............................................................................................98
Using /usr/lib and /usr/lib/pa20_64 ...........................................................................98
Using /usr/local/lib or /usr/contrib/lib..........................................................................98
Creating Shared Libraries........................................................................................................98
Creating Position-Independent Code (PIC).............................................................................99
Example Using +z.........................................................................................................99
Comparing +z and +Z...................................................................................................99
Compiler Support for +z and +Z.....................................................................................99
Creating the Shared Library with ld......................................................................................99
Shared Library Dependencies............................................................................................100
The Order in Which Libraries are Loaded (Load Graph)...................................................100
Placing Loaded Libraries in the Search List......................................................................101
Updating a Shared Library................................................................................................102
Incompatible Changes to a Shared Library.....................................................................102
Shared Library Location (IPF).............................................................................................102
Improving Shared Library Performance................................................................................102
Loading Shared Libraries with the LD_PRELOAD Environment Variable................................103
LD_PRELOAD Example.................................................................................................103
LD_PRELOAD Example (PA-RISC)...................................................................................104
64-bit Behavior......................................................................................................104
32-bit Behavior.......................................................................................................105
Loading Shared Libraries with the LD_PRELOAD_ONCE Environment Variable.....................106
Using Profile-Based Optimization on Shared Libraries.......................................................106
Exporting Only the Required Symbols............................................................................106
Placing Frequently-Called Routines Together....................................................................106
Making Shared Libraries Non-Writable..........................................................................107
Using the +ESlit/+Olit=all Option to cc..........................................................................107
+cond_rodata Command-Line Option............................................................................108
Using Filtered Shared Libraries (32-bit Mode Only)..........................................................108
Building Filtered Shared Libraries..............................................................................108
Building application programs linked to filtered shared libraries....................................109
Run time behavior of filtered shared libraries..............................................................109
Initializers..............................................................................................................109
Dynamic Path Lookup..............................................................................................110
Thread-Private Data (TLS).........................................................................................110
Maintaining filtered shared libraries..........................................................................110
Function Level Versioning..................................................................................................110
6 Contents
Version Control with Shared Libraries......................................................................................110
When to Use Shared Library Versioning..............................................................................110
Maintaining Old Versions of Library Modules......................................................................111
Library-Level Versioning.....................................................................................................111
How to Use Library-Level Versioning ..............................................................................111
Creating a New, Incompatible Version of the Library ......................................................112
Migrating an Existing Library to Use Library-Level Versioning.............................................112
The +h Option and Internal Names...............................................................................112
File System Links to Shared Libraries...................................................................................112
Using shl_load(3X) with Library-Level Versioning...................................................................113
Intra-Library Versioning (PA-RISC only).................................................................................113
The Version Number Compiler Directive.........................................................................113
Shared Library Dependencies and Version Control...........................................................114
Adding New Versions to a Shared Library......................................................................114
Specifying a Version Date............................................................................................115
Switching from Archive to Shared Libraries...............................................................................115
Relying on Undocumented Linker Behavior ..........................................................................115
Absolute Virtual Addresses................................................................................................116
Stack Usage....................................................................................................................116
Version Control................................................................................................................116
Debugger Limitations........................................................................................................116
Using the chroot Command with Shared Libraries.................................................................117
Profiling Limitations..........................................................................................................117
Summary of HP-UX Libraries...................................................................................................117
Caution When Mixing Shared and Archive Libraries.................................................................118
Example 1: Unsatisfied Symbols.........................................................................................118
Example 2: Using shl_load(3X)..........................................................................................120
Example 3: Hidden Definitions..........................................................................................122
Using Shared Libraries in Default Mode...................................................................................124
Internal Name Processing.................................................................................................125
Dynamic Path Searching for Shared Libraries.......................................................................126
Shared Library Symbol Binding Semantics...........................................................................126
Link-Time Symbol Resolution in Shared Libraries ..............................................................126
Resolution of Unsatisfied Shared Library References.........................................................127
Promotion of Uninitialized Global Data Items.............................................................128
Symbol Searching in Dependent Libraries..................................................................129
Mixed Mode Shared Libraries............................................................................................130
IPF Library Examples........................................................................................................131
Library Example: Creating an IPF Compatibility Mode Shared Library................................131
Library Example: Creating an IPF Standard Mode Shared Library......................................132
Library example: IPF Dynamic Path Searching.................................................................132
Library Example: IPF Compatibility Mode Link.................................................................133
Library Example: Using IPF Compatibility and Standard Shared Libraries............................133
Comparing Breadth-first and Depth-first Search in IPF/PA-64 Mode....................................133
Library Example: Using RPATH with Standard Mode Shared Library...................................134
Linking Libraries with +b pathlist....................................................................................134
Library Example: Linking to Libraries with +b path_list in IPF/PA-64 Mode..........................134
Library Example: Linking to Libraries with +b path_list in PA-32 Mode................................135
7 Shared Library Management Routines.......................................................136
Shared Library Management Routine Summaries.......................................................................136
The dlopen Routines Summary...........................................................................................136
The shl_load Routine Summary..........................................................................................137
Related Files and Commands.............................................................................................137
Shared Library Header Files...................................................................................................137
Contents 7
Using Shared Libraries with cc and ld Options.........................................................................138
Initializers for Shared Libraries................................................................................................138
Styles of Initializers ..........................................................................................................138
Init/Fini Style Initializers...............................................................................................138
HP-UX-10.X Style Initializers...........................................................................................139
Using Init/Fini Initializers..................................................................................................139
Init and Fini Usage Example.........................................................................................139
Ordering Within an Executable or Shared Library...........................................................141
Ordering Among Executables and Shared Libraries.........................................................142
Using HP-UX 10.X Style Initializers......................................................................................143
Declaring the Initializer with the +I Option......................................................................143
Order of Execution of Multiple Initializers.......................................................................143
Initializer Syntax..........................................................................................................144
Accessing Initializers' Addresses...............................................................................144
Example: An Initializer for Each Library..........................................................................144
Example: A Common Initializer for Multiple Libraries........................................................146
The dlopen Shared Library Management Routines.....................................................................148
The dlopen Routine .........................................................................................................148
Syntax ......................................................................................................................148
Return Values..............................................................................................................149
Description.................................................................................................................150
Using dlopen to load a shared library...........................................................................152
The dlsetlibpath Routine....................................................................................................153
Synopsis....................................................................................................................153
Description.................................................................................................................153
Using dlsetlibpath to set the dynamic search path.......................................................154
Multithread Usage.......................................................................................................155
Return Value...............................................................................................................155
Errors........................................................................................................................155
The dlerrno Routine..........................................................................................................155
Synopsis....................................................................................................................155
Description.................................................................................................................155
The dlgetfileinfo Routine....................................................................................................155
Synopsis....................................................................................................................155
Description.................................................................................................................155
Multithread Usage.......................................................................................................157
Return Value...............................................................................................................157
Errors........................................................................................................................157
The dlerror Routine...........................................................................................................157
Syntax.......................................................................................................................157
Description.................................................................................................................157
Using dlerror to get diagnostic information.....................................................................157
The dlsym Routine............................................................................................................157
Syntax.......................................................................................................................157
Return Values..............................................................................................................158
Description.................................................................................................................158
Usage.......................................................................................................................158
Using dlopen and dlsym to access either function or data objects......................................158
The dlget Routine.............................................................................................................159
Syntax.......................................................................................................................159
Return Values..............................................................................................................159
Description.................................................................................................................159
Using dlget to retrieve information about loaded modules.................................................160
The dlmodinfo Routine......................................................................................................160
Syntax ......................................................................................................................160
8 Contents
Return Values..............................................................................................................160
Description.................................................................................................................161
Using dlmodinfo to retrieve information about a load module............................................161
The dlgetname Routine.....................................................................................................161
Syntax.......................................................................................................................161
Return Values..............................................................................................................162
Description.................................................................................................................162
Using dlgetname to retrieve pathname...........................................................................162
The dlclose Routine..........................................................................................................162
Syntax.......................................................................................................................162
Return Values..............................................................................................................163
Description.................................................................................................................163
Using dlclose to unload a shared library........................................................................163
The dladdr Routine...........................................................................................................163
Syntax.......................................................................................................................163
Return Values..............................................................................................................164
Diagnostics................................................................................................................164
Description.................................................................................................................164
Using dladdr to get the symbolic information for an address.............................................165
The dlmodadd Routine......................................................................................................165
Syntax.......................................................................................................................165
Return Values..............................................................................................................165
Description.................................................................................................................166
The dlmodremove Routine.................................................................................................166
Syntax.......................................................................................................................166
Return Values..............................................................................................................166
Description.................................................................................................................166
The dlgetmodinfo Routine..................................................................................................166
Syntax.......................................................................................................................166
Return Values..............................................................................................................167
Description.................................................................................................................167
Using dlgetmodinfo.....................................................................................................167
The shl_load Shared Library Management Routines...................................................................168
The shl_load Routine........................................................................................................168
Syntax.......................................................................................................................168
Parameters.................................................................................................................168
Return Value...............................................................................................................169
Description.................................................................................................................169
shl_load Usage...........................................................................................................170
shl_load Example........................................................................................................170
BIND_NONFATAL Modifier.....................................................................................171
BIND_VERBOSE Modifier........................................................................................171
BIND_FIRST Modifier..............................................................................................171
DYNAMIC_PATH Modifier.......................................................................................171
BIND_NOSTART Modifier .......................................................................................171
BIND_RESTRICTED Modifier.....................................................................................171
BIND_TOGETHER Modifier......................................................................................172
BIND_BREADTH_FIRST Modifier...............................................................................172
The shl_findsym Routine....................................................................................................172
Syntax ......................................................................................................................172
Parameters ................................................................................................................173
Return Value...............................................................................................................173
Description.................................................................................................................173
shl_findsym Example....................................................................................................174
Load a Shared Library and Call its Routines and Access its Data...................................174
Contents 9
The shl_get and shl_get_r Routines.....................................................................................175
Syntax.......................................................................................................................175
Parameters.................................................................................................................175
Return Value...............................................................................................................176
Description.................................................................................................................176
Example ...................................................................................................................176
The shl_gethandle and shl_gethandle_r Routines..................................................................177
Syntax.......................................................................................................................177
Parameters.................................................................................................................177
Return Value...............................................................................................................177
Description.................................................................................................................177
Example....................................................................................................................177
The shl_definesym Routine.................................................................................................177
Syntax.......................................................................................................................178
Parameters ................................................................................................................178
Return Value...............................................................................................................178
Description.................................................................................................................178
The shl_getsymbols Routine...............................................................................................178
Syntax ......................................................................................................................178
Parameters ................................................................................................................179
Return Value...............................................................................................................179
The shl_symbol Structure...............................................................................................180
show_symbols - Display Shared Library Symbols..............................................................180
show_all - Use show_symbols to Show All Symbols .........................................................181
The shl_unload Routine.....................................................................................................182
Syntax ......................................................................................................................182
Parameters ................................................................................................................182
Return Value ..............................................................................................................182
Description ................................................................................................................182
Usage.......................................................................................................................182
The shl_unload Routine Returning ETXTBSY.....................................................................183
Dynamic Loader Compatibility Warnings.................................................................................183
Unsupported Shared Library Management Routines..............................................................183
Unsupported Shared Library Management Flags..................................................................183
8 Writing and Generating Position-Independent Code....................................185
What is a Relocatable Object Code?......................................................................................185
What is a Absolute Object Code?..........................................................................................185
What is a Position-Independent Code?....................................................................................186
Generating Position-Independent Code....................................................................................186
PIC Requirements for Compilers and Assembly Code............................................................187
Long Calls.......................................................................................................................188
Long Branches and Switch Tables.......................................................................................188
Assigned GOTO Statements .............................................................................................188
Literal References.............................................................................................................188
Global and Static Variable References................................................................................189
Procedure Labels..............................................................................................................189
9 Using Mapfiles.......................................................................................191
Controlling Mapfiles with the -k Option....................................................................................191
Changing Mapfiles with -k filename and +nodefaultmap............................................................191
Mapfile Example: Using -k mapfile and +nodefaultmap .......................................................191
Simple Mapfile.....................................................................................................................193
Default HP-UX 11.0 Release Mapfile.........................................................................................193
Defining Syntax for Mapfile Directives.....................................................................................195
Defining Mapfile Segment Declarations...................................................................................196
10 Contents
Segment Flags.................................................................................................................196
Mapfile Segment Declaration Examples..............................................................................197
Defining Mapfile Section Mapping Directives...........................................................................197
Internal Map Structure...........................................................................................................198
Placement of Segments in an Executable.............................................................................198
Mapping Input Sections to Segments..................................................................................198
Interaction between User-defined and Default Mapfile Directives.............................................200
Mapfile Option Error Messages..............................................................................................200
Fatal Errors.....................................................................................................................200
Warnings ......................................................................................................................201
10 Improving Your Application Performance..................................................202
Linker Optimizations..............................................................................................................202
Invoking Linker Optimizations from the Compile Line.............................................................202
Incompatibilities with other Options ...................................................................................203
Unused Procedure Elimination with +Oprocelim...................................................................203
Complete Executables..................................................................................................203
Incomplete Executables................................................................................................204
Shared Libraries..........................................................................................................204
Retain Unreferenced Symbols with +noprocelim_sym........................................................204
Relocatable Objects....................................................................................................204
Affects on Symbolic Debugging....................................................................................204
Profile-Based Optimization (PA-RISC)..................................................................................204
General Information about PBO....................................................................................204
Using PBO ................................................................................................................205
When to Use PBO.......................................................................................................205
How to Use PBO.........................................................................................................205
Instrumenting (+I/-I).....................................................................................................206
The Startup File icrt0.o............................................................................................207
The -I Linker Option.................................................................................................207
Code Generation from I-SOMs.................................................................................207
Building Portable Code with Linker Optimization.........................................................208
Profiling.....................................................................................................................208
Choosing Input Data...............................................................................................208
The flow.data File...................................................................................................208
Storing Profile Information for Multiple Programs.........................................................209
Sharing the flow.data File Among Multiple Processes..................................................209
Forking an Instrumented Application.........................................................................210
Optimizing Based on Profile Data (+P/-P).......................................................................210
The -P Linker Option................................................................................................210
Using The flow.data File..........................................................................................211
Specifying a Different flow.data File with +df..............................................................211
Specifying a Different flow.data with FLOW_DATA......................................................211
Interaction between FLOW_DATA and +df ................................................................211
Specifying a Different Program Name (+pgm)............................................................211
Selecting an Optimization Level with PBO.......................................................................212
Using PBO to Optimize Shared Libraries........................................................................212
Using PBO with ld -r....................................................................................................213
Restrictions and Limitations of PBO................................................................................214
Temporary Files......................................................................................................214
Source Code Changes and PBO..............................................................................214
Profile-Based Optimization (PBO) and High-Level Optimization (HLO)............................214
I-SOM File Restrictions.............................................................................................215
Compatibility with 9.0 PBO.....................................................................................216
Compatibility with 9.0 PBO..........................................................................................216
Contents 11
Options to Improve TLB Hit Rates............................................................................................217
Profile-Based Optimization (Itanium)........................................................................................217
Incremental Linking...............................................................................................................217
Using Incremental Linking Options......................................................................................219
Archive Library Processing.................................................................................................219
Shared Library Processing.................................................................................................219
Performance ...................................................................................................................219
Reusing Compiled Object Files (PA-RISC).................................................................................220
Improving Performance with the Global Symbol Table................................................................220
Improving Performance by Optimizing the Hash Table Size........................................................221
Improving Performance with Function Symbol Aliasing...............................................................222
Improving Shared Library Start-Up Time with fastbind................................................................222
Using fastbind.................................................................................................................222
Invoking the fastbind Tool..................................................................................................223
Invoking fastbind from the Linker........................................................................................223
How to Tell if fastbind Information is Current........................................................................223
Removing fastbind Information from a File...........................................................................224
Turning off fastbind at Run Time.........................................................................................224
Glossary..................................................................................................225
12 Contents

About This Document

This document discusses the most recent product information on HP-UX Linker and Libraries Version B.11.72 for HP 9000 systems and Version B.12.57 for Integrity systems that are running HP-UX 11i v1, HP-UX 11i v2, and HP-UX 11i v3.

Intended Audience

This document is intended for developers who want to compile, link, and build applications using the HP C/ANSI C Developer's Bundle on HP 9000 or HP Integrity systems.

Document conventions and symbols

Table 1 (page 13) lists the conventions and symbols used in this white paper.
Table 1 Document conventions
ElementConvention
Cross-reference links and email addressesMedium blue text:
Website addressesMedium blue, underlined text
(http://www.hp.com)
Bold font
Monospace font
Monospace, italic font
Monospace, bold font
Key names
Text typed into a GUI element, such as into a box
GUI elements that are clicked or selected, such as menu and list items,
buttons, and check boxes
Text emphasisItalic font
File and directory names
System output
Code
Text typed at the command line
Code variables
Command-line variables
Emphasis of file and directory names, system output, code, and text typed at the command line
CAUTION: Indicates that failure to follow directions can result in damage to equipment or data.
IMPORTANT: Provides clarifying information or specific instructions.
NOTE: Provides additional information.

Related Information

The following documents provide more information:
HP-UX Linker, Libraries, and Tools Versions B.11.72 and B.12.57 Release Notes
Improving program startup with fastbind: White paper
The HP-UX Linker web page is at:
http://www.hp.com/go/linker
Intended Audience 13

HP Encourages Your Comments

HP encourages your comments concerning this document. We are committed to providing documentation that meets your needs. Send any errors found, suggestions for improvement, or compliments to:
feedback@fc.hp.com
Include the document title, manufacturing part number, and any comment, error found, or suggestion for improvement you have concerning this document.

Document Organization

This guide is organized into the following chapters: This document is organized as follows:
“Compiling and Linking Programs on HP-UX” (page 16)
This chapter describes the process of compiling and linking programs on HP-UX. An example is used to illustrate the process. The sections here describe the process of creating an executable file and explain how ld creates an executable file from one or more object files. This chapter also describes the conventions for using libraries with ld, describes the process of loading and binding programs at run time, and explains the thread-safe features of linker. In addition, it explains the means by which you can control how the linker links your programs or libraries.
“Determining How to Link Programs or Libraries (Linker Tasks)” (page 27)
This chapter describes the tasks you can perform using the Compiler commands and Linker commands. The tasks help you determine how the linker must link your program or library.
“Linker Tools for Itanium-Based Systems” (page 53)
This chapter describes the linker toolset available for IA systems. The linker toolset provides several tools to help you find symbols, display and modify object files, and determine link order.
“Linker Tools for PA-RISC Systems” (page 69)
This chapter describes the linker toolset available for PA-RISC systems. The linker toolset provides several tools to help you find symbols, display and modify object files, and determine link order.
“Linker Toolset Differences Between PA-RISC and Itanium-Based Systems” (page 79)
This chapter describes some of the linker toolset differences between PA-RISC and Itanium-based systems. This chapter also describes linker options specific to PA64 mode, symbols reserved by linker, system library location, changes to the library name extension, and dynamic path searching for shared libraries.
“Creating and Using Libraries” (page 89)
This chapter provides an overview of shared and archived libraries, explains creating and using libraries on HP-UX, and describes how to use shared libraries for programs in IA.
“Shared Library Management Routines” (page 136)
This chapter explains shared library header files, initializers for shared libraries, and the various shared library management routines.
14
“Writing and Generating Position-Independent Code” (page 185)
This chapter is applicable to only PA-RISC 32-bit applications. The chapter explains relocatable object code, absolute object code, and position-independent code. The chapter also explains how to generate position-independent code.
“Using Mapfiles” (page 191)
This chapter explains how to use mapfiles. The mapfile option, which is an advanced feature of the linker toolset, is intended for use in system programming.
“Improving Your Application Performance” (page 202)
This chapter explains how you can use linker to improve the performance of your applications. This chapter discusses options to improve TLB hit rates, incremental linking, profile-based optimization, and other ways to improve application performance.
Glossary
The glossary provides definitions of terms listed alphabetically.
Document Organization 15

1 Compiling and Linking Programs on HP-UX

This chapter describes the process of compiling and linking a program.
DescriptionSection
Provides an overview of compiling on HP-UX.“Compiling Programs on HP-UX: An Example”
(page 16)
Describes how ld creates an executable file from one or more object.“Linking Programs on HP-UX” (page 21)
Describes conventions for using libraries with ld.“Linking with Libraries” (page 23)
Describes the process of loading and binding programs at run time.“Running the Program” (page 25)
Describes the thread-safe features.“Linker Thread-Safe Features” (page 26)

Compiling Programs on HP-UX: An Example

This chapter addresses the following:
“Overview” (page 16)
“Looking Inside a Compiler” (page 18)
“Compiler-Linker Interaction” (page 19)

Overview

To create an executable program, you compile a source file containing a main program. For example, to compile an ANSI C program named sumnum.c, shown below, use this command (-Aa says to compile in ANSI mode):
$ cc -Aa sumnum.c
The compiler displays status, warning, and error messages to standard error output (stderr). If no errors occur, the compiler creates an executable file named a.out in the current working directory. If your PATH environment variable includes the current working directory, you can run
a.out as follows:
$ a.out Enter a number: 4 Sum 1 to 4: 10
The process is essentially the same for all HP-UX compilers. For instance, to compile and run a similar FORTRAN program named sumnum.f:
$ f90 sumnum.f //Compile and link sumnum.f.
... //The compiler displays any messages here. $ a.out
//Run the program. ...
//Output from the program is displayed here.
Program source can also be divided among separate files. For example, sumnum.c could be divided into two files: main.c, containing the main program, and func.c, containing the function
sum_n. The command for compiling the two together is:
$ cc -Aa main.c func.c main.c: func.c:
16 Compiling and Linking Programs on HP-UX
Notice that cc displays the name of each source file it compiles. This way, if errors occur, you know where they occur. Also, the diagnostics mention the name of the source file.
#include <stdio.h> /* contains standard I/O defs */ int sum_n( int n )
/* sum numbers from n to 1 */ { int sum = 0;
/* running total; initially 0 */
for (; n >= 1; --n)
/* sum from n to 1 */
sum += n;
/* add n to sum */
return sum;
/* return the value of sum */ }
int main() /* begin main program
*/ { int n;
/* number to input from user */
printf("Enter a number: ");
/* prompt for number */
scanf("%d", &n);
/* read the number into n */
printf("Sum 1 to %d: %d\\n", n, sum_n(n)); /* display the sum */ }
Generally speaking, the compiler reads one or more source files, one of which optionally contains a main program, and outputs an executable named a.out by default unless a name is specified, as shown in Figure 1.
Compiling Programs on HP-UX: An Example 17
Figure 1 High-level View of the Compiler

Looking Inside a Compiler

On the surface, it appears as though an HP-UX compiler generates an a.out file by itself. Actually, an HP-UX compiler is a driver that calls other commands to create the a.out file. The driver performs different tasks (or phases) for different languages, but two phases are common to all languages:
1. For each source file, the driver calls the language compiler to create an object file. (See also
“What is an Object File?” (page 18))
2. The HP-UX linker (ld) links the specified object files to create either a reusable object file, also
called a shared library, or an executable, which is named a.out by default unless a name is specified. (See also “Compiler-Linker Interaction” (page 19).)
Figure 2 summarizes how a compiler driver works.
Figure 2 Looking Inside a Compiler
The C, aC++, and Fortran90 compilers provide the -v (verbose) option to display the phases a compiler is performing.
What is an Object File?
An object file is basically a file containing machine language instructions and data in a form that the linker can use to create an executable program. Each routine or data item defined in an object file has a corresponding symbol name by which it is referenced. A symbol generated for a routine
18 Compiling and Linking Programs on HP-UX
or data definition can be either a local definition or global definition. Any reference to a symbol outside the object file is known as an external reference.
To keep track of where all the symbols and external references occur, an object file has a symbol table. The linker uses the symbol tables of all input object files to match external references to global definitions.
Local Definitions
A local definition is a definition of a routine or data that is accessible only within the object file in which it is defined. Such a definition cannot be accessed from another object file. Local definitions are used primarily by debuggers, such as adb. More important for this discussion are the global definitions and external references.
Global Definitions
A global definition is a definition of a procedure, function, or data item that can be accessed by code in another object file. For example, the C compiler generates global definitions for all variable and function definitions that are not static. The FORTRAN compiler generates global definitions for subroutines and common blocks. In Pascal, global definitions are generated for external procedures, external variables, and global data areas for each module.
External References
An external reference is an attempt by code in one object file to access a global definition in another object file. A compiler cannot resolve external references because it works on only one source file at a time. Therefore, the compiler simply places external references in an object file's symbol table; the matching of external references to global definitions is left to the linker or loader.

Compiler-Linker Interaction

As described in “Looking Inside a Compiler” (page 18), the compilers automatically call the linker to create an executable file. To see how the compilers call ld, run the compiler with the -v (verbose) option.
For example, compiling a C program to produce an IPF 32-bit share-bound application, produces the output below:
$ cc -v main.c func.c -lm main.c: /opt/ansic/lbin/ecom -ia64abi all -architecture 32 -ext on -lang c \
-exception off -sysdir /usr/include - inline_power 1 -link_type dynamic \
-fpeval float - tls_dyn on -target_os 11.23 --sys_include /usr/include \
-D__hpux -D__unix -D__ia64=1 -D_BIG_ENDIAN=1 -D_ILP32 -D__HP_cc=60200 \
-D__STDC_EXT__ -D_HPUX_SOURCE -D_INCLUDE_LONGLONG -D_INLINE_ASM \
-D_BIND_LIBCALLS -D_Math_errhandling=MATH_ERREXCEPT -D_FLT_EVAL_METHOD=O \
-ucode hdriver=optlevel%1% -plusolistoption -O106const! -plusolistoption \
-O113moderate! -plusooption -Oq01,al,ag,cn,sz,ic,vo,Mf,Po,es,rs,Rf,Pr,sp,\ in,cl,om,vc,pi,fa,pe,rr,pa,pv,nf,cp,1x,Pg,ug,1u,lb,uj,dn,sg,pt,kt,em,np,ar,\ rp,dl,fs,bp,wp,pc,mp,1r,cx,cr,pi,so,Rc,fa,ft,fe,ap,st,lc,Bl,sr,ib,pl,sd,ll,\ rl,dl,Lt,ol,fl,lm,ts,rd,dp,If! main.c func.c: /opt/ansic/lbin/ecom -ia64abi all -architecture 32 -ext on -lang c \
-exception off -sysdir /usr/include - inline_power 1 -link_type dynamic \
-fpeval float - tls_dyn on -target_os 11.23 --sys_include /usr/include \
Compiling Programs on HP-UX: An Example 19
-D__hpux -D__unix -D__ia64=1 -D_BIG_ENDIAN=1 -D_ILP32 -D__HP_cc=60200 \
-D__STDC_EXT__ -D_HPUX_SOURCE -D_INCLUDE_LONGLONG -D_INLINE_ASM \
-D_BIND_LIBCALLS -D_Math_errhandling=MATH_ERREXCEPT -D_FLT_EVAL_METHOD=O \
-ucode hdriver=optlevel%1% -plusolistoption -O106const! -plusolistoption \
-O113moderate! -plusooption -Oq01,al,ag,cn,sz,ic,vo,Mf,Po,es,rs,Rf,Pr,sp,\ in,cl,om,vc,pi,fa,pe,rr,pa,pv,nf,cp,1x,Pg,ug,1u,lb,uj,dn,sg,pt,kt,em,np,ar,\ rp,dl,fs,bp,wp,pc,mp,1r,cx,cr,pi,so,Rc,fa,ft,fe,ap,st,lc,Bl,sr,ib,pl,sd,ll,\ rl,dl,Lt,ol,fl,lm,ts,rd,dp,If! func.c LPATH=/usr/lib/hpux32:/opt/langtools/lib/hpux32 /usr/ccs/bin/ld -o a.out -u__exit -umain main.o func.o -lm -lc
removing /var/tmp/AAAa02486
This example shows that the cc driver calls the actual C compiler (/opt/ansic/lbin/ecom) for each source file. Then the driver calls the linker (/usr/ccs/bin/ld) on the object files created by the compiler (main.o and func.o).
The next-to-last line in the above example is the command line that the compiler used to invoke the linker, /usr/ccs/bin/ld. When building a share-bound executable, the startup functions are handled by the dynamic loader dld. By default, the dynamic loader is found in /usr/lib/hpux32. Thus, in most cases, the ld command does not include crtO.o. In the ld command line, ld combines the two object files created by the compiler (main.o and func.o). It also searches the libm (-lm) and libc (-lc) libraries.
On PA-RISC systems, the same compile command invokes the PA32 linker. The output is shown below.
$ cc -Aa -v main.c func.c -lm cc: CCOPTS is not set. main.c: /opt/langtools/lbin/cpp.ansi main.c /var/tmp/ctmAAAa10102 \
-D__hp9000s700 -D__hp9000s800 -D__hppa -D__hpux \
-D__unix -D_PA_RISC1_1 cc: Entering Preprocessor. /opt/ansic/lbin/ccom /var/tmp/ctmAAAa10102 main.o -O0 -Aa func.c: /opt/langtools/lbin/cpp.ansi func.c /var/tmp/ctmAAAa10102 \
-D__hp9000x700 -D__hp9000s800 -D__hppa -D__hpux \
-D__unix -D_PA_RISC1_1 cc: Entering Preprocessor. /opt/ansic/lbin/ccom /var/tmp/ctmAAAa10102 func.o -O0 -Aa cc: LPATH is /usr/lib/pa1.1:/usr/lib:/opt/langtools/lib: /usr/ccs/bin/ld /opt/langtools/lib/crt0.o -u main main.o func.o -lm -lc cc: Entering Link editor.
The next-to-last line in the above example is the command line the compiler used to invoke the PA32 mode linker, /usr/ccs/bin/ld. In this command, ld combines a startup file (crt0.o) and the two object files created by the compiler (main.o and func.o) Also, ld searches the libm and libc libraries.
For PA64 and IPF executables, the startup functions are handled by the dynamic loader. In most cases, the ld command line does not include crt0.o.
20 Compiling and Linking Programs on HP-UX

Linking Programs on HP-UX

“The crt0.o Startup File” (page 21)
“The a.out File” (page 22)
“Magic Numbers (PA-RISC ONLY)” (page 22)
“File Permissions” (page 23)
The HP-UX linker (ld) creates an executable file, shared library, or combines the object files to create another relocatable object file. In doing so, it matches external references to global definitions contained in other object files or libraries. It revises code and data to reflect new addresses. This process is known as relocation. If the input files contain debugger information, ld updates this information appropriately. The linker places the resulting executable code in a file named, by default, a.out.
In the C program example, (see “Compiling Programs on HP-UX: An Example” (page 16) ) main.o contains an external reference to sum_n, which has a global definition in func.o.
The linker (ld) matches the external reference to the global definition, allowing the main program code in a.out to access sum_n (see Figure 3 (page 21)).
Figure 3 Matching the External Reference to sum_n
If the linker (ld) cannot match an external reference to a global definition, it displays a message to standard error output. If, for instance, you compile main.c without func.c, the linker (ld) cannot match the external reference to sum_n and displays this output:
$ cc -Aa main.c ld: Unsatisfied symbol "func1" in file main.o 1 errors.

The crt0.o Startup File

Notice that in the PA32 example in “Compiler-Linker Interaction” (page 19) the first object file on the linker command line is /opt/langtools/lib/crt0.o, even though this file was not specified on the compiler command line. This file, known as a startup file, contains the program's entry point. The program's entry point is is the location at which the program starts running after HP-UX loads it into memory to begin execution. The startup code does such things as retrieving command line arguments into the program at run time, and activating the dynamic loader to load any required shared libraries. In the C language, it also calls the routine _start in libc which, in turn, calls the main program as a function.
Linking Programs on HP-UX 21
The linker uses four startup files:
32-bit PA is /opt/langtools/lib/crt0.o
64-bit PA is /opt/langtools/lib/pa_64/crt0.o
The linker uses this startup file when it is in compatibility mode (+compat) or it is in default standard mode (+std) with the -noshared option.
32-bit IPF is /opt/langtools/lib/hpux32/crt0.o
The linker uses this startup file when it is in default standard mode (+std) with the -noshared option.
64-bit IPF is /opt/langtools/lib/hpux64/crt0.o
The linker uses this startup file when it is in default standard mode (+std) with the -noshared option.
If the -p profiling option is specified on the compile line, the compilers link with -L
/usr/ccs/lib/libp -lprof. If the-G profiling option is specified, the compilers link with /usr/ccs/lib/lip -lgprof.
PA-RISC ONLY:
If the linker option -I is specified to create an executable file with profile-based optimization, in 32-bit mode icrt0.o is used, and in 64-bit mode the linker inserts /usr/ccs/lib/pa20_64/fdp_init.o. If the linker options -I and -b are specified to create a shared library with profile-based optimization, in 32-bit mode scrt0.o is used, and in 64-bit mode, the linker inserts /usr/ccs/lib/pa20_64/fdp_init-sl.o. In 64-bit mode, the linker uses the single 64-bit crt0.o to support these options.
For details on startup files, see crt0(3).
The Program's Entry Point
For archive-bound (using the -complete compiler option or the -noshared linker option) executables, the entry point is the location at which execution begins in the a.out file. The entry point is defined by the symbol $START$ in crt0.o. In share-bound executables, the entry point is defined by the symbol $START$ in the dynamic loader (dld.so).

The a.out File

The information contained in the resulting a.out file depends on which architecture the file was created on and what options were used to link the program. In any case, an executable a.out file contains information that HP-UX needs when loading and running the file. For example: Is it a shared executable? Does it reference shared libraries? Is it demand-loadable? Where do the text (code), data, and bss (uninitialized data) segments reside in the file? For details on the format of this file, see a.out(4).

Magic Numbers (PA-RISC ONLY)

In 32-bit mode, the linker records a magic number with each executable program that determines how the program should be loaded. There are three possible values for an executable file's magic number:
SHARE_MAGIC The program's text (code) can be shared by processes; its data cannot be
shared. The first process to run the program loads the entire program into virtual memory. If the program is already loaded by another process, then a process shares the program text with the other process.
DEMAND_MAGIC As with SHARE_MAGIC the program's text is shareable but its data is not.
However, the program's text is loaded only as needed - that is, only as the pages are accessed. This improves process startup time since the entire
22 Compiling and Linking Programs on HP-UX
program does not need to be loaded; however, it can degrade performance throughout execution.
EXEC_MAGIC Neither the program's text nor data is shareable. In other words, the program is
an unshared executable. Usually, it is not desirable to create such unshared executables because they place greater demands on memory resources.
By default, the linker creates executables whose magic number is SHARE_MAGIC. Table 2 (page
23) shows which linker option to use to specifically set the magic number.
Table 2 32-bit Mode Magic Number Linker Options
Use the optionTo set the magic number to
-nSHARE_MAGIC
-qDEMAND_MAGIC
-NEXEC_MAGIC
An executable file's magic number can also be changed using the chatr command (see “Changing
a Program's Attributes with chatr(1)” (page 53) ). However, chatr can only toggle between
SHARE_MAGIC and DEMAND_MAGIC; it cannot be used to change from or to EXEC_MAGIC. This is because the file format of SHARE_MAGIC and DEMAND_MAGIC is exactly the same, while EXEC_MAGIC files have a different format. For details on magic numbers, refer to magic(4).
In 64-bit mode, the linker sets the magic number to the predefined type for ELF object files (\177ELF). The value of the e_type field in the ELF object file header specifies how the file should be loaded.

File Permissions

If linker errors do not occur, the linker gives the a.out file read/write/execute permissions to all users (owner, group, and other). If errors occur, the linker gives read/write permissions to all users. Permissions are further modified if the umask is set (see umask(1)). For example, on a system with umask set to 022, a successful link produces an a.out file with read/write/execute permissions for the owner, and read/execute permissions for group and others:
$ umask 022 $ ls -l a.out
-rwxr-xr-x 1 michael users
74440 Apr
4 14:38 a.out

Linking with Libraries

“Library Naming Conventions” (page 24)
“Default Libraries” (page 24)
“Link Order” (page 24)
In addition to matching external references to global definitions in object files, the linker (ld) matches external references to global definitions in libraries. A library is a file containing object code for subroutines and data that can be used by other programs. For example, the standard C library, libc, contains object code for functions that can be used by C, C++, FORTRAN, and Pascal programs to do input, output, and other standard operations.
Linking with Libraries 23

Library Naming Conventions

By convention, library names have the form:
libname. suffix
name is a string of one or more characters that identifies the library. suffix is .a if the library is an archive library, .sl if the library is a PA-RISC shared library,
or .so if the library is a shared library. (The suffix can be .sl for an IPF shared library. This naming convention is not recommended, but it is supported for backwards compatibility with PA-32 and PA-64.)
Typically, library names are referred to without the suffix. For instance, the standard C library is referred to as libc.

Default Libraries

A compiler driver automatically specifies certain default libraries when it invokes ld. For example, cc automatically links in the standard library libc, as shown by the -lc option to ld in this example:
$ cc -Aa -v main.c func.c ... /usr/ccs/bin/ld -o a.out -u__exit -umain main.o func.o -lc cc: informational note 413: Entering Link editor.
Similarly, the Series 700/800 Fortran90 compiler automatically links with the libcl (C interface), libisamstub (ISAM file I/O), and libc libraries:
$ f90 -v sumnum.f ... /usr/ccs/bin/ld -x /opt/langtools/lib/crt0.o \ sumnum.o -lcl -lisamstub -lc
The Default Library Search Path
Following are the default search paths for the libraries:
On Itanium systems, ld searches for libraries in the directory /usr/lib/hpux32 for 32-bit
executables and /usr/lib/hpux64 for 64-bit executables.
On PA-RISC systems, ld searches for libraries in the directory /usr/lib/ for 32-bit
executables and /usr/lib/pa20_64/ for 64-bit executables.
If the -p or -G compiler profiling option is specified on the command line, the compiler directs the linker to also search:
/usr/lib/libp (for PA32)
/usr/lib/pa20__64/libp (for PA64)
/usr/lib/hpux32/libp (for IPF 32-bit)
/usr/lib/hpux64/libp (for IPF 64-bit)
The default order can be overridden with the LPATH environment variable, the -L linker option, specifies $ORIGIN in the library path, or the +origin option. These are described in Changing the“Changing the Default Library Search Path with -L, LPATH, and $ORIGIN” (page 30) .

Link Order

The linker searches libraries in the order in which they are specified on the command line - the link order. Link order is important in that a library containing an external reference to another library must precede the library containing the definition. This is why libc is typically the last
24 Compiling and Linking Programs on HP-UX
library specified on the linker command line: because the other libraries preceding it in the link order often contain references to libc routines and so must precede it.
NOTE: If multiple definitions of a symbol occur in the specified libraries, ld does not necessarily
choose the first definition. It depends on whether the program is linked with archive libraries, shared libraries, or a combination of both. Depending on link order to resolve such library definition conflicts is risky because it relies on undocumented linker behavior that may change in future releases. (See also “Caution When Mixing Shared and Archive Libraries” (page 118).)

Running the Program

“Loading Programs: exec” (page 25)
“Binding Routines to a Program” (page 25)
“Deferred Binding is the Default” (page 25)
An executable file is created after the program has been compiled and linked. The next step is to run or load the program.

Loading Programs: exec

When you run an executable file created by ld, the program is loaded into memory by the HP-UX program loader, exec. This routine is actually a system call and can be called by other programs to load a new program into the current process space. The exec function performs many tasks; some of the more important ones are:
Determining how to load the executable file by looking at its magic number. (See also“The
a.out File” (page 22).)
Determining where to begin execution of the program - that is, the entry point - For examples
in share-bound executables in dld.so, in archive-bound executables in crt0.o. (See also
“The crt0.o Startup File” (page 21).)
When the program uses shared libraries, the crt0.o startup code invokes the dynamic loader,
which in turn attaches any required shared libraries. If immediate binding was specified at link time, then the libraries are bound immediately. If deferred binding was specified, then libraries are bound as they are referenced. (See also “What are Shared Libraries?” (page
91).)
For details on exec, see the exec(2) page in the HP-UX Reference.

Binding Routines to a Program

Since 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. Attaching a shared library entails mapping the shared library code and data into the process's address space, relocating any pointers in the shared library data that depend on actual virtual addresses, allocating the bss segment, and binding routines and data in the shared library to the program.
The dynamic loader binds only those symbols that are reachable during the execution of the program. This is similar to how archive libraries are treated by the linker; namely, ld pulls in an object file from an archive library only if the object file is needed for program execution.

Deferred Binding is the Default

To accelerate program startup time, routines in a shared library are not bound until referenced. (Data items are always bound at program startup.) This deferred binding of shared library routines distributes the overhead of binding across the execution time of the program and is especially expedient for programs that contain many references that are not likely to be executed. In essence, deferred binding is similar to demand-loading.
Running the Program 25

Linker Thread-Safe Features

The dynamic loader (dld) and its application interface library (libdl) are thread-safe. Also, the linker toolset provides thread local storage support in:
ld - the link editor
crt0.o - the program startup file
Thread local storage (also called thread-specific data) is data specific to a thread. Each thread has its own copy of the data item.
NOTE: Use of the __thread keyword in a shared library prevents that shared library from being
dynamically loaded, that is, loaded by an explicit call to shl_load().
For More Information:
See your HP compiler documentation to learn how to create thread local storage data items
with the _thread compiler directive.
See Programming with Threads on HP-UX for information on threads.

Shared library loading and unloading in multi-threaded applications

The dynamic loader serializes all calls to dlopen, dlclose, shl_load, and shl_unload using a pthread mutex lock. A thread executing dlopen holds this lock, and another thread that wants to execute dlclose (for example), even on a different shared library, must wait for the dlopen in the first thread to release the lock after it is done.
Developers, who use these routines in multi-threaded applications (or shared libraries) and also use mutex locks for synchronizing threads should take note of this behavior to avoid deadlock situations. One example of such a situation is when a shared library initializer creates a new thread that calls dlopen - this would invariably lead to a deadlock in a multi-threaded application. A less trivial example could be as follows. Suppose thread A of an application calls dlopen to load a shared library, libA. Now this shared library has an initializer initA that wants to obtain a mutex lock M. But M is currently held by thread B of the application. Further, thread B wants to load another library, libB and then release the mutex lock M. Now thread B would call either dlopen or shl_load, either of which waits for the dld mutex lock to be released by the dlopen called by thread A. In turn, thread A waits for mutex lock M to be released before it can finish dlopen and release the dld mutex lock. This results in a deadlock.
26 Compiling and Linking Programs on HP-UX
2 Determining How to Link Programs or Libraries (Linker
Tasks)
You have a great deal of control over how the linker links your program or library by using ld command-line options. This chapter describes the tasks you can perform to determine how programs and libraries must link by using the Compiler commands and Linker commands.
“Using the Compiler to Link” (page 28)
“Changing the Default Library Search Path with -Wl, -L” (page 28)
“Getting Verbose Output with -v” (page 29)
“Passing Linker Options from the Compiler Command with -Wl” (page 29)
“Renaming the Output File with -o” (page 29)
“Specifying Libraries with -l” (page 29)
“Suppressing the Link-Edit Phase with -c” (page 30)
“Using Linker Commands” (page 30)
“Linking with the crt0.o Startup File” (page 30)
“Changing the Default Library Search Path with -L, LPATH, and $ORIGIN” (page 30)
“Using $ORIGIN” (page 31)
“Changing the Default Shared Library Binding with -B” (page 32)
“Improving Shared Library Performance with -B symbolic” (page 34)
“Choosing Archive or Shared Libraries with -a” (page 36)
“Linking Shared Libraries with -dynamic” (page 36)
“Linking Archived Libraries with -noshared” (page 37)
“Exporting Symbols with +e” (page 37)
“Exporting Symbols with +ee” (page 38)
“Exporting Symbols from main with -E” (page 38)
“Hiding Symbols from Export with +hideallsymbols” (page 39)
“Hiding Symbols with -h” (page 39)
“ Not Recording Link Time Paths with +nodefaultrapth” (page 41)
“Moving Libraries after Linking with +b” (page 41)
“Moving Libraries After Linking with +s and SHLIB_PATH” (page 43)
“Ignoring Dynamic Path Environment Variables with +noenvvar” (page 43)
“Controlling Archive Library Loading with +[no]forceload” (page 44)
“Passing Linker Options in a file with -c” (page 44)
“Passing Linker Options with LDOPTS” (page 44)
27
“Specifying Libraries with -l and -l:” (page 45)
“Flagging Unsatisfied Symbols with +[no]allowunsats” (page 45)
“Stripping Symbol Table Information from the Output File with -s and -x” (page 46)
“Controlling Output from the Unwind Table with +strip unwind” (page 46)
“Using the IPF Linker with +compat or +std” (page 46)
“Linking in PA-64 Mode with +std” (page 48)
“Linking in PA-32 Mode with +compat” (page 48)
“Changing Mapfiles with -k and +nodefaultmap” (page 48)
“Selecting Verbose Output with +vtype” (page 48)
“Turning on the linkage table protection with +protect” (page 50)
“Allocating Storage for Uninitialized Data with +nobss” (page 50)
“Initializing Floating Point Environment with +FP ” (page 50)
“Allocating Storage for Hidden Common Symbols with +alloc_hidden_commons” (page
51)
“Turn Off Linker Warnings with -w” (page 52)
“Preserving Compiler Generated Relocation Sections with -emit_relocs” (page 52)

Using the Compiler to Link

In many cases, you use your compiler command to compile and link programs. Your compiler uses options that directly affect the linker.

Changing the Default Library Search Path with -Wl, -L

The -L libpath option to ld augments the default search path; that is, it causes ld to search the specified libpath before the default places. The C compiler (cc), the C++ compiler (CC), the POSIX FORTRAN compiler (fort77), and the HP Fortran 90 compiler (f90) recognize the -L option and pass it directly to ld. However, the HP FORTRAN compiler (f77) and Pascal compiler (pc) do not recognize -L; it must be passed to ld with the -Wl option.
Example Using -Wl, -L
For example, to make the f77 compiler search /usr/local/lib to find a locally developed library named liblocal, use this command line:
$ f77 prog.f -Wl,-L,/usr/local/lib -llocal
(The f77 compiler searches /opt/fortran/lib and /usr/lib as default directories.) To make the f90 compiler search /usr/local/lib to find a locally developed library named
liblocal, use this command line:
$ f90 prog.f90 -L/usr/local/lib -llocal
(The f90 compiler searches /opt/fortran90/lib and /usr/lib as default directories.) For the C compiler, use this command line:
$ cc -Aa prog.c -L /usr/local/lib -llocal
The LPATH environment variable provides another way to override the default search path. For details, see “Changing the Default Library Search Path with -L, LPATH, and $ORIGIN” (page 30)
28 Determining How to Link Programs or Libraries (Linker Tasks)

Getting Verbose Output with -v

The -v option makes a compiler display the verbose information. This is useful for viewing how the compiler calls ld. For example, using the -v option with the C compiler shows that it automatically links with libc.
$ cc -v himom.c /opt/ansic/lbin/ecom -ia64abi all -architecture 32 -ext on -lang c \
-exception off -sysdir /usr/include -inline_power 1 -link_type dynamic \
-fpeval float -tls_dyn on -target_os 11.23 -- sys_include /usr/include \
-D__hpux -D__unix -D__ia64=1 -D_BIG_ENDIAN=1 -D_ILP32 -D__HP_cc=60200 \
-D__STDC_EXT__ -D_HPUX_SOURCE -D_INCLUDE_LONGLONG -D_INLINE_ASM \
-D_BIND_LIBCALLS -D_Math_errhandling=MATH_ERREXCEPT -D_FLT_EVAL_METHOD=0 \
-ucode hdriver=optlevel%1% -plusolistoption -O106const! -plusolistoption \
-O113moderate! -plusooption -Oq01,al,ag,cn,sz,ic,vo,Mf,Po,es,rs,Rf,Pr,sp,\ in,cl,om,vc,pi,fa,pe,rr,pa,pv,nf,cp,1x,Pg,ug,1u,lb,uj,dn,sg,pt,kt,em,np,\ ar,rp,dl,fs,bp,wp,pc,mp,lr,cx,cr,pi,so,Rc,fa,ft,fe,ap,st,lc,Bl,sr,ib,pl,\ sd,ll,rl,dl,Lt,ol,fl,lm,ts,rd,dp,If! himom.c LPATH=/usr/lib/hpux32:/opt/langtools/lib/hpux32 /usr/ccs/bin/ld -o a.out -u__exit -umain himom.o -lc removing /var/tmp/AAAa17931 removing himom.o

Passing Linker Options from the Compiler Command with -Wl

The -Wl option passes options and arguments to ld directly, without the compiler interpreting the options. Its syntax is:
-Wl,arg1 [,arg2]...
where each argn is an option or argument passed to the linker. For example, to make ld use the archive version of a library instead of the shared, you must specify -a archive on the ld command line before the library.
Example Using -Wl
The command for instructing the linker to use an archive version of libm from the C command line is:
$ cc -Aa mathprog.c -Wl,-a,archive,-lm,-a,default
The command for instructing the linker to use an archive version of libm is:
$ $ ld /opt/langtools/lib/crt0.o mathprog.o -a archive -lm
-a default -lc

Renaming the Output File with -o

The -o name option causes ld to name the output file name instead of a.out. For example, to compile a C program prog.c and name the resulting file sum_num:
$ cc -Aa -o sum_num prog.c //Compile using -o option. $ sum_num //Run the program. Enter a number to sum: 5 The sum of 1 to 5: 15

Specifying Libraries with -l

Sometimes programs call routines not contained in the default libraries. In such cases you must explicitly specify the necessary libraries on the compile line with the -l option. The compilers pass
-l options directly to the linker before any default libraries, such as libc. For example, if a C program calls library routines in the curses library (libcurses), you must
specify -lcurses on the cc command line: .
Using the Compiler to Link 29
$ cc -Aa -v cursesprog.c -lcurses ... /usr/ccs/bin/ld /opt/langtools/lib/crt0.o cursesprog.o -lcurses \
-u main -lc cc: informational note 413: Entering Link editor.
Linking with the crt0.o Startup File in 32-bit mode (PA-RISC)
Notice also, in the above example, that the compiler linked cursesprog.o with the file /opt/langtools/lib/crt0.o. This file contains object code that performs tasks which must be executed when a program starts running - for example, retrieving any arguments specified on the command line when the program is invoked. For details on this file, see “The crt0.o Startup
File” (page 21)

Suppressing the Link-Edit Phase with -c

The -c compiler option suppresses the link-edit phase. That is, the compiler generates only the .o files and not the a.out file. This is useful when compiling source files that contain only subprograms and data. These may be linked later with other object files, or placed in an archive or shared library. The resulting object files can then be specified on the compiler command line, just like source files. For example:
$ f90 -c func.f //Produce .o for func.f. $ ls func.o func.o $ f90 main.f func.o //Compile main.f with func.o $ a.out //Run it to verify it worked.

Using Linker Commands

This section describes linker commands for the 32-bit and 64-bit linker
NOTE: Unless otherwise noted, all examples show 32-bit behavior.

Linking with the crt0.o Startup File

In default mode, you need not include crt0.o on the link line. However, you must include crt0.o on the link line for all fully archive links (ld -noshared) and in compatibility mode (+compat). You need not include the crt0.o startup file on the ld command line for shared bound links. The dynamic loader does some of the startup duties previously done by crt0.o.
See “The crt0.o Startup File” (page 21), and crt0(3) manpage for more information.

Changing the Default Library Search Path with -L, LPATH, and $ORIGIN

You can change or override the default linker search path by using the LPATH environment variable, the -L linker option, or the +origin linker option.
Overriding the Default Linker Search Path with LPATH
The LPATH environment variable allows you to specify which directories ld should search. If LPATH is not set, ld searches the default directory /usr/lib. If LPATH is set, ld searches only the directories specified in LPATH; the default directories are not searched unless they are specified in LPATH.
If set, LPATH must contain a list of colon-separated directory path names that ld must search. For example, to include /usr/local/lib in the search path after the default directories, set LPATH as follows:
30 Determining How to Link Programs or Libraries (Linker Tasks)
Loading...
+ 198 hidden pages