0% found this document useful (0 votes)
2K views542 pages

RPG Programmers Guide

WebSphere(r)(r) Development Studio: ILE RPG Programmer's Guide Version 5 SC09-2507-05. This edition applies to Version 5, Release 3, Modification Level 0, of websphere Development Studio for iSeries(tm) (5722-wds) this edition applies only to reduced instruction set computer (RISC) systems.

Uploaded by

api-3800226
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views542 pages

RPG Programmers Guide

WebSphere(r)(r) Development Studio: ILE RPG Programmer's Guide Version 5 SC09-2507-05. This edition applies to Version 5, Release 3, Modification Level 0, of websphere Development Studio for iSeries(tm) (5722-wds) this edition applies only to reduced instruction set computer (RISC) systems.

Uploaded by

api-3800226
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 542

򔻐򗗠򙳰

ERserver
iSeries
WebSphere®® Development Studio:
ILE RPG Programmer’s Guide
Version 5
SC09-2507-05
򔻐򗗠򙳰
ERserver
iSeries
WebSphere®® Development Studio:
ILE RPG Programmer’s Guide
Version 5
SC09-2507-05
Note!
Before using this information and the product it supports, be sure to read the general information
under “Notices” on page 481.

Sixth Edition (May 2004)


This edition applies to Version 5, Release 3, Modification Level 0, of IBM WebSphere Development Studio for
iSeries™ (5722-WDS), ILE RPG compiler, and to all subsequent releases and modifications until otherwise indicated
in new editions. This edition applies only to reduced instruction set computer (RISC) systems.
This edition replaces SC09-2507-04.
Order publications through your IBM representative or the IBM branch office serving your locality. Publications are
not stocked at the address that is given below.
IBM welcomes your comments. You can send your comments to:
# IBM Canada Ltd. Laboratory
# Information Development
# 8200 Warden Avenue
# Markham, Ontario, Canada L6G 1C7
You can also send your comments by FAX (attention: RCF Coordinator), or you can send your comments
electronically to IBM. See “How to Send Your Comments” for a description of the methods.
When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information in any
way it believes appropriate without incurring any obligation to you.
© Copyright International Business Machines Corporation 1994, 2004. All rights reserved.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract
with IBM Corp.
Contents
About This Guide . . . . . . . . . . ix Chapter 4. Creating an Application
Who Should Use This Guide . . . . . . . . . ix Using Multiple Procedures . . . . . . 33
Prerequisite and Related Information . . . . . . ix A Multiple Procedures Module — Overview . . . 33
How to Send Your Comments . . . . . . . . x Main Procedures and Subprocedures . . . . . 33
What's New . . . . . . . . . . . . . . x Prototyped Calls . . . . . . . . . . . . 34
Changes to this Guide Since V5R2 and V5R1 . . . xi Example of Module with Multiple Procedures . . . 36
| What's New This Release? . . . . . . . . . xi The Entire ARRSRPT Program . . . . . . . 40
# What's New in V5R2? . . . . . . . . . . . xv Coding Considerations . . . . . . . . . . 44
What's New in V5R1? . . . . . . . . . . xviii General Considerations . . . . . . . . . 45
What's New in V4R4? . . . . . . . . . . xxiii Program Creation . . . . . . . . . . . 45
What's New in V4R2? . . . . . . . . . . xxvii Main Procedure Considerations . . . . . . . 45
What's New in V3R7? . . . . . . . . . . xxxi Subprocedure Considerations . . . . . . . 46
What's New in V3R6/V3R2? . . . . . . . . xxxv For Further Information . . . . . . . . . . 46
Main Procedures . . . . . . . . . . . 46
Part 1. ILE RPG Introduction. . . . . 1 Subprocedures . . . . . . . . . . . . 46
Prototyped Call . . . . . . . . . . . . 47
Chapter 1. Overview of the RPG IV
Programming Language . . . . . . . . 3 Part 2. Creating and Running an ILE
RPG IV Specifications . . . . . . . . . . . 3 RPG Application . . . . . . . . . . 49
Cycle Programming . . . . . . . . . . . . 4
Subprocedure logic . . . . . . . . . . . 5 Chapter 5. Using Source Files . . . . . 51
Indicators . . . . . . . . . . . . . . . 5 Using Source Physical Files . . . . . . . . . 51
Operation Codes . . . . . . . . . . . . . 6 Creating a Library and Source Physical File . . 51
Example of an ILE RPG Program . . . . . . . 6 Using the Source Entry Utility (SEU) . . . . . 52
Using the OS/400 System . . . . . . . . . 12 Using SQL Statements . . . . . . . . . . 55
Interacting with the System . . . . . . . . 12 # Using IFS Source Files . . . . . . . . . . . 56
WebSphere Development Studio for iSeries . . . . 13 # Include files . . . . . . . . . . . . . 56
WebSphere Development Studio Client for iSeries 14
Chapter 6. Creating a Program with the
Chapter 2. RPG Programming in ILE . . 17 CRTBNDRPG Command . . . . . . . 59
Program Creation . . . . . . . . . . . . 17
Using the CRTBNDRPG Command . . . . . . 59
Program Management . . . . . . . . . . . 19
Creating a Program for Source Debugging . . . 61
Program Call . . . . . . . . . . . . . . 19
Creating a Program with Static Binding . . . . 62
Source Debugging . . . . . . . . . . . . 20
Creating an OPM-Compatible Program Object . . 63
Bindable APIs . . . . . . . . . . . . . 20
Using a Compiler Listing . . . . . . . . . . 65
Multithreaded Applications . . . . . . . . . 21
Obtaining a Compiler Listing . . . . . . . 65
Customizing a Compiler Listing . . . . . . 66
Chapter 3. Program Creation Strategies 23 Correcting Compilation Errors . . . . . . . 68
Strategy 1: OPM-Compatible Application . . . . 23 Correcting Run-time Errors . . . . . . . . 70
Method . . . . . . . . . . . . . . . 23 Using a Compiler Listing for Maintenance . . . 71
Example of OPM-Compatible Program . . . . 23 Accessing the RETURNCODE Data Area . . . . 71
Related Information . . . . . . . . . . 24
Strategy 2: ILE Program Using CRTBNDRPG . . . 25 Chapter 7. Creating a Program with the
Method . . . . . . . . . . . . . . . 25
Example of ILE Program Using CRTBNDRPG . . 25
CRTRPGMOD and CRTPGM
Related Information . . . . . . . . . . 27 Commands . . . . . . . . . . . . . 75
Strategy 3: ILE Application Using CRTRPGMOD . . 27 Creating a Module Object . . . . . . . . . 75
Method . . . . . . . . . . . . . . . 28 Using the CRTRPGMOD Command . . . . . 76
Single-Language ILE Application Scenario . . . 28 Creating a Module for Source Debugging . . . 80
Mixed-Language ILE Application Scenario . . . 29 Additional Examples . . . . . . . . . . 82
Advanced Application Scenario . . . . . . . 30 Behavior of Bound ILE RPG Modules . . . . 82
Related Information . . . . . . . . . . 31 Related CL Commands . . . . . . . . . 82
A Strategy to Avoid. . . . . . . . . . . . 31 Binding Modules into a Program . . . . . . . 82
Using the CRTPGM Command . . . . . . . 84

© Copyright IBM Corp. 1994, 2004 iii


Additional Examples . . . . . . . . . . 86 Omitting Parameters . . . . . . . . . . 140
Related CL Commands . . . . . . . . . 86 Checking for the Number of Passed Parameters 142
Using a Binder Listing . . . . . . . . . . . 87 Passing Less Data Than Required . . . . . 147
Changing a Module or Program . . . . . . . 88 Order of Evaluation . . . . . . . . . . 148
Using the UPDPGM Command . . . . . . . 88 Interlanguage Calls . . . . . . . . . . 148
Changing the Optimization Level . . . . . . 89 Interlanguage Calling Considerations . . . . . 149
Removing Observability . . . . . . . . . 89 Using the Fixed-Form Call Operations . . . . . 150
Reducing an Object’s Size . . . . . . . . 90 Examples of CALL and CALLB . . . . . . 151
Passing Parameters Using PARM and PLIST . . 151
Chapter 8. Creating a Service Program 91 Returning from a Called Program or Procedure . . 153
Service Program Overview . . . . . . . . . 91 Returning from a Main Procedure . . . . . 153
Strategies for Creating Service Programs . . . . . 92 Returning from a Subprocedure . . . . . . 155
Creating a Service Program Using CRTSRVPGM . . 92 Returning using ILE Bindable APIs . . . . . 156
Changing A Service Program . . . . . . . 93 Using Bindable APIs . . . . . . . . . . . 156
Related CL commands . . . . . . . . . . 93 Examples of Using Bindable APIs . . . . . 157
Sample Service Program . . . . . . . . . . 93 Calling a Graphics Routine . . . . . . . . . 158
Creating the Service Program . . . . . . . 97 Calling Special Routines . . . . . . . . . . 158
Binding to a Program . . . . . . . . . . 98 Multithreading Considerations . . . . . . . 158
Updating the Service Program . . . . . . . 99 How to Share Data Across More Than One
Sample Binder Listing . . . . . . . . . 100 Module . . . . . . . . . . . . . . 159
How to Avoid Deadlock Between Modules . . 160
Chapter 9. Running a Program . . . . 103
Running a Program Using the CL CALL Command 103 Chapter 11. RPG and the eBusiness
Passing Parameters using the CL CALL World . . . . . . . . . . . . . . . 163
Command . . . . . . . . . . . . . 103 RPG and XML . . . . . . . . . . . . . 163
Running a Program From a Menu-Driven RPG and MQSeries, V5.2 . . . . . . . . . 163
Application . . . . . . . . . . . . . . 105 RPG and Java . . . . . . . . . . . . . 163
Running a Program Using a User-Created Introduction to Java and RPG . . . . . . . 163
Command . . . . . . . . . . . . . . 108 Calling Java Methods from ILE RPG . . . . 167
Replying to Run-Time Inquiry Messages . . . . 108 | Calling methods in your own classes . . . . 172
Ending an ILE Program . . . . . . . . . . 109 | Controlling how the Java Virtual Machine is set
Managing Activation Groups . . . . . . . . 110 | up . . . . . . . . . . . . . . . . 173
Specifying an Activation Group . . . . . . 110 RPG Native Methods . . . . . . . . . . 174
Running in the OPM Default Activation Group 111 Coding Errors when calling Java from RPG . . 176
Maintaining OPM RPG/400® and ILE RPG Additional RPG Coding for Using Java . . . . 178
Program Compatibility . . . . . . . . . 111 Additional Considerations . . . . . . . . 186
Deleting an Activation Group . . . . . . . 112 Advanced JNI Coding . . . . . . . . . 188
Reclaim Resources Command . . . . . . . 112 # Calling RPG programs from Java using PCML 192
Managing Dynamically-Allocated Storage . . . . 113
Managing the Default Heap Using RPG Part 3. Debugging and Exception
Operations . . . . . . . . . . . . . 113
Heap Storage Problems . . . . . . . . . 119 Handling . . . . . . . . . . . . . 195
Managing Your Own Heap Using ILE Bindable
APIs . . . . . . . . . . . . . . . 120 Chapter 12. Debugging Programs . . . 197
The ILE Source Debugger . . . . . . . . . 198
Chapter 10. Calling Programs and Debug Commands . . . . . . . . . . 198
Procedures . . . . . . . . . . . . 129 Preparing a Program for Debugging . . . . . . 200
Creating a Root Source View . . . . . . . 201
Program/Procedure Call Overview . . . . . . 129
Creating a COPY Source View . . . . . . . 202
Calling Programs . . . . . . . . . . . 130
Creating a Listing View . . . . . . . . . 203
Calling Procedures . . . . . . . . . . 130
Creating a Statement View . . . . . . . . 203
The Call Stack . . . . . . . . . . . . 131
Starting the ILE Source Debugger . . . . . . 204
Recursive Calls . . . . . . . . . . . . 131
STRDBG Example . . . . . . . . . . . 205
Parameter-Passing Considerations . . . . . 133
Setting Debug Options . . . . . . . . . 206
Using a Prototyped Call . . . . . . . . . . 134
Adding/Removing Programs from a Debug
Using the CALLP Operation . . . . . . . 135
Session . . . . . . . . . . . . . . . 206
Calling within an Expression . . . . . . . 135
Example of Adding a Service Program to a
Examples of Free-Form Call . . . . . . . 136
Debug Session . . . . . . . . . . . . 207
Passing Prototyped Parameters . . . . . . . 136
Example of Removing ILE Programs from a
Parameter Passing Styles . . . . . . . . 136
Debug Session . . . . . . . . . . . . 207
Using Operational Descriptors . . . . . . . 139

iv ILE RPG Programmer’s Guide


Viewing the Program Source . . . . . . . . 208 ILE Condition Handlers . . . . . . . . . . 272
Viewing a Different Module . . . . . . . 209 Using a Condition Handler . . . . . . . . 272
Changing the View of a Module . . . . . . 210 Using Cancel Handlers . . . . . . . . . . 279
Setting and Removing Breakpoints . . . . . . 211 Problems when ILE CL Monitors for Notify and
Setting and Removing Unconditional Job Status Messages . . . . . . . . . . . . 282
Breakpoints . . . . . . . . . . . . . 212
Setting and Removing Unconditional Thread Chapter 14. Obtaining a Dump . . . . 285
Breakpoints . . . . . . . . . . . . . 214 Obtaining an ILE RPG Formatted Dump . . . . 285
Setting and Removing Conditional Job Using the DUMP Operation Code . . . . . . 286
Breakpoints . . . . . . . . . . . . . 215 Example of a Formatted Dump . . . . . . . 286
National Language Sort Sequence (NLSS) . . . 217
Setting and Removing Job Breakpoints Using
Statement Numbers . . . . . . . . . . 218 Part 4. Working with Files and
Setting and Removing Conditional Thread Devices . . . . . . . . . . . . . 293
Breakpoints . . . . . . . . . . . . . 220
Removing All Job and Thread Breakpoints . . 221 Chapter 15. Defining Files . . . . . . 295
Setting and Removing Watch Conditions . . . . 221 Associating Files with Input/Output Devices . . . 295
Characteristics of Watches . . . . . . . . 221 Naming Files . . . . . . . . . . . . . 297
Setting Watch Conditions . . . . . . . . 222 Types of File Descriptions . . . . . . . . . 297
Displaying Active Watches . . . . . . . . 224 Using Files with External-Description as
Removing Watch Conditions . . . . . . . 224 Program-Described . . . . . . . . . . 298
Example of Setting a Watch Condition . . . . . 225 Example of Some Typical Relationships between
Stepping Through the Program Object . . . . . 226 Programs and Files . . . . . . . . . . 298
Stepping Over Call Statements . . . . . . 227 Defining Externally Described Files . . . . . . 299
Stepping Into Call Statements . . . . . . . 228 Renaming Record-Format Names . . . . . . 299
Displaying Data and Expressions . . . . . . . 231 Renaming Field Names . . . . . . . . . 300
Unexpected Results when Evaluating Variables 233 Ignoring Record Formats . . . . . . . . 300
Displaying the Contents of an Array . . . . 234 Using Input Specifications to Modify an
Displaying the Contents of a Table . . . . . 234 External Description . . . . . . . . . . 301
Displaying Data Structures . . . . . . . . 235 Using Output Specifications . . . . . . . 303
Displaying Indicators . . . . . . . . . . 236 Level Checking . . . . . . . . . . . . 304
Displaying Fields as Hexadecimal Values . . . 237 Defining Program-Described Files . . . . . . 305
Displaying Fields in Character Format . . . . 237 Data Management Operations and ILE RPG I/O
Displaying UCS-2 Data . . . . . . . . . 238 Operations . . . . . . . . . . . . . . 305
Displaying Variable-Length Fields . . . . . 238
Displaying Data Addressed by Pointers . . . 238
Displaying Null-Capable Fields . . . . . . 238
Chapter 16. General File
Using Debug Built-In Functions . . . . . . 238 Considerations . . . . . . . . . . . 307
Changing the Value of Fields . . . . . . . . 240 Overriding and Redirecting File Input and Output 307
Displaying Attributes of a Field . . . . . . . 242 Example of Redirecting File Input and Output 308
Equating a Name with a Field, Expression, or File Locking . . . . . . . . . . . . . . 309
Command . . . . . . . . . . . . . . 243 Record Locking . . . . . . . . . . . . . 310
Source Debug National Language Support for ILE Sharing an Open Data Path . . . . . . . . . 311
RPG . . . . . . . . . . . . . . . . 244 Spooling . . . . . . . . . . . . . . . 312
Sample Source for Debug Examples . . . . . . 244 Output Spooling . . . . . . . . . . . 312
SRTSEQ/ALTSEQ in an RPG Program versus a
Chapter 13. Handling Exceptions . . . 251 DDS File . . . . . . . . . . . . . . . 313
Exception Handling Overview . . . . . . . . 251
ILE RPG Exception Handling . . . . . . . 254 Chapter 17. Accessing Database Files 315
Using Exception Handlers . . . . . . . . . 256 Database Files . . . . . . . . . . . . . 315
Exception Handler Priority . . . . . . . . 257 Physical Files and Logical Files . . . . . . 315
Nested Exceptions . . . . . . . . . . . 257 Data Files and Source Files . . . . . . . . 315
Unhandled Exceptions . . . . . . . . . 257 Using Externally Described Disk Files . . . . . 316
Optimization Considerations . . . . . . . 259 Record Format Specifications . . . . . . . 316
Using RPG-Specific Handlers . . . . . . . . 260 Access Path . . . . . . . . . . . . . 316
Specifying Error Indicators or the ’E’ Operation Valid Keys for a Record or File . . . . . . 319
Code Extender . . . . . . . . . . . . 260 Record Blocking and Unblocking . . . . . . 321
Using a MONITOR Group . . . . . . . . 261 Using Program-Described Disk Files . . . . . . 322
Using an Error Subroutine . . . . . . . . 263 Indexed File . . . . . . . . . . . . . 322
Specifying a Return Point in the ENDSR Sequential File . . . . . . . . . . . . 324
Operation . . . . . . . . . . . . . 271 Record Address File . . . . . . . . . . 325

Contents v
Methods for Processing Disk Files . . . . . . 326 File Maintenance . . . . . . . . . . . . 379
Consecutive Processing . . . . . . . . . 326 CUSMSTL1: DDS for a Logical File . . . . . 380
Sequential-by-Key Processing . . . . . . . 327 MNTMENU: DDS for a Display Device File . . 381
Random-by-Key Processing . . . . . . . . 332 CUSMNT: RPG Source . . . . . . . . . 383
Sequential-within-Limits Processing . . . . . 334 Search by Zip Code . . . . . . . . . . . 390
Relative-Record-Number Processing . . . . . 336 CUSMSTL2: DDS for a Logical File . . . . . 391
Valid File Operations . . . . . . . . . . . 337 SZIPMENU: DDS for a Display Device File . . 392
Using Commitment Control . . . . . . . . 339 SCHZIP: RPG Source . . . . . . . . . . 394
Starting and Ending Commitment Control . . . 340 Search and Inquiry by Name . . . . . . . . 398
Specifying Files for Commitment Control . . . 342 CUSMSTL3: DDS for a Logical File . . . . . 399
Using the COMMIT Operation . . . . . . 342 SNAMMENU: DDS for a Display Device File 400
Specifying Conditional Commitment Control 344 SCHNAM: RPG Source . . . . . . . . . 403
Commitment Control in the Program Cycle . . 344
DDM Files . . . . . . . . . . . . . . 345
Part 5. Appendixes . . . . . . . . 409
Using Pre-V3R1 DDM Files . . . . . . . . 345

Chapter 18. Accessing Externally Appendix A. Behavioral Differences


Attached Devices. . . . . . . . . . 347 Between OPM RPG/400 and ILE RPG
Types of Device Files . . . . . . . . . . . 347 for AS/400 . . . . . . . . . . . . . 411
Accessing Printer Devices . . . . . . . . . 347 Compiling . . . . . . . . . . . . . . 411
Specifying PRINTER Files . . . . . . . . 348 Running . . . . . . . . . . . . . . . 411
Handling Page Overflow . . . . . . . . 348 Debugging and Exception Handling . . . . . . 412
Using the Fetch-Overflow Routine in I/O. . . . . . . . . . . . . . . . . 413
Program-Described Files . . . . . . . . . 351 DBCS Data in Character Fields . . . . . . . 415
Changing Forms Control Information in a
Program-Described File . . . . . . . . . 354 Appendix B. Using the RPG III to RPG
Accessing Tape Devices . . . . . . . . . . 356 IV Conversion Aid . . . . . . . . . 417
Accessing Display Devices . . . . . . . . . 356 Conversion Overview . . . . . . . . . . 417
Using Sequential Files . . . . . . . . . . 356 File Considerations . . . . . . . . . . 417
Specifying a Sequential File. . . . . . . . 356 The Log File . . . . . . . . . . . . . 419
Using SPECIAL Files . . . . . . . . . . . 357 Conversion Aid Tool Requirements . . . . . 419
Example of Using a Special File . . . . . . 359 What the Conversion Aid Won’t Do . . . . . 419
Converting Your Source . . . . . . . . . . 420
Chapter 19. Using WORKSTN Files 361 The CVTRPGSRC Command . . . . . . . 421
Intersystem Communications Function . . . . . 361 Converting a Member Using the Defaults . . . 425
Using Externally Described WORKSTN Files . . . 361 Converting All Members in a File . . . . . 425
Specifying Function Key Indicators on Display Converting Some Members in a File . . . . . 426
Device Files . . . . . . . . . . . . . 363 Performing a Trial Conversion . . . . . . . 426
Specifying Command Keys on Display Device Obtaining Conversion Reports . . . . . . . 427
Files . . . . . . . . . . . . . . . 364 Converting Auto Report Source Members . . . 427
Processing an Externally Described WORKSTN Converting Source Members with Embedded
File . . . . . . . . . . . . . . . . 364 SQL . . . . . . . . . . . . . . . 428
Using Subfiles . . . . . . . . . . . . 365 Inserting Specification Templates . . . . . . 428
Using Program-Described WORKSTN Files . . . 368 Converting Source from a Data File . . . . . 428
Using a Program-Described WORKSTN File Example of Source Conversion . . . . . . . 428
with a Format Name . . . . . . . . . . 369 Analyzing Your Conversion . . . . . . . . 431
Using a Program-Described WORKSTN File Using the Conversion Report . . . . . . . 431
without a Format Name . . . . . . . . . 370 Using the Log File . . . . . . . . . . . 433
Valid WORKSTN File Operations . . . . . . . 371 Resolving Conversion Problems . . . . . . . 435
EXFMT Operation . . . . . . . . . . . 371 Compilation Errors in Existing RPG III Code 436
READ Operation . . . . . . . . . . . 371 Unsupported RPG III Features. . . . . . . 436
WRITE Operation . . . . . . . . . . . 372 Use of the /COPY Compiler Directive . . . . 436
Multiple-Device Files . . . . . . . . . . . 372 Use of Externally Described Data Structures . . 439
Run-time Differences . . . . . . . . . . 441
Chapter 20. Example of an Interactive
Application . . . . . . . . . . . . 375 Appendix C. The Create Commands 443
Database Physical File . . . . . . . . . . 375 Using CL Commands . . . . . . . . . . . 443
Main Menu Inquiry . . . . . . . . . . . 376 How to Interpret Syntax Diagrams . . . . . 443
MAINMENU: DDS for a Display Device File 376 CRTBNDRPG Command . . . . . . . . . 444
CUSMAIN: RPG Source . . . . . . . . . 378 Description of the CRTBNDRPG Command . . 447

vi ILE RPG Programmer’s Guide


CRTRPGMOD Command . . . . . . . . . 461 External References List . . . . . . . . . 477
Description of the CRTRPGMOD command . . 463 Message Summary . . . . . . . . . . 478
Final Summary . . . . . . . . . . . . 478
Appendix D. Compiler Listings . . . . 465 Code Generation and Binding Errors . . . . 479
Reading a Compiler Listing . . . . . . . . 466
Prologue . . . . . . . . . . . . . . 466 Notices . . . . . . . . . . . . . . 481
Source Section . . . . . . . . . . . . 468 Programming Interface Information . . . . . . 482
Additional Diagnostic Messages . . . . . . 473 Trademarks and Service Marks . . . . . . . 482
Output Buffer Positions . . . . . . . . . 474
/COPY Member Table . . . . . . . . . 474 Bibliography . . . . . . . . . . . . 485
Compile-Time Data . . . . . . . . . . 474
Key Field Information . . . . . . . . . 475
Index . . . . . . . . . . . . . . . 487
Cross-Reference Table . . . . . . . . . 476

Contents vii
viii ILE RPG Programmer’s Guide
About This Guide
This guide provides information that shows how to use the ILE RPG compiler (ILE
RPG) in the Integrated Language Environment. ILE RPG is an implementation of
the RPG IV language on the iSeries server with the Operating System/400
(OS/400) operating system. Use this guide to create and run ILE applications from
RPG IV source.

This guide shows how to:


v Enter RPG IV source statements
v Create modules
v Bind modules
v Run an ILE program
v Call other objects
v Debug an ILE program
v Handle exceptions
v Define and process files
v Access devices
v Convert programs from an RPG III format to RPG IV format
v Read compiler listings

Who Should Use This Guide


This guide is for programmers who are familiar with the RPG programming
language, but who want to learn how to use it in the ILE framework. This guide is
also for programmers who want to convert programs from the RPG III to the RPG
IV format. It is designed to guide you in the use of the ILE RPG compiler on the
iSeries system.

Though this guide shows how to use the RPG IV in an ILE framework, it does not
provide detailed information on RPG IV specifications and operations. For a
detailed description of the language, see the WebSphere Development Studio: ILE
RPG Reference, SC09-2508-04.

Before using this guide, you should:


v Know how to use applicable iSeries server menus and displays, or Control
Language (CL) commands.
v Have the appropriate authority to the CL commands and objects described here.
v Have a firm understanding of ILE as described in detail in the ILE Concepts,
SC41-5606-06.

Prerequisite and Related Information


Use the iSeries Information Center as your starting point for looking up iSeries and
AS/400e technical information. You can access the Information Center in two ways:
v From the following Web site:
http://www.ibm.com/eserver/iseries/infocenter
v From CD-ROMs that ship with your Operating System/400 order:

© Copyright IBM Corp. 1994, 2004 ix


iSeries Information Center, SK3T-4091-02. This package also includes the PDF
versions of iSeries manuals, iSeries Information Center: Supplemental Manuals,
SK3T-4092-01, which replaces the Softcopy Library CD-ROM.

The iSeries Information Center contains advisors and important topics such as CL
commands, system application programming interfaces (APIs), logical partitions,
clustering, Java , TCP/IP, Web serving, and secured networks. It also includes links
to related IBM Redbooks and Internet links to other IBM Web sites such as the
Technical Studio and the IBM home page.

The manuals that are most relevant to the ILE RPG compiler are listed in the
“Bibliography” on page 485.

How to Send Your Comments


Your feedback is important in helping to provide the most accurate and
high-quality information. IBM welcomes any comments about this book or any
other iSeries documentation.
v If you prefer to send comments by mail, use the the following address:
# IBM Canada Ltd. Laboratory
# Information Development
# 8200 Warden Avenue
# Markham, Ontario, Canada L6G 1C7

# If you are mailing a readers’ comment form from a country other than the
United States, you can give the form to the local IBM branch office or IBM
representative for postage-paid mailing.
v If you prefer to send comments by FAX, use the following number:
1–845–491–7727
v If you prefer to send comments electronically, use one of these e-mail addresses:
– Comments on books:
[email protected]
– Comments on the Information Center:
[email protected]
Be sure to include the following:
v The name of the book.
v The publication number of the book.
v The page number or topic to which your comment applies.

What's New
There have been several releases of RPG IV since the first V3R1 release. The
following is a list of enhancements made for each release since V3R1 up to the
current release:
v “What's New This Release?” on page xi
v “What's New in V5R2?” on page xv
v “What's New in V5R1?” on page xviii
v “What's New in V4R4?” on page xxiii
v “What's New in V4R2?” on page xxvii
v “What's New in V3R7?” on page xxxi
v “What's New in V3R6/V3R2?” on page xxxv

x ILE RPG Programmer’s Guide


You can use this section to link to and learn about new RPG IV functions.

| Note: The information for this product is up-to-date with the V5R3 release of RPG
| IV. If you are using a previous release of the compiler, you will need to
| determine what functions are supported on your system. For example, if
| you are using a V5R1 system, the functions new to the V5R3 release will not
| be supported.

Changes to this Guide Since V5R2 and V5R1


This V5R3 guide, WebSphere Development Studio: ILE RPG Programmer’s Guide,
SC09-2507-05 differs in many places from the V5R2 guide, SC09-2507-04, and the
V5R1 guide, SC09–2507–03. Most of the changes are related to the enhancements
that have been made since previous releases; others reflect minor technical
corrections. To assist you in using this manual, technical changes and
enhancements are noted with a symbol in the margin:.
v Enhancements for V5R3 are marked with a vertical bar (|).
v Enhancements for V5R2 are marked with a pound sign (#).

Note: Many of the examples included in this guide have been modified to
″free-form″, rather than ″traditional″ coding style. These changed examples
have not been marked. See WebSphere Development Studio: ILE RPG Reference
for detailed explanation of the differences between the two coding styles.

| What's New This Release?


| The following list describes the enhancements made to ILE RPG in V5R3:
| v New builtin function %SUBARR:
| New builtin function %SUBARR allows assignment to a sub-array or returning a
| sub-array as a value.
| Along with the existing %LOOKUP builtin function, this enhancements enables
| the implementation of dynamically sized arrays with a varying number of
| elements.
| %SUBARR(array : start) specifies array elements array(start) to the end of the
| array
| %SUBARR(array : start : num) specifies array elements array(start) to array(start
| + num - 1)
| Example:
| // Copy part of an array to another array:
| resultArr = %subarr(array1:start:num);
| // Copy part of an array to part of another array:
| %subarr(Array1:x:y) = %subarr(Array2:m:n);
| // Sort part of an array
| sorta %subarr(Array3:x:y);
|
| // Sum part of an array
| sum = %xfoot(%subarr(Array4:x:y));
| v The SORTA operation code is enhanced to allow sorting of partial arrays.
| When %SUBARR is specified in factor 2, the sort only affects the partial array
| indicated by the %SUBARR builtin function.
| v Direct conversion of date/time/timestamp to numeric, using %DEC:
| %DEC is enhanced to allow the first parameter to be a date, time or timestamp,
| and the optional second parameter to specify the format of the resulting numeric
| value.

About This Guide xi


Changes to this Guide Since V5R1 and V5R2

| Example:
| D numDdMmYy s 6p 0
| D date s d datfmt(*jul)
| date = D’2003-08-21’;
| numDdMmYy = %dec(date : *dmy);
| // now numDdMmYy = 210803
| v Control specification CCSID(*CHAR : *JOBRUN) for correct conversion of
| character data at runtime:
| The Control specification CCSID keyword is enhanced to allow a first parameter
| of *CHAR. When the first parameter is *CHAR, the second parameter must be
| *JOBRUN. CCSID(*CHAR : *JOBRUN) controls the way character data is
| converted to UCS-2 at runtime. When CCSID(*CHAR:*JOBRUN) is specified,
| character data will be assumed to be in the job CCSID; when CCSID(*CHAR :
| *JOBRUN) is not specified, character data will be assumed to be in the
| mixed-byte CCSID related to the job CCSID.
| v Second parameter for %TRIM, %TRIMR and %TRIML indicating what
| characters to trim:
| %TRIM is enhanced to allow an optional second parameter giving the list of
| characters to be trimmed.
| Example:
| trimchars = ’*-.’;
| data = ’***a-b-c-.’
| result = %trim(data : trimchars);
| // now result = ’a-b-c’. All * - and . were trimmed from the ends of the data
| v New prototype option OPTIONS(*TRIM) to pass a trimmed parameter:
| When OPTIONS(*TRIM) is specified on a prototyped parameter, the data that is
| passed be trimmed of leading and trailing blanks. OPTIONS(*TRIM) is valid for
| character, UCS-2 and graphic parameters defined with CONST or VALUE. It is
| also valid for pointer parameters defined with OPTIONS(*STRING). With
| OPTIONS(*STRING : *TRIM), the passed data will be trimmed even if a pointer
| is passed on the call.
| Example:
| D proc pr
| D parm1 5a const options(*trim)
| D parm2 5a const options(*trim : *rightadj)
| D parm3 5a const varying options(*trim)
| D parm4 * value options(*string : *trim)
| D parm5 * value options(*string : *trim)
| D ptr s *
| D data s 10a
| D fld1 s 5a
|
| /free
| data = ’ rst ’ + x’00’;
| ptr = %addr(data);
|
| proc (’ xyz ’ : ’ @#$ ’ : ’ 123 ’ : ’ abc ’ : ptr);
| // the called procedure receives the following parameters
| // parm1 = ’xyz ’
| // parm2 = ’ @#$’
| // parm3 = ’123’
| // parm4 = a pointer to ’abc.’ (where . is x’00’)
| // parm5 = a pointer to ’rst.’ (where . is x’00’)
| v Support for 63 digit packed and zoned decimal values
| Packed and zoned data can be defined with up to 63 digits and 63 decimal
| positions. The previous limit was 31 digits.

xii ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

| v Relaxation of the rules for using a result data structure for I/O to
| externally-described files and record formats
| – The result data structure for I/O to a record format may be an
| externally-described data structure.
| – A data structure may be specified in the result field for I/O to an
| externally-described file name for operation codes CHAIN, READ, READE,
| READP and READPE.
| Examples:
| 1. The following program writes to a record format using from an
| externally-described data structure.
| Foutfile o e k disk
| D outrecDs e ds extname(outfile) prefix(O_)
| /free
| O_FLD1 = ’ABCDE’;
| O_FLD2 = 7;
| write outrec outrecDs;
| *inlr = *on;
| /end-free
| 2. The following program reads from a multi-format logical file into data
| structure INPUT which contains two overlapping subfields holding the fields
| of the respective record formats.
| Flog if e k disk infds(infds)
| D infds ds
| D recname 261 270
| D input ds qualified
| D rec1 likerec(rec1) overlay(input)
| D rec2 likerec(rec2) overlay(input)
| /free
| read log input;
| dow not %eof(log);
| dsply recname;
| if recname = ’REC1’;
| // handle rec1
| elseif recname = ’REC2’;
| // handle rec2
| endif;
| read log input;
| enddo;
| *inlr = *on;
| /end-free
| v Support for new environment variables for use with RPG programs calling
| Java methods
| – QIBM_RPG_JAVA_PROPERTIES allows RPG users to explicitly set the java
| properties used to start the JVM
| This environment variable must be set before any RPG program calls a Java
| method in a job.
| This environment variable has contains Java options, separated and
| terminated by some character that does not appear in any of the option
| strings. Semicolon is usually a good choice.
| Examples:
| 1. Specifying only one option: If the system’s default JDK is 1.3, and you
| want your RPG programs to use JDK 1.4, set environment variable
| QIBM_RPG_JAVA_PROPERTIES to
| ’-Djava.version=1.4;’

| Note that even with just one option, a terminating character is required. This
| example uses the semicolon.

About This Guide xiii


Changes to this Guide Since V5R1 and V5R2

| 2. Specifying more than one option: If you also want to set the os400.stdout
| option to a different value than the default, you could set the environment
| variable to the following value:
| ’-Djava.version=1.4!-Dos400.stdout=file:mystdout.txt!’

| This example uses the exclamation mark as the separator/terminator. Note:


| This support is also available in V5R1 and V5R2 with PTFs. V5R1: SI10069,
| V5R2: SI10101.
| – QIBM_RPG_JAVA_EXCP_TRACE allows RPG users to get the exception
| trace when an RPG call to a Java method ends with an exception
| This environment variable can be set, changed, or removed at any time.
| If this environment variable contains the value ’Y’, then when a Java
| exception occurs during a Java method call from RPG, or a called Java
| method throws an exception to its caller, the Java trace for the exception will
| be printed. By default, it will be printed to the screen, and may not be
| possible to read. To get it printed to a file, set the Java option os400.stderr.
| (This would have to be done in a new job; it could be done by setting the
| QIBM_RPG_JAVA_PROPERTIES environment variable to
| ’-Dos400.stderr=file:stderr.txt;’
| v An RPG preprocessor enabling the SQL preprocessor to handle conditional
| compilation and nested /COPY
| When the RPG compiler is called with a value other than *NONE for parameter
| PPGENOPT, it will behave as an RPG preprocessor. It will generate a new
| source file rather than generating a program. The new source file will contain
| the original source lines that are accepted by the conditional compilation
| directives such as /DEFINE and /IF. It will also have the source lines from files
| included by /COPY statements, and optionally it will have the source lines
| included by /INCLUDE statements. The new source file will have the comments
| from the original source file if PPGENOPT(*DFT) or
| PPGENOPT(*NORMVCOMMENT) is specified.When the SQL precompiler is
| called with a value other than *NONE for new parameter RPGPPOPT, the
| precompiler will use this RPG preprocessor to handle /COPY, the conditional
| compilation directives and possibly the /INCLUDE directive. This will allow
| SQLRPGLE source to have nested /COPY statements, and conditionally used
| statements.
| Table 1. Changed Language Elements Since V5R2
| Language Unit Element Description
| Control specification CCSID(*GRAPH:parameter| Can now take a first
| keywords *UCS2:number| parameter of *CHAR, with a
| *CHAR:*JOBRUN) second parameter of
| *JOBRUN, to control how
| character data is treated at
| runtime.
| Built-in Functions %DEC(expression {format}) Can now take a parameter of
| type Date, Time or Timestamp
| %TRIM(expression:expression) Can now take a second
| parameter indicating the set of
| characters to be trimmed
| Definition OPTIONS(*TRIM) Indicates that blanks are to be
| Specification trimmed from passed
| Keywords parameters

xiv ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

| Table 1. Changed Language Elements Since V5R2 (continued)


| Definition Length and decimal place entries The length and number of
| Specifications decimal places can be 63 for
| packed and zoned fields.
| Input specifications Length entry The length can be 32 for
| packed fields and 63 for zoned
| fields.
| Decimal place entry The number of decimal places
| can be 63 for packed and
| zoned fields.
| Calculation Length and decimal place entries The length and number of
| specifications decimal places can be 63 for
| packed and zoned fields.
| CHAIN, READ, READE, READP, Allow a data structure to be
| AND READPE operations specified in the result field
| when Factor 2 is the name of
| an externally-described file.
| CHAIN, READ, READC, READE, Allow an externally-described
| READP, READPE, WRITE, data structure to be specified
| UPDATE operations in the result field when Factor
| 2 is the name of an
| externally-described record
| format.
| SORTA operation Now has an extended Factor
| 2, allowing %SUBARR to be
| specified.
|
| Table 2. New Language Elements Since V5R2
| Language Unit Element Description
| Built-in Functions %SUBARR(array:starting Returns a section of the
| element {:number of array, or allows a section of
| elements}) the array to be modified.
|
|
# What's New in V5R2?
# The following list describes the enhancements made to ILE RPG in V5R2:
# v Conversion from character to numeric
# Built-in functions %DEC, %DECH, %INT, %INTH, %UNS, %UNSH and
# %FLOAT are enhanced to allow character parameters. For example,
# %DEC(’-12345.67’ : 7 : 2) returns the numeric value -12345.67.
# v Bitwise logical built-in functions
# %BITAND, %BITOR, %BITXOR and %BITNOT allow direct bit manipulation
# within RPG expressions.
# v Complex data structures
# Data structure definition is enhanced to allow arrays of data structures and
# subfields of data structures defined with LIKEDS that are themselves data
# structures. This allows the coding of complex structures such as arrays of arrays,
# or arrays of structures containing subarrays of structures.
# Example: family(f).child(i).hobbyInfo.pets(p).type = ’dog’;
# family(f).child(i).hobbyInfo.pets(p).name = ’Spot’;

About This Guide xv


Changes to this Guide Since V5R1 and V5R2

# In addition, data structures can be defined the same as a record format, using
# the new LIKEREC keyword.
# v Enhanced externally-described data structures
# Externally-described data structures can hold the programmer’s choice of input,
# output, both, key or all fields. Currently, externally-described data structures can
# only hold input fields.
# v Enhancments to keyed I/O
# Programmers can specify search arguments in keyed Input/Output operations in
# /FREE calculations in two new ways:
# 1. By specifying the search arguments (which can be expressions) in a list.
# 2. By specifying a data structure which contains the search arguments.
# Examples: D custkeyDS e ds extname(custfile:*key)
# /free
# CHAIN (keyA : keyB : key3) custrec;
# CHAIN %KDS(custkeyDS) custrec;
# v Data-structure result for externally-described files
# A data structure can be specified in the result field when using I/O operations
# for externally-described files. This was available only for program-described files
# prior to V5R2. Using a data structure can improve performance if there are
# many fields in the file.
# v UPDATE operation to update only selected fields
# A list of fields to be updated can be specified with an UPDATE operation. Tthis
# could only be done by using exception output prior to V5R2.
# Example: update record %fields(salary:status).
# v 31 digit support
# Supports packed and zoned numeric data with up to 31 digits and decimal
# places. This is the maximum length supported by DDS. Only 30 digits and
# decimal places were supported prior to V5R2.
# v Performance option for FEOD
# The FEOD operation is enhanced by supporting an extender N which indicates
# that the operation should simply write out the blocked buffers locally, without
# forcing a costly write to disk.
# v Enhanced data area access
# The DTAARA keyword is enhanced to allow the name and library of the data
# area to be determined at runtime
# v New assignment operators
# The new assignment operators +=, -=, *=, /=, **= allow a variable to be modified
# based on its old value in a more concise manner.
# Example: totals(current_customer) += count;

# This statement adds ″count″ to the value currently in ″totals(current_customer)″


# without having to code ″totals(current_customer)″ twice.
# v IFS source files
# The ILE RPG compiler can compile both main source files and /COPY files from
# the IFS. The /COPY and /INCLUDE directives are enhanced to support IFS file
# names.
# v Program Call Markup Language (PCML) generation
# The ILE RPG compiler will generate an IFS file containing the PCML,
# representing the parameters to the program (CRTBNDRPG) or to the exported
# procedures (CRTRPGMOD).

xvi ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

# Table 3. Changed Language Elements Since V5R1


# Language Unit Element Description
# Built-in functions %DEC(expression) Can now take parameters of type character.
# %DECH(expression)
# %FLOAT(expression)
# %INT(expression)
# %INTH(expression)
# %UNS(expression)
# %UNSH(expression)
# Definition DTAARA({*VAR:}data-area-name) The data area name can be a name, a character literal
# specification specifying ’LIBRARY/NAME’ or a character variable
# keywords which will determine the actual data area at runtime.
# DIM Allowed for data structure specifications.
# LIKEDS Allowed for subfield specifications.
# EXTNAME(filename{:extrecname} The optional ″type″ parameter controls which type of
# {:*ALL|*INPUT|*OUTPUT|*KEY} field is extracted for the externally-described data
# ) structure.
# Definition Length and decimal place entries The length and number of decimal places can be 31 for
# Specifications packed and zoned fields.
# Operation codes CHAIN, DELETEREADE, READPE, In free-form operations, Factor 1 can be a list of key
# SETGT, SETLL values.
# CHAIN, READ, READC, READE, When used with externally-described files or record
# READP, READPE, UPDATE, WRITE formats, a data structure may be specified in the result
# field.
# UPDATE In free-form calculations, the final argument can contain
# a list of the fields to be updated.
# FEOD Operation extender N is allowed. This indicates that the
# unwritten buffers must be made available to the
# database, but not necessarily be written to disk.
# Calculation Length and decimal place entries The length and number of decimal places can be 31 for
# specifications packed and zoned fields.
#
# Table 4. New Language Elements Since V5R1
# Language Unit Element Description
# Expressions Assignment Operators += -= *= /= When these assignment operators are used, the
# **= target of the operation is also the first operand of
# the operation.
# Control Specification DECPREC(30|31) Controls the precision of decimal intermediate
# Keywords values for presentation, for example, for %EDITC
# and %EDITW
# Definition specification LIKEREC(intrecname{:*ALL| Defines a data structure whose subfields are the
# keywords *INPUT|*OUTPUT|*KEY}) same as a record format.

About This Guide xvii


Changes to this Guide Since V5R1 and V5R2

# Table 4. New Language Elements Since V5R1 (continued)


# Language Unit Element Description
# Built-in functions %BITAND(expression : expression) Returns a result whose bits are on if the
# corresponding bits of the operands are both on.
# %BITNOT(expression) Returns a result whose bits are the inverse of the
# bits in the argument.
# %BITOR(expression : expression) Returns a result whose bits are on if either of the
# corresponding bits of the operands is on.
# %BITXOR(expression : expression) Returns a result whose bits are on if exactly one
# of the corresponding bits of the operands is on.
# %FIELDS(name{:name...}) Used in free-form ″UPDATE to specify the fields
# to be updated.
# %KDS(data structure) Used in free-form keyed operation codes CHAIN,
# SETLL, SETGT, READE and READPE, to indicate
# that the keys for the operation are in the data
# structure.
#
#
What's New in V5R1?
The ILE RPG compiler is part of the IBM WebSphere Development Studio product,
which now includes the C/C++ and COBOL compilers, and the Application
Development ToolSet tools.

The major enhancements to RPG IV since V4R4 are easier interfacing with Java,
new built-in functions, free form calculation specifications, control of which file is
opened, qualified subfield names, and enhanced error handling.

The following list describes these enhancements:


v Improved support for calls between Java and ILE RPG using the Java Native
Interface (JNI):
– A new data type: Object
– A new definition specification keyword: CLASS
– The LIKE definition specification keyword has been extended to support
objects.
– The EXTPROC definition specification keyword has been extended to support
Java procedures.
– New status codes.
v New built-in functions:
– Functions for converting a number into a duration that can be used in
arithmetic expressions: %MSECONDS, %SECONDS, %MINUTES, %HOURS,
%DAYS, %MONTHS, and %YEARS.
– The %DIFF function, for subtracting one date, time, or timestamp value from
another.
– Functions for converting a character string (or date or timestamp) into a date,
time, or timestamp: %DATE, %TIME, and %TIMESTAMP.
– The %SUBDT function, for extracting a subset of a date, time, or timestamp.
– Functions for allocating or reallocating storage: %ALLOC and %REALLOC.
– Functions for finding an element in an array: %LOOKUP, %LOOKUPGT,
%LOOKUPGE, %LOOKUPLT, and %LOOKUPLE.

xviii ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

– Functions for finding an element in a table: %TLOOKUP, %TLOOKUPGT,


%TLOOKUPGE, %TLOOKUPLT, and %TLOOKUPLE.
– Functions for verifying that a string contains only specified characters (or
finding the first or last exception to this rule): %CHECK and %CHECKR
– The %XLATE function, for translating a string based on a list of
from-characters and to-characters.
– The %OCCUR function, for getting or setting the current occurrence in a
multiple-occurrence data structure.
– The %SHTDN function, for determining if the operator has requested
shutdown.
– The %SQRT function, for calculating the square root of a number.
v A new free-form syntax for calculation specifications. A block of free-form
calculation specifcations is delimited by the compiler directives /FREE and
/END-FREE
v You can specify the EXTFILE and EXTMBR keywords on the file specification to
control which external file is used when a file is opened.
v Support for qualified names in data structures:
– A new definition specification keyword: QUALIFIED. This keyword specifies
that subfield names will be qualified with the data structure name.
– A new definition specification keyword: LIKEDS. This keyword specifies that
subfields are replicated from another data structure. The subfield names will
be qualified with the new data structure name. LIKEDS is allowed for
prototyped parameters; it allows the parameter’s subfields to be used directly
in the called procedure.
– The INZ definition specification keyword has been extended to allow a data
structure to be initialized based on its parent data structure.
v Enhanced error handling:
– Three new operation codes (MONITOR, ON-ERROR, and ENDMON) allow
you to define a group of operations with conditional error handling based on
the status code.

Other enhancements have been made to this release as well. These include:
v You can specify parentheses on a procedure call that has no parameters.
v You can specify that a procedure uses ILE C or ILE CL calling conventions, on
the EXTPROC definition specification keyword.
v The following /DEFINE names are predefined: *VnRnMn, *ILERPG,
*CRTBNDRPG, and *CRTRPGMOD.
v The search string in a %SCAN operation can now be longer than string being
searched. (The string will not be found, but this will no longer generate an error
condition.)
v The parameter to the DIM, OCCURS, and PERRCD keywords no longer needs
to be previously defined.
v The %PADDR built-in function can now take either a prototype name or an
entry point name as its argument.
v A new operation code, ELSEIF, combines the ELSE and IF operation codes
without requiring an additional ENDIF.
v The DUMP operation code now supports the A extender, which means that a
dump is always produced - even if DEBUG(*NO) was specified.

About This Guide xix


Changes to this Guide Since V5R1 and V5R2

v A new directive, /INCLUDE, is equivalent to /COPY except that /INCLUDE is


not expanded by the SQL preprocessor. Included files cannot contain embedded
SQL or host variables.
v The OFLIND file-specification keyword can now take any indicator, including a
named indicator, as an argument.
v The LICOPT (licensed internal code options) keyword is now available on the
CRTRPGMOD and CRTBNDRPG commands.
v The PREFIX file description keyword can now take an uppercase character literal
as an argument. The literal can end in a period, which allows the file to be used
with qualified subfields.
v The PREFIX definition specification keyword can also take an uppercase
character literal as an argument. This literal cannot end in a period.

The following tables summarize the changed and new language elements, based
on the part of the language affected.
Table 5. Changed Language Elements Since V4R4
Language Unit Element Description
Built-in functions %CHAR(expression{:format}) The optional second parameter specifies the
desired format for a date, time, or timestamp. The
result uses the format and separators of the
specified format, not the format and separators of
the input.
%PADDR(prototype-name) This function can now take either a prototype
name or an entry point name as its argument.
Definition specification EXTPROC(*JAVA:class-name:proc- Specifies that a Java method is called.
keywords name)
EXTPROC(*CL:proc-name) Specifies a procedure that uses ILE CL
conventions for return values.
EXTPROC(*CWIDEN:proc-name) Specifies a procedure that uses ILE C conventions
with parameter widening.
EXTPROC(*CNOWIDEN:proc-name) Specifies a procedure that uses ILE C conventions
without parameter widening.
INZ(*LIKEDS) Specifies that a data structure defined with the
LIKEDS keyword inherits the initialization from
its parent data structure.
LIKE(object-name) Specifies that an object has the same class as
another object.
PREFIX(character-literal{:number}) Prefixes the subfields with the specified character
literal, optionally replacing the specified number
of characters.
File specification OFLIND(name) This keyword can now take any named indicator
keywords as a parameter.
PREFIX(character-literal{:number}) Prefixes the subfields with the specified character
literal, optionally replacing the specified number
of characters.
Operation codes DUMP (A) This operation code can now take the A extender,
which causes a dump to be produced even if
DEBUG(*NO) was specified.

xx ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

Table 6. New Language Elements Since V4R4


Language Unit Element Description
Data types Object Used for Java objects
Compiler directives /FREE ... /END-FREE The /FREE... /END-FREE compiler directives
denote a free-form calculation specifications block.
/INCLUDE Equivalent to /COPY, except that it is not
expanded by the SQL preprocessor. Can be used
to inlcude nested files that are within the copied
file. The copied file cannot have embedded SQlL
or host variables.
Definition specification CLASS(*JAVA:class-name) Specifies the class for an object.
keywords
LIKEDS(dsname) Specifies that a data structure, prototyped
parameter, or return value inherits the subfields of
another data strucutre.
QUALIFIED Specifies that the subfield names in a data
structure are qualified with the data structure
name.
File specification EXTFILE(filename) Specifies which file is opened. The value can be a
keywords literal or a variable. The default file name is the
name specified in position 7 of the file
specification. The default library is *LIBL.
EXTMBR(membername) Specifies which member is opened. The value can
be a literal or a variable. The default is *FIRST.

About This Guide xxi


Changes to this Guide Since V5R1 and V5R2

Table 6. New Language Elements Since V4R4 (continued)


Language Unit Element Description
Built-in functions %ALLOC(num) Allocates the specified amount of storage.
%CHECK(comparator:base{:start}) Finds the first character in the base string that is
not in the comparator.
%CHECKR(comparator:base{:start}) Finds the last character in the base string that is
not in the comparator.
%DATE(expression{:date-format}) Converts the expression to a date.
%DAYS(num) Converts the number to a duration, in days.
%DIFF(op1:op2:unit) Calculates the difference (duration) between two
date, time, or timestamp values in the specified
units.
%HOURS(num) Converts the number to a duration, in hours.
%LOOKUPxx(arg:array{:startindex Finds the specified argument, or the specified
{:numelems}}) type of near-match, in the specified array.
%MINUTES(num) Converts the number to a duration, in minutes.
%MONTHS(num) Converts the number to a duration, in months.
%MSECONDS(num) Converts the number to a duration, in
microseconds.
%OCCUR(dsn-name) Sets or gets the current position of a
multiple-occurrence data structure.
%REALLOC(pointer:number) Reallocates the specified amount of storage for the
specified pointer.
%SECONDS(num) Converts the number to a duration, in seconds.
%SHTDN Checks if the system operator has requested
shutdown.
%SQRT(numeric-expression) Calculates the square root of the specified
number.
%SUBDT(value:unit) Extracts the specified portion of a date, time, or
timestamp value.
%THIS Returns an Object value that contains a reference
to the class instance on whose behalf the native
method is being called.
%TIME(expression{:time-format}) Converts the expression to a time.
%TIMESTAMP(expression Converts the expression to a timestamp.
{:*ISO|*ISO0})
%TLOOKUP(arg:search-table Finds the specified argument, or the specified
{:alt-table}) type of near-match, in the specified table.
%XLATE(from:to:string{:startpos}) Translates the specified string, based on the
from-string and to-string.
%YEARS(num) Converts the number to a duration, in years.

xxii ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

Table 6. New Language Elements Since V4R4 (continued)


Language Unit Element Description
Operation codes MONITOR Begins a group of operations with conditional
error handling.
ON-ERROR Performs conditional error handling, based on the
status code.
ENDMON Ends a group of operations with conditional error
handling.
ELSEIF Equivalent to an ELSE operation code followed by
an IF operation code.
CRTBNDRPG and LICOPT(options) Specifies Licensed Internal Code options.
CRTRPGMOD keywords

What's New in V4R4?


The major enhancements to RPG IV since V4R2 are the support for running ILE
RPG modules safely in a threaded environment, the new 3-digit and 20-digit
signed and unsigned integer data types, and support for a new Universal
Character Set Version 2 (UCS-2) data type and for conversion between UCS-2 fields
and graphic or single-byte character fields.

The following list describes these enhancements:


v Support for calling ILE RPG procedures from a threaded application, such as
Domino™ or Java™.
– The new control specification keyword THREAD(*SERIALIZE) identifies
modules that are enabled to run in a multithreaded environment. Access to
procedures in the module is serialized.
v Support for new 1-byte and 8-byte integer data types: 3I and 20I signed integer,
and 3U and 20U unsigned integer
– These new integer data types provide you with a greater range of integer
values and can also improve performance of integer computations, taking full
advantage of the 64-bit AS/400 RISC processor.
– The new 3U type allows you to more easily communicate with ILE C
procedures that have single-byte character (char) return types and parameters
passed by value.
– The new INTPREC control specification keyword allows you to specify
20-digit precision for intermediate values of integer and unsigned binary
arithmetic operations in expressions.
– Built-in functions %DIV and %REM have been added to support integer
division and remainder operations.
v Support for new Universal Character Set Version 2 (UCS-2) or Unicode data type
– The UCS-2 (Unicode) character set can encode the characters for many written
languages. The field is a character field whose characters are two bytes long.
– By adding support for Unicode, a single application can now be developed
for a multinational corporation, minimizing the necessity to perform code
page conversion. The use of Unicode permits the processing of characters in
multiple scripts without loss of integrity.
– Support for conversions between UCS-2 fields and graphic or single-byte
character fields using the MOVE and MOVEL operations, and the new
%UCS2 and %GRAPH built-in functions.

About This Guide xxiii


Changes to this Guide Since V5R1 and V5R2

– Support for conversions between UCS-2 fields or graphic fields with different
Coded Character Set Identifiers (CCSIDs) using the EVAL, MOVE, and
MOVEL operations, and the new %UCS2 built-in function.

Other enhancements have been made to this release as well. These include:
v New parameters for the OPTION control specification keyword and on the
create commands:
– *SRCSTMT allows you to assign statement numbers for debugging from the
source IDs and SEU sequence numbers in the compiler listing. (The statement
number is used to identify errors in the compiler listing by the debugger, and
to identify the statement where a run-time error occurs.) *NOSRCSTMT
specifies that statement numbers are associated with the Line Numbers of the
listing and the numbers are assigned sequentially.
– Now you can choose not to generate breakpoints for input and output
specifications in the debug view with *NODEBUGIO. If this option is
selected, a STEP on a READ statement in the debugger will step to the next
calculation, rather than stepping through the input specifications.
v New special words for the INZ definition specification keyword:
– INZ(*EXTDFT) allows you to use the default values in the DDS for
initializing externally described data structure subfields.
– Character variables initialized by INZ(*USER) are initialized to the name of
the current user profile.
v The new %XFOOT built-in function sums all elements of a specified array
expression.
v The new EVALR operation code evaluates expressions and assigns the result to a
fixed-length character or graphic result. The assignment right-adjusts the data
within the result.
v The new FOR operation code performs an iterative loop and allows free-form
expressions for the initial, increment, and limit values.
v The new LEAVESR operation code can be used to exit from any point within a
subroutine.
v The new *NEXT parameter on the OVERLAY(name:*NEXT) keyword indicates
that a subfield overlays another subfield at the next available position.
v The new *START and *END values for the SETLL operation code position to the
beginning or end of the file.
v The ability to use hexadecimal literals with integer and unsigned integer fields
in initialization and free-form operations, such as EVAL, IF, etc.
v New control specification keyword OPENOPT{(*NOINZOFL | *INZOFL)} to
indicate whether the overflow indicators should be reset to *OFF when a file is
opened.
v Ability to tolerate pointers in teraspace — a memory model that allows more
than 16 megabytes of contiguous storage in one allocation.

The following tables summarize the changed and new language elements, based
on the part of the language affected.

xxiv ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

Table 7. Changed Language Elements Since V4R2


Language Unit Element Description
Control OPTION(*{NO}SRCSTMT) *SRCSTMT allows you to request that
specification the compiler use SEU sequence
keywords numbers and source IDs when
generating statement numbers for
debugging. Otherwise, statement
numbers are associated with the Line
Numbers of the listing and the
numbers are assigned sequentially.
OPTION(*{NO}DEBUGIO) *{NO}DEBUGIO, determines if
breakpoints are generated for input
and output specifications.
Definition INZ(*EXTDFT) All externally described data structure
specification subfields can now be initialized to the
keywords default values specified in the DDS.
INZ(*USER) Any character field or subfield can be
initialized to the name of the current
user profile.
OVERLAY(name:*NEXT) The special value *NEXT indicates that
the subfield is to be positioned at the
next available position within the
overlayed field.
OPTIONS(*NOPASS *OMIT The new OPTIONS(*RIGHTADJ)
*VARSIZE *STRING specified on a value or constant
*RIGHTADJ) parameter in a function prototype
indicates that the character, graphic, or
UCS-2 value passed as a parameter is
to be right adjusted before being
passed on the procedure call.
Definition 3 and 20 digits allowed for I Added to the list of allowed values for
specification and U data types internal data types to support 1-byte
positions 33-39 (To and 8-byte integer and unsigned data.
Position/Length)
Internal data type C (UCS-2 fixed or Added to the list of allowed internal
variable-length format) data types on the definition
specifications. The UCS-2 (Unicode)
character set can encode the characters
for many written languages. The field
is a character field whose characters
are two bytes long.
Data format C (UCS-2 fixed or UCS-2 format added to the list of
variable-length format) allowed data formats on the input and
output specifications for program
described files.
Command OPTION *NOSRCSTMT, *SRCSTMT,
parameter *NODEBUGIO, and *DEBUGIO have
been added to the OPTION parameter
on the CRTBNDRPG and
CRTRPGMOD commands.

About This Guide xxv


Changes to this Guide Since V5R1 and V5R2

Table 8. New Language Elements Since V4R2


Language Unit Element Description
Control CCSID(*GRAPH: *IGNORE | Sets the default graphic CCSID for the
specification *SRC | number) module. This setting is used for
keywords literals, compile-time data and
program-described input and output
fields and definitions. The default is
*IGNORE.
CCSID(*UCS2: number) Sets the default UCS-2 CCSID for the
module. This setting is used for
literals, compile-time data and
program-described input and output
fields and definitions. The default is
13488.
INTPREC(10 | 20) Specifies the decimal precision of
integer and unsigned intermediate
values in binary arithmetic operations
in expressions. The default,
INTPREC(10), indicates that 10-digit
precision is to be used.
OPENOPT{(*NOINZOFL | Indicates whether the overflow
*INZOFL)} indicators should be reset to *OFF
when a file is opened.
THREAD(*SERIALIZE) Indicates that the module is enabled to
run in a multithreaded environment.
Access to the procedures in the
module is to be serialized.
Definition CCSID(number | *DFT) Sets the graphic and UCS-2 CCSID for
specification the definition.
keywords
Built-in functions %DIV(n:m) Performs integer division on the two
operands n and m; the result is the
integer portion of n/m. The operands
must be numeric values with zero
decimal positions.
%GRAPH(char-expr | Converts to graphic data from
graph-expr | UCS2-expr {: single-byte character, graphic, or
ccsid}) UCS-2 data.
%REM(n:m) Performs the integer remainder
operation on two operands n and m;
the result is the remainder of n/m. The
operands must be numeric values with
zero decimal positions.
%UCS2(char-expr | Converts to UCS-2 data from
graph-expr | UCS2-expr {: single-byte character, graphic, or
ccsid}) UCS-2 data.
%XFOOT(array-expr) Produces the sum of all the elements
in the specified numeric array
expression.

xxvi ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

Table 8. New Language Elements Since V4R2 (continued)


Language Unit Element Description
Operation codes EVALR Evaluates an assignment statement of
the form result=expression. The result
will be right-justified.
FOR Begins a group of operations and
indicates the number of times the
group is to be processed. The initial,
increment, and limit values can be
free-form expressions.
ENDFOR ENDFOR ends a group of operations
started by a FOR operation.
LEAVESR Used to exit from anywhere within a
subroutine.

What's New in V4R2?


The major enhancements to RPG IV since V3R7 are the support for variable-length
fields, several enhancements relating to indicators, and the ability to specify
compile options on the control specifications. These further improve the RPG
product for integration with the OS/400 operating system and ILE interlanguage
communication.

The following list describes these enhancements:


v Support for variable-length fields
This enhancement provides full support for variable-length character and
graphic fields. Using variable-length fields can simplify many string handling
tasks.
v Ability to use your own data structure for INDARA indicators
Users can now access logical data areas and associate an indicator data structure
with each WORKSTN and PRINTER file that uses INDARA, instead of using the
*IN array for communicating values to data management.
v Ability to use built-in functions instead of result indicators
Built-in functions %EOF, %EQUAL, %FOUND, and %OPEN have been added to
query the results of input/output operations. Built-in functions %ERROR and
%STATUS, and the operation code extender ’E’ have been added for error
handling.
v Compile options on the control specification
Compile options, specified through the CRTBNDRPG and CRTRPGMOD
commands, can now be specified through the control specification keywords.
These compile options will be used on every compile of the program.

In addition, the following new function has been added:


v Support for import and export of procedures and variables with mixed case
names
v Ability to dynamically set the DECEDIT value at runtime
v Built-in functions %CHAR and %REPLACE have been added to make string
manipulation easier
v New support for externally defined *CMDY, *CDMY, and *LONGJUL date data
formats
v An extended range for century date formats

About This Guide xxvii


Changes to this Guide Since V5R1 and V5R2

v Ability to define indicator variables


v Ability to specify the current data structure name as the parameter for the
OVERLAY keyword
v New status code 115 has been added to indicate variable-length field errors
v Support for application profiling
v Ability to handle packed-decimal data that is not valid when it is retrieved from
files using FIXNBR(*INPUTPACKED)
v Ability to specify the BNDDIR command parameter on the CRTRPGMOD
command.

The following tables summarize the changed and new language elements, based
on the part of the language affected.
Table 9. Changed Language Elements Since V3R7
Language Unit Element Description
Control DECEDIT(*JOBRUN | The decimal edit value can now be
specification ’value’) determined dynamically at runtime
keywords from the job or system value.
Definition DTAARA {(data_area_name)} Users can now access logical data
specification areas.
keywords
EXPORT {(external_name)} The external name of the variable
being exported can now be specified as
a parameter for this keyword.
IMPORT {(external_name)} The external name of the variable
being imported can now be specified
as a parameter for this keyword.
OVERLAY(name{:pos}) The name parameter can now be the
name of the current data structure.
Extended century *CYMD (cyy/mm/dd) The valid values for the century
format character ’c’ are now:
’c’ Years
-----------------------
0 1900-1999
1 2000-2099
. .
. .
. .
9 2800-2899
Internal data type N (Indicator format) Added to the list of allowed internal
data types on the definition
specifications. Defines character data in
the indicator format.
Data format N (Indicator format) Indicator format added to the list of
allowed data formats on the input and
output specifications for program
described files.
Data Attribute *VAR Added to the list of allowed data
attributes on the input and output
specifications for program described
files. It is used to specify
variable-length fields.

xxviii ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

Table 9. Changed Language Elements Since V3R7 (continued)


Language Unit Element Description
Command FIXNBR The *INPUTPACKED parameter has
parameter been added to handle packed-decimal
data that is not valid.

Table 10. New Language Elements Since V3R7


Language Unit New Description
Control ACTGRP(*NEW | *CALLER The ACTGRP keyword allows you to
specification | ’activation- group-name’) specify the activation group the
keywords program is associated with when it is
called.
ALWNULL(*NO | The ALWNULL keyword specifies how
*INPUTONLY | *USRCTL) you will use records containing
null-capable fields from externally
described database files.
AUT(*LIBRCRTAUT | *ALL The AUT keyword specifies the
| *CHANGE | *USE | authority given to users who do not
*EXCLUDE | have specific authority to the object,
’authorization-list-name’) who are not on the authorization list,
and whose user group has no specific
authority to the object.
BNDDIR( ’binding The BNDDIR keyword specifies the list
-directory-name’ {:’binding- of binding directories that are used in
directory-name’...}) symbol resolution.
CVTOPT(*{NO}DATETIME The CVTOPT keyword is used to
*{NO}GRAPHIC determine how the ILE RPG compiler
*{NO}VARCHAR handles date, time, timestamp, graphic
*{NO}VARGRAPHIC) data types, and variable-length data
types that are retrieved from externally
described database files.
DFTACTGRP(*YES | *NO) The DFTACTGRP keyword specifies
the activation group in which the
created program will run when it is
called.
ENBPFRCOL(*PEP | The ENBPFRCOL keyword specifies
*ENTRYEXIT | *FULL) whether performance collection is
enabled.
FIXNBR(*{NO}ZONED The FIXNBR keyword specifies
*{NO}INPUTPACKED) whether decimal data that is not valid
is fixed by the compiler.
GENLVL(number) The GENLVL keyword controls the
creation of the object.
INDENT(*NONE | The INDENT keyword specifies
’character-value’) whether structured operations should
be indented in the source listing for
enhanced readability.
LANGID(*JOBRUN | *JOB | The LANGID keyword indicates which
’language-identifier’) language identifier is to be used when
the sort sequence is *LANGIDUNQ or
*LANGIDSHR.

About This Guide xxix


Changes to this Guide Since V5R1 and V5R2

Table 10. New Language Elements Since V3R7 (continued)


Language Unit New Description
OPTIMIZE(*NONE | *BASIC The OPTIMIZE keyword specifies the
| *FULL) level of optimization, if any, of the
object.
OPTION(*{NO}XREF The OPTION keyword specifies the
*{NO}GEN *{NO}SECLVL options to use when the source
*{NO}SHOWCPY member is compiled.
*{NO}EXPDDS *{NO}EXT
*{NO}SHOWSKP)
PRFDTA(*NOCOL | *COL) The PRFDTA keyword specifies
whether the collection of profiling data
is enabled.
SRTSEQ(*HEX | *JOB | The SRTSEQ keyword specifies the
*JOBRUN | *LANGIDUNQ sort sequence table that is to be used
| *LANGIDSHR | in the ILE RPG source program.
’sort-table-name’)
TEXT(*SRCMBRTXT | The TEXT keyword allows you to
*BLANK | ’description’) enter text that briefly describes the
object and its function.
TRUNCNBR(*YES | *NO) The TRUNCNBR keyword specifies if
the truncated value is moved to the
result field or if an error is generated
when numeric overflow occurs while
running the object.
USRPRF(*USER | *OWNER) The USRPRF keyword specifies the
user profile that will run the created
program object.
File Description INDDS( The INDDS keyword lets you associate
Specification data_structure_name) a data structure name with the
keywords INDARA indicators for a workstation
or printer file.
Definition VARYING Defines variable-length fields when
specification specified on character data or graphic
keywords data.
Built-in functions %CHAR(graphic, date, time Returns the value in a character data
or timestamp expression) type.
%EOF{file name} Returns ’1’ if the most recent file input
operation or write to a subfile (for a
particular file, if specified) ended in an
end-of-file or beginning-of-file
condition; otherwise, it returns ’0’.
%EQUAL{file name} Returns ’1’ if the most recent SETLL
(for a particular file, if specified) or
LOOKUP operation found an exact
match; otherwise, it returns ’0’.
%ERROR Returns ’1’ if the most recent operation
code with extender ’E’ specified
resulted in an error; otherwise, it
returns ’0’.

xxx ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

Table 10. New Language Elements Since V3R7 (continued)


Language Unit New Description
%FOUND{file name} Returns ’1’ if the most recent relevant
operation (for a particular file, if
specified) found a record (CHAIN,
DELETE, SETGT, SETLL), an element
(LOOKUP), or a match (CHECK,
CHECKR and SCAN); otherwise, it
returns ’0’.
%OPEN(file name) Returns ’1’ if the specified file is open
and ’0’ if the specified file is closed.
%REPLACE(replacement Returns the string produced by
string: source string {:start inserting a replacement string into a
position {:source length to source string, starting at the start
replace}}) position and replacing the specified
number of characters.
%STATUS{file name} If no program or file error occurred
since the most recent operation code
with extender ’E’ specified, it returns 0.
If an error occurred, it returns the most
recent value set for any program or file
status. If a file is specified, the value
returned is the most recent status for
that file.
Operation code E Allows for error handling using the
Extender %ERROR and %STATUS built-in
functions on the CALLP operation and
all operations that allow error
indicators.
New century *CMDY (cmm/dd/yy) To be used by the MOVE, MOVEL,
formats and TEST operations.
*CDMY (cdd/mm/yy) To be used by the MOVE, MOVEL,
and TEST operations.
New 4-digit year *LONGJUL (yyyy/ddd) To be used by the MOVE, MOVEL,
format and TEST operations.
Command PRFDTA The PRFDTA parameter specifies
parameters whether the collection of profiling data
is enabled.
BNDDIR The BNDDIR parameter was
previously only allowed on the
CRTBNDRPG command and not on
the CRTRPGMOD command, now it is
allowed on both commands.

What's New in V3R7?


The major enhancements to RPG IV since V3R6 are the new support for database
null fields, and the ability to better control the precision of intermediate results in
expressions. Other enhancements include the addition of a floating point data type
and support for null-terminated strings. These further improve the RPG product
for integration with the OS/400 operating system and ILE interlanguage
communication. This means greater flexibility for developing applications.

About This Guide xxxi


Changes to this Guide Since V5R1 and V5R2

The following is a list of these enhancements including a number of new built-in


functions and usability enhancements:
v Support for database null fields
This enhancement allows users to process database files which contain
null-capable fields, by allowing these fields to be tested for null and set to null.
v Expression intermediate result precision
A new control specification keyword and new operation code extenders on
free-form expression specifications allow the user better control over the
precision of intermediate results.
v New floating point data type
The new floating point data type has a much larger range of values than other
data types. The addition of this data type will improve integration with the
OS/400 database and improve interlanguage communication in an ILE
environment, specifically with the C and C++ languages.
v Support for null terminated strings
The new support for null terminated strings improves interlanguage
communication. It allows users full control over null terminated data by
allowing users to define and process null terminated strings, and to conveniently
pass character data as parameters to procedures which expect null terminated
strings.
v Pointer addition and subtraction
Free-form expressions have been enhanced to allow adding an offset to a
pointer, subtracting an offset from a pointer, and determining the difference
between two pointers.
v Support for long names
Names longer than 10 characters have been added to the RPG language.
Anything defined on the definition or procedure specifications can have a long
name and these names can be used anywhere where they fit within the bounds
of an entry. In addition, names referenced on any free-form specification may be
continued over multiple lines.
v New built-in functions
A number of new built-in functions have been added to the language which
improve the following language facilities:
– editing (%EDITW, %EDITC, %EDITFLT)
– scanning strings (%SCAN)
– type conversions (%INT, %FLOAT, %DEC, %UNS)
– type conversions with half-adjust (%INTH, %DECH, %UNSH)
– precision of intermediate results for decimal expressions (%DEC)
– length and decimals of variables and expressions (%LEN, %DECPOS)
– absolute value (%ABS)
– set and test null-capable fields (%NULLIND)
– handle null terminated strings (%STR)
v Conditional compilation
RPG IV has been extended to support conditional compilation. This support will
include the following:
– defining conditions (/DEFINE, /UNDEFINE),
– testing conditions (/IF, /ELSEIF, /ELSE, /ENDIF)
– stop reading current source file (/EOF)

xxxii ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

– a new command option (DEFINE) to define up to 32 conditions on the


CRTBNDRPG and CRTRPGMOD commands.
v Date enhancements
Several enhancements have been made to improve date handling operations.
The TIME operation code is extended to support Date, Time or Timestamp fields
in the result field. Moving dates or times from and to character fields no longer
requires separator characters. Moving UDATE and *DATE fields no longer
requires a format code to be specified. Date fields can be initialized to the
system (*SYS) or job (*JOB) date on the definition specifications.
v Character comparisons with alternate collating sequence
Specific character variables can be defined so that the alternate collating
sequence is not used in comparisons.
v Nested /COPY members
You can now nest /COPY directives. That is, a /COPY member may contain one
(or more) /COPY directives which can contain further /COPY directives and so
on.
v Storage management
You can now use the new storage management operation codes to allocate,
reallocate and deallocate storage dynamically.
v Status codes for storage management and float underflow errors.
Two status codes 425 and 426 have been added to indicate storage management
errors. Status code 104 was added to indicate that an intermediate float result is
too small.

The following tables summarize the changed and new language elements, based
on the part of the language affected.
Table 11. Changed Language Elements Since V3R6
Language Unit Element Description
Definition ALIGN ALIGN can now be used to align float
specification subfields along with the previously
keywords supported integer and unsigned
alignment.
OPTIONS(*NOPASS *OMIT The *STRING option allows you to
*VARSIZE *STRING) pass a character value as a
null-terminated string.
Record address F (Float format) Added to the list of allowed record
type address types on the file description
specifications. Signals float processing
for a program described file.
Internal data type F (Float format) Added to the list of allowed internal
data types on the definition
specifications. Defines a floating point
standalone field, parameter, or data
structure subfield.
Data format F (Float format) Added to the list of allowed data
formats on the input and output
specifications for program described
files.

About This Guide xxxiii


Changes to this Guide Since V5R1 and V5R2

Table 12. New Language Elements Since V3R6


Language Unit New Description
Control COPYNEST(’1-2048’) Specifies the maximum depth for
specification nesting of /COPY directives.
keywords
EXPROPTS(*MAXDIGITS | Expression options for type of
*RESDECPOS) precision (default or ″Result Decimal
Position″ precision rules)
FLTDIV{(*NO | *YES)} Indicates that all divide operations in
expressions are computed in floating
point.
Definition ALTSEQ(*NONE) Forces the normal collating sequence to
specification be used for character comparison even
keywords when an alternate collating sequence is
specified.
Built-in functions %ABS Returns the absolute value of the
numeric expression specified as the
parameter.
%DEC & %DECH Converts the value of the numeric
expression to decimal (packed) format
with the number of digits and decimal
positions specified as parameters.
%DECH is the same as %DEC, but
with a half adjust applied.
%DECPOS Returns the number of decimal
positions of the numeric variable or
expression. The value returned is a
constant, and may be used where a
constant is expected.
%EDITC This function returns a character result
representing the numeric value edited
according to the edit code.
%EDITFLT Converts the value of the numeric
expression to the character external
display representation of float.
%EDITW This function returns a character result
representing the numeric value edited
according to the edit word.
%FLOAT Converts the value of the numeric
expression to float format.
%INT & %INTH Converts the value of the numeric
expression to integer. Any decimal
digits are truncated with %INT and
rounded with %INTH.
%LEN Returns the number of digits or
characters of the variable expression.
%NULLIND Used to query or set the null indicator
for null-capable fields.
%SCAN Returns the first position of the search
argument in the source string, or 0 if it
was not found.

xxxiv ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

Table 12. New Language Elements Since V3R6 (continued)


Language Unit New Description
%STR Used to create or use null-terminated
strings, which are very commonly
used in C and C++ applications.
%UNS & %UNSH Converts the value of the numeric
expression to unsigned format. Any
decimal digits are truncated with
%UNS and rounded with %UNSH.
Operation code N Sets pointer to *NULL after successful
Extenders DEALLOC
M Default precision rules
R No intermediate value will have fewer
decimal positions than the result
(″Result Decimal Position″ precision
rules)
Operation codes ALLOC Used to allocate storage dynamically.
DEALLOC Used to deallocate storage
dynamically.
REALLOC Used to reallocate storage dynamically.

What's New in V3R6/V3R2?


The major enhancement to RPG IV since V3R1 is the ability to code a module with
more than one procedure. What does this mean? In a nutshell, it means that you
can code an module with one or more prototyped procedures, where the
procedures can have return values and run without the use of the RPG cycle.

Writing a module with multiple procedures enhances the kind of applications you
can create. Any application consists of a series of logical units that are conceived to
accomplish a particular task. In order to develop applications with the greatest
flexibility, it is important that each logical unit be as independent as possible.
Independent units are:
v Easier to write from the point of view of doing a specific task.
v Less likely to change any data objects other than the ones it is designed to
change.
v Easier to debug because the logic and data items are more localized.
v Maintained more readily since it is easier to isolate the part of the application
that needs changing.

The main benefit of coding a module with multiple procedures is greater control
and better efficiency in coding a modular application. This benefit is realized in
several ways. You can now:
v Call procedures and programs by using the same call operation and syntax.
v Define a prototype to provide a check at compile time of the call interface.
v Pass parameters by value or by reference.
v Define a procedure that will return a value and call the procedure within an
expression.
v Limit access to data items by defining local definitions of variables.
v Code a module that does not make use of the cycle.

About This Guide xxxv


Changes to this Guide Since V5R1 and V5R2

v Call a procedure recursively.

The run-time behavior of the main procedure in a module is the same as that of a
V3R1 procedure. The run-time behavior of any subsequent procedures differs
somewhat from a V3R1 program, most notably in the areas of procedure end and
exception handling. These differences arise because there is no cycle code that is
generated for these procedures.

Other enhancements have been made to for this release as well. These include:
v Support for two new integer data types: signed integer (I), and unsigned integer
(U)
The use of the integer data types provides you with a greater range of values
than the binary data type. Integer data types can also improve performance of
integer computations.
v *CYMD support for the MOVE, MOVEL, and TEST operations
You can now use the *CYMD date format in certain operations to work with
system values that are already in this data format.
v Ability to copyright your programs and modules by using the COPYRIGHT
keyword on the control specification
The copyright information that is specified using this keyword becomes part of
the DSPMOD, DSPPGM, or DSPSRVPGM information.
v User control of record blocking using keyword BLOCK
You can request record blocking of DISK or SEQ files to be done even when
SETLL, SETGT, or CHAIN operations are used on the file. You can also request
that blocking not be done. Use of blocking in these cases may significantly
improve runtime performance.
v Improved PREFIX capability
Changes to the PREFIX keyword for either file-description and definition
specifications allow you to replace characters in the existing field name with the
prefix string.
v Status codes for trigger program errors
Two status codes 1223 and 1224 have been added to indicate trigger program
errors.

The following tables summarize the changed and new language elements, based
on the part of the language affected.
Table 13. Changed Language Elements Since V3R1
Language Unit Element Description
File description PREFIX(prefix_string Allows prefixing of string to a field
specification {:nbr_of_char_ replaced}) name or a partial rename of the field
keywords name
Definition CONST{(constant)} Specifies the value of a named
specification constant, or indicates that a prototyped
keywords parameter that is passed by reference
has a constant value
PREFIX(prefix_string Allows prefixing of string to a field
{:nbr_of_char_ replaced}) name or a partial rename of the field
name
Operation codes RETURN Returns control to the caller, and
returns a value, if specified

xxxvi ILE RPG Programmer’s Guide


Changes to this Guide Since V5R1 and V5R2

Table 14. New Language Elements Since V3R1


Language Unit New Description
Control COPYRIGHT(’copyright Allows you to associate copyright
specification string’) information with modules and
keywords programs
EXTBININT{(*NO | *YES)} Specifies that binary fields in
externally-described files be assigned
an integer format during program
processing
NOMAIN Indicates that the module has only
subprocedures
File description BLOCK(*YES |*NO) Allows you to control whether record
specification blocking occurs (assuming other
keywords conditions are met)
Definition ALIGN Specifies whether integer or unsigned
specification fields should be aligned
keywords
EXTPGM(name) Indicates the external name of the
prototyped program
EXTPROC(name) Indicates the external name of the
prototyped procedure
OPDESC Indicates whether operational
descriptors are to be passed for the
prototyped bound call
OPTIONS(*NOPASS *OMIT Specifies various options for
*VARSIZE) prototyped parameters
STATIC Specifies that the local variable is to
use static storage
VALUE Specifies that the prototyped
parameter is to be passed by value
Built-in functions %PARMS Returns the number of parameters
passed on a call
Operation codes CALLP Calls a prototyped program or
procedure
Specification type Procedure specification Signals the beginning and end of a
subprocedure definition
Definition type PR Signals the beginning of a prototype
definition
PI Signals the beginning of a procedure
interface definition
blank in positions 24-25 Defines a prototyped parameter

About This Guide xxxvii


Changes to this Guide Since V5R1 and V5R2

xxxviii ILE RPG Programmer’s Guide


Part 1. ILE RPG Introduction
Before using ILE RPG to create a program, you must know certain aspects of the
environment in which you will be using it. This part provides information on the
following topics that you should know:
v Overview of RPG IV language
v Role of Integrated Language Environment components in RPG programming
v Integrated Language Environment program creation strategies
v Overview of coding a module with more than one procedure and prototyped
calls

© Copyright IBM Corp. 1994, 2004 1


2 ILE RPG Programmer’s Guide
Chapter 1. Overview of the RPG IV Programming Language
This chapter presents a high-level review of the features of the RPG IV
programming language that distinguish RPG from other programming languages.
You should be familiar and comfortable with all of these features before you
program in the RPG IV language. The features discussed here encompass the
following subjects:
v Coding specifications
v The program cycle
v Indicators
v Operation codes

For more information on RPG IV, see the WebSphere Development Studio: ILE RPG
Reference.

RPG IV Specifications
RPG code is written on a variety of specification forms, each with a specific set of
functions. Many of the entries which make up a specification type are
position-dependent. Each entry must start in a specific position depending on the
type of entry and the type of specification.

There are seven types of RPG IV specifications. Each specification type is optional.
Specifications must be entered into your source program in the order shown below.

Main source section:


1. Control specifications provide the compiler with information about generating
and running programs, such as the program name, date format, and use of
alternate collating sequence or file translation.
2. File description specifications describe all the files that your program uses.
3. Definition specifications describe the data used by the program.
4. Input specifications describe the input records and fields used by the program.
5. Calculation specifications describe the calculations done on the data and the
order of the calculations. Calculation specifications also control certain input
and output operations.
6. Output specifications describe the output records and fields used by the
program.

Subprocedure section:
1. Procedure specifications mark the beginning and end of the subprocedure,
indicate the subprocedure name, and whether it is exported.
2. Definition specifications describe the local data used by the subprocedure.
3. Calculation specifications describe the calculations done on both the global
and local data and the order of the calculations.

© Copyright IBM Corp. 1994, 2004 3


RPG IV Overview

Cycle Programming
When a system processes data, it must do the processing in a particular order. This
logical order is provided by:
v The ILE RPG compiler
v The program code

The logic the compiler supplies is called the program cycle. When you let the
compiler provide the logic for your programs, it is called cycle programming.

The program cycle is a series of steps that your program repeats until an
end-of-file condition is reached. Depending on the specifications you code, the
program may or may not use each step in the cycle.

If you want to have files controlled by the cycle, the information that you code on
RPG specifications in your source program need not specify when records for these
files are read. The compiler supplies the logical order for these operations, and
some output operations, when your source program is compiled.

If you do not want to have files controlled by the cycle, you must end your
program some other way, either by creating an end-of-file condition by setting on
the last record (LR) indicator, by creating a return condition by setting on the
return (RT) indicator, or by returning directly using the RETURN operation.

Note: No cycle code is generated for subprocedures or when NOMAIN is


specified on the control specification.

Figure 1 shows the specific steps in the general flow of the RPG program cycle.

Write Perform
Get input
Start heading and total
record
detail lines calculations

Perform No Write
LR on
detail Move fields total
calculations output

Yes

End of
program

Figure 1. RPG Program Logic Cycle

1 RPG processes all heading and detail lines (H or D in position 17 of the
output specifications).

4 ILE RPG Programmer’s Guide


RPG IV Overview

2 RPG reads the next record and sets on the record identifying and control
level indicators.
3 RPG processes total calculations (conditioned by control level indicators L1
through L9, an LR indicator, or an L0 entry).
4 RPG processes all total output lines (identified by a T in position 17 of the
output specifications).
5 RPG determines if the LR indicator is on. If it is on, the program ends.
6 The fields of the selected input records move from the record to a
processing area. RPG sets on field indicators.
7 RPG processes all detail calculations (not conditioned by control level
indicators in positions 7 and 8 of the calculation specifications). It uses the
data from the record at the beginning of the cycle.

The first cycle

The first and last time through the program cycle differ somewhat from other
cycles. Before reading the first record the first time through the cycle, the program
does three things:
v handles input parameters, opens files, initializes program data
v writes the records conditioned by the 1P (first page) indicator
v processes all heading and detail output operations.

For example, heading lines printed before reading the first record might consist of
constant or page heading information, or special fields such as PAGE and *DATE.
The program also bypasses total calculations and total output steps on the first
cycle.

The last cycle

The last time a program goes through the cycle, when no more records are
available, the program sets the LR (last record) indicator and the L1 through L9
(control level) indicators to on. The program processes the total calculations and
total output, then all files are closed, and then the program ends.

Subprocedure logic
The general flow of a subprocedure is much simpler: the calculations of a
subprocedure are done once, and then the subprocedure returns. There is no cycle
code generated for a subprocedure.

Indicators
An indicator is a one-byte character field that is either set on (’1’) or off (’0’). It is
generally used to indicate the result of an operation or to condition (control) the
processing of an operation. Indicators are like switches in the flow of the program
logic. They determine the path the program will take during processing,
depending on how they are set or used.

Indicators can be defined as variables on the definition specifications. You can also
use RPG IV indicators, which are defined either by an entry on a specification or
by the RPG IV program itself.

Chapter 1. Overview of the RPG IV Programming Language 5


RPG IV Overview

Each RPG IV indicator has a two-character name (for example, LR, 01, H3), and is
referred to in some entries of some specifications just by the two-character name,
and in others by the special name *INxx where xx is the two-character name. You
can use several types of these indicators; each type signals something different. The
positions on the specification in which you define an indicator determine the use
of the indicator. Once you define an indicator in your program, it can limit or
control calculation and output operations.

Indicator variables can be used any place an indicator of the form *INxx may be
used with the exception of the OFLIND and EXTIND keywords on the file
description specifications.

An RPG program sets and resets certain indicators at specific times during the
program cycle. In addition, the state of indicators can be changed explicitly in
calculation operations.

Operation Codes
The RPG IV programming language allows you to do many different types of
operations on your data. Operation codes, entered on the calculation specifications,
indicate what operations will be done. For example, if you want to read a new
record, you could use the READ operation code. The following is a list of the types
of operations available.
v Arithmetic operations
v Array operations
v Bit operations
v Branching operations
v Call operations
v Compare operations
v Conversion operations
v Data-area operations
v Date operations
v Declarative operations
v Error-handling operations
v File operations
v Indicator-setting operations
v Information operations
v Initialization operations
v Memory management operations
v Move operations
v Move zone operations
v Result operations
v Size operations
v String operations
v Structured programming operations
v Subroutine operations
v Test operations

Example of an ILE RPG Program


This section illustrates a simple ILE RPG program that performs payroll
calculations.

Problem Statement

6 ILE RPG Programmer’s Guide


Example of an ILE RPG Program

The payroll department of a small company wants to create a print output that
lists employees’ pay for that week. Assume there are two disk files, EMPLOYEE
and TRANSACT, on the system.

The first file, EMPLOYEE, contains employee records. The figure below shows the
format of an employee record:

EMP_REC

EMP_NUMBER EMP_NAME EMP_RATE

1 6 22 27

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..*


A..........T.Name++++++RLen++TDpB......Functions++++++++++++++++++++*
A R EMP_REC
A EMP_NUMBER 5 TEXT(’EMPLOYEE NUMBER’)
A EMP_NAME 16 TEXT(’EXPLOYEE NAME’)
A EMP_RATE 5 2 TEXT(’EXPLOYEE RATE’)
A K EMP_NUMBER

Figure 2. DDS for Employee physical file

The second file, TRANSACT, tracks the number of hours each employee worked
for that week and any bonus that employee may have received. The figure below
shows the format of a transaction record:

TRN_REC

TRN_NUMBER TRN_HOURS TRN_BONUS

1 6 10 16

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ..*


A..........T.Name++++++RLen++TDpB......Functions++++++++++++++++++++*
A R TRN_REC
A TRN_NUMBER 5 TEXT(’EMPLOYEE NUMBER’)
A TRN_HOURS 4 1 TEXT(’HOURS WORKED’)
A TRN_BONUS 6 2 TEXT(’BONUS’)

Figure 3. DDS for TRANSACT physical file

Each employee’s pay is calculated by multiplying the ″hours″ (from the


TRANSACT file) and the ″rate″ (from the EMPLOYEE file) and adding the ″bonus″
from the TRANSACT file. If more than 40 hours were worked, the employee is
paid for for 1.5 times the normal rate.

Control Specifications

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+... 8


HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
H DATEDIT(*DMY/)

Chapter 1. Overview of the RPG IV Programming Language 7


Example of an ILE RPG Program

Today's date will be printed in day, month, year format with ″/″ as the separator.

File Description Specifications

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+...


FFilename++IPEASFRlen+LKlen+AIDevice+.Keywords+++++++++++++++++++++++++++
FTRANSACT IP E K DISK
FEMPLOYEE IF E K DISK
FQSYSPRT O F 80 PRINTER

There are three files defined on the file description specifications:


v The TRANSACT file is defined as the Input Primary file. The ILE RPG program
cycle controls the reading of records from this file.
v The EMPLOYEE file is defined as the Input Full-Procedure file. The reading of
records from this file is controlled by operations in the calculation specifications.
v The QSYSPRT file is defined as the Output Printer file.

Definition Specifications

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+...


D+Name++++++++++ETDsFrom+++To/L+++IDc.Keywords+++++++++++++++++++++++++
D Pay S 8P 2
D Heading1 C ’NUMBER NAME RATE H-
D OURS BONUS PAY ’
D Heading2 C ’______ ________________ ______ _-
D ____ _______ __________’
D CalcPay PR 8P 2
D Rate 5P 2 VALUE
D Hours 10U 0 VALUE
D Bonus 5P 2 VALUE

Using the definition specifications, declare a variable called ″Pay″ to hold an


employees’ weekly pay and two constants ″Heading1″ and ″Heading2″ to aid in
the printing of the report headings.

Calculation Specifications

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+...


/free
chain trn_number emp_rec;
if %found(emp_rec);
pay = CalcPay (emp_rate: trn_hours: trn_bonus);
endif;
/end-free

The coding entries on the calculation specifications include:


v Using the CHAIN operation code, the field TRN_NUMBER from the transaction
file is used to find the record with the same employee number in the employee
file.
v If the CHAIN operation is successful (that is, indicator 99 is off), the pay for that
employee is evaluated. The result is ″rounded″ and stored in the variable called
Pay.

8 ILE RPG Programmer’s Guide


Example of an ILE RPG Program

Output Specifications

*.. 1 ...+... 2 ...+... 3 ...+... 4 ...+... 5 ...+... 6 ...+... 7 ...+...


OFilename++DF..N01N02N03Excnam++++B++A++Sb+Sa+...........................
O..............N01N02N03Field+++++++++YB.End++PConstant/editword/DTformat
OQSYSPRT H 1P 2 3
O 35 ’PAYROLL REGISTER’
O *DATE Y 60
O H 1P 2
O 60 Heading1
O H 1P 2
O 60 Heading2
O D N1PN99 2
O TRN_NUMBER 5
O EMP_NAME 24
O EMP_RATE L 33
O TRN_HOURS L 40
O TRN_BONUS L 49
O Pay 60 ’$ 0. ’
O D N1P 99 2
O TRN_NUMBER 5
O 35 ’** NOT ON EMPLOYEE FILE **’
O T LR
O 33 ’END OF LISTING’

The output specifications describe what fields are to be written on the QSYSPRT
output:
v The Heading Lines that contain the constant string ’PAYROLL REGISTER’ as
well as headings for the detail information will be printed if indicator 1P is on.
Indicator 1P is turned on by the ILE RPG program cycle during the first cycle.
v The Detail Lines are conditioned by the indicators 1P and 99. Detail Lines are
not printed at 1P time. The N99 will only allow the Detail lines to be printed if
indicator 99 is off, which indicates that the corresponding employee record has
been found. If the indicator 99 is on, then the employee number and the
constant string ’** NOT ON EMPLOYEE FILE **’ will be printed instead.
v The Total Line contains the constant string ’END OF LISTING’. It will be printed
during the last program cycle.

A Subprocedure

The subprocedure calculates the pay for the employee using the parameters passed
to it. The resulting value is returned to the caller using the RETURN statement.

The procedure specifications indicate the beginning and end of the procedure. The
definition specifications define the return type of the procedure, the parameters to
the procedure, and the local variable Overtime.

Chapter 1. Overview of the RPG IV Programming Language 9


Example of an ILE RPG Program

P CalcPay B
D CalcPay PI 8P 2
D Rate 5P 2 VALUE
D Hours 10U 0 VALUE
D Bonus 5P 2 VALUE
D Overtime S 5P 2 INZ(0)

/free
// Determine any overtime hours to be paid.
if Hours > 40;
Overtime = (Hours - 40) * Rate * 1.5;
Hours = 40;
endif;
// Calculate the total pay and return it to the caller.
return Rate * Hours + Bonus + Overtime;
/end-free
P CalcPay E

The Entire Source Program

The following figure combines all the specifications used in this program. This is
what you should enter into the source file for this program.

*------------------------------------------------------------------------*
* DESCRIPTION: This program creates a printed output of employee’s pay *
* for the week. *
*------------------------------------------------------------------------*
H DATEDIT(*DMY/)
*------------------------------------------------------------------------*
* File Definitions *
*------------------------------------------------------------------------*
FTRANSACT IP E K DISK
FEMPLOYEE IF E K DISK
FQSYSPRT O F 80 PRINTER
*------------------------------------------------------------------------*
* Variable Declarations *
*------------------------------------------------------------------------*
D Pay S 8P 2

Figure 4. A Sample Payroll Calculation Program (Part 1 of 3)

10 ILE RPG Programmer’s Guide


Example of an ILE RPG Program

*------------------------------------------------------------------------*
* Constant Declarations *
*------------------------------------------------------------------------*
D Heading1 C ’NUMBER NAME RATE H-
D OURS BONUS PAY ’
D Heading2 C ’______ ________________ ______ _-
D ____ _______ __________’
*------------------------------------------------------------------------*
* Prototype Definition for subprocedure CalcPay *
*------------------------------------------------------------------------*
D CalcPay PR 8P 2
D Rate 5P 2 VALUE
D Hours 10U 0 VALUE
D Bonus 5P 2 VALUE
*------------------------------------------------------------------------*
* For each record in the transaction file (TRANSACT), if the employee *
* is found, compute the employee’s pay and print the details. *
*------------------------------------------------------------------------*
/free
chain trn_number emp_rec;
if %found(emp_rec);
pay = CalcPay (emp_rate: trn_hours: trn_bonus);
endif;
/end-free
*------------------------------------------------------------------------*
* Report Layout *
* -- print the heading lines if 1P is on *
* -- if the record is found (indicator 99 is off) print the payroll *
* details otherwise print an exception record *
* -- print ’END OF LISTING’ when LR is on *
*------------------------------------------------------------------------*
OQSYSPRT H 1P 2 3
O 35 ’PAYROLL REGISTER’
O *DATE Y 60
O H 1P 2
O 60 Heading1
O H 1P 2
O 60 Heading2
O D N1PN99 2
O TRN_NUMBER 5
O EMP_NAME 24
O EMP_RATE L 33
O TRN_HOURS L 40
O TRN_BONUS L 49
O Pay 60 ’$ 0. ’
O D N1P 99 2
O TRN_NUMBER 5
O 35 ’** NOT ON EMPLOYEE FILE **’
O T LR
O 33 ’END OF LISTING’

Figure 4. A Sample Payroll Calculation Program (Part 2 of 3)

Chapter 1. Overview of the RPG IV Programming Language 11


Using the OS/400 System

*------------------------------------------------------------------------*
* Subprocedure -- calculates overtime pay. *
*------------------------------------------------------------------------*
P CalcPay B
D CalcPay PI 8P 2
D Rate 5P 2 VALUE
D Hours 10U 0 VALUE
D Bonus 5P 2 VALUE
D Overtime S 5P 2 INZ(0)

/free
// Determine any overtime hours to be paid.
if Hours > 40;
Overtime = (Hours - 40) * Rate * 1.5;
Hours = 40;
endif;
// Calculate the total pay and return it to the caller.
return Rate * Hours + Bonus + Overtime;
/end-free
P CalcPay E

Figure 4. A Sample Payroll Calculation Program (Part 3 of 3)

Using the OS/400 System


The operating system that controls all of your interactions with the iSeries system
is called the Operating System/400 (OS/400) system. From your workstation, the
OS/400 system allows you to:
v Sign on and sign off
v Interact with the displays
v Use the online help information
v Enter control commands and procedures
v Respond to messages
v Manage files
v Run utilities and programs.

If you have internet access, you can obtain a complete list of publications that
discuss the OS/400 system at the following URL:
http://publib.boulder.ibm.com/

You can also order the AS/400 V4 System Library Poster, G325-6334-02.

Interacting with the System


You can manipulate the OS/400 system using Command Language (CL). You
interact with the system by entering or selecting CL commands. The system often
displays a series of CL commands or command parameters appropriate to the
situation on the screen. You then select the desired command or parameters.

Commonly Used Control Language Commands

The following table lists some of the most commonly used CL commands, their
function, and the reasons you might want to use them.

12 ILE RPG Programmer’s Guide


Using the OS/400 System

Table 15. Commonly Used CL Commands

Action CL command Result


Using System Menus
GO MAIN Display main menu
GO INFO Display help menu
GO CMDRPG List commands for RPG
GO CMDCRT List commands for creating
GO CMDxxx List commands for ’xxx’
Calling
CALL program-name
Runs a program
Compiling
CRTxxxMOD Creates xxx Module
CRTBNDxxx Creates Bound xxx Program
Binding
CRTPGM Creates a program from ILE modules
CRTSRVPGM Creates a service program
UPDPGM Updates a bound program object
Debugging
STRDBG Starts ILE source debugger
ENDDBG Ends ILE source debugger
Creating Files
CRTPRTF Creates Print File
CRTPF Creates Physical File
CRTSRCPF Creates Source Physical File
CRTLF Creates Logical File

WebSphere Development Studio for iSeries


WebSphere Development Studio is an application development package to help
you rapidly and cost-effectively increase the number of e-business applications for
the iSeries server. This package consolidates all of the key iSeries development
tools, both host and workstation, into one iSeries offering.

The host development tools have undergone major improvements. We are shipping
new C and C++ compilers, completely refreshed from the latest AIX compilers, to
replace the existing versions of these compilers. This will help customers and
solution providers port e-business solutions from other platforms. ILE RPG has
also made major enhancements. Improved Java interoperability and free-form
C-Specs top the list of enhancements. COBOL has added z/OS migration
capabilities as well as introducing some COBOL/Java interoperability capabilities.

The following components are included in WebSphere Development Studio for


iSeries.

Host components:
v ILE RPG
v ILE COBOL
v ILE C/C++
v Application Development ToolSet (ADTS)
Chapter 1. Overview of the RPG IV Programming Language 13
WebSphere Development Studio for iSeries

Workstation components:
v IBM WebFacing Tool
v iSeries development tools: Remote System Explorer and iSeries projects
v Java development tools (with iSeries enhancements)
v Web development tools (with iSeries enhancements)
v Struts environment support
v Database development tools
v Web services development tools
v Server development tools
v XML development tools
v CODE
v VisualAge RPG
v Integrated iSeries debugger

WebSphere Development Studio Client for iSeries


WebSphere Development Studio Client for iSeries (Development Studio Client) is
an application development package of workstation tools that helps you rapidly
and cost-effectively increase the number of e-business applications for the iSeries
server.

This package consolidates all of the key iSeries workstation-based development


tools into one iSeries offering. It is also an included entitlement for purchasers of
WebSphere Development Studio for iSeries.

WebSphere Development Studio Client for iSeries Feature List:


The workbench-based integrated development environment
IBM WebSphere Development Studio Client for iSeries uses WebSphere
Studio Workbench (WSWB) version 2.1.
The IBM WebFacing Tool
The IBM WebFacing Tool can convert your DDS display source files into an
application that can be run in a browser.
Remote System Explorer and iSeries Development Tools
The Remote System Explorer, included as a part of iSeries development
tools, encompasses the framework, user interface, editing, and file,
command, and job actions of iSeries capability.
iSeries Java development tools
Java development tools and iSeries Java development tools give you the
ability to develop Java applications and write, compile, test, debug, and
edit programs written in the Java programming language for Java
applications development.
iSeries Web development tools
Web development tools give you the ability to create new e-business
applications that use a Web-based front end to communicate with the
business logic in an ILE and non-ILE language program residing on an
iSeries host.
Struts environment support
Development Studio Client offers support for Struts and the Web Diagram
editor.

14 ILE RPG Programmer’s Guide


WebSphere Development Studio for iSeries

Database development tools


Database development tools support any local or remote database that has
a Java Database Connectivity (JDBC) driver.
Web services development tools
Web services development tools allow developers to create modular
applications that can be invoked on the World Wide Web.
Server development tools
Server development tools are used to test applications in a local or
remotely installed run-time environment.
XML development tools
XML development tools support any XML-based development.
CODE (CoOperative Development Environment)
CODE is the classic set of Windows tools for iSeries development. It gives
you a suite of utilities for creating source and DDS files, and managing
your projects.
VisualAge RPG
VisualAge RPG is a visual development environment that allows you to
create and maintain client/server applications on the workstation.
Integrated iSeries debugger
The integrated iSeries debugger helps you debug code that is running on
the iSeries system or on your Windows system, using a graphical user
interface on your workstation.

If you want to learn more about WebSphere Development Studio Client for iSeries,
see the most current information available on the World Wide Web at
ibm.com/software/awdtools/iseries/.

Chapter 1. Overview of the RPG IV Programming Language 15


16 ILE RPG Programmer’s Guide
Chapter 2. RPG Programming in ILE
ILE RPG is an implementation of the RPG IV programming language in the
Integrated Language Environment. It is one of the family of ILE compilers
available on the iSeries system.

ILE is a recent approach to programming on the iSeries system. It is the result of


major enhancements to the iSeries machine architecture and the OS/400 operating
system. The ILE family of compilers includes: ILE RPG, ILE C, ILE COBOL, ILE
CL, and VisualAge for C++. Table 16 lists the programming languages supported
by the OS/400 operating system. In addition to the support for the ILE languages,
support for the original program model (OPM) and extended program model
(EPM) languages has been retained.
Table 16. Programming Languages Supported on the iSeries
Integrated Language Original Program Model Extended Program Model
Environment (ILE) (OPM) (EPM)
C++ BASIC (PRPQ) FORTRAN
C CL PASCAL (PRPQ)
CL COBOL
COBOL PL/I (PRPQ)
RPG RPG

Compared to OPM, ILE provides RPG users with improvements or enhancements


in the following areas of application development:
v Program creation
v Program management
v Program call
v Source debugging
v Bindable application program interfaces (APIs)

Each of the above areas is explained briefly in the following paragraphs and
discussed further in the following chapters.

Program Creation
In ILE, program creation consists of:
1. Compiling source code into modules
2. Binding (combining) one or more modules into a program object

You can create a program object much like you do in the OPM framework, with a
one-step process using the Create Bound RPG Program (CRTBNDRPG) command.
This command creates a temporary module which is then bound into a program
object. It also allows you to bind other objects through the use of a binding
directory.

Alternatively, you may create a program using separate commands for compilation
and binding. This two-step process allows you to reuse a module or update one

© Copyright IBM Corp. 1994, 2004 17


RPG Programming in ILE

module without recompiling the other modules in a program. In addition, because


you can combine modules from any ILE language, you can create and maintain
mixed-language programs.

In the two-step process, you create a module object using the Create RPG Module
(CRTRPGMOD) command. This command compiles the source statements into a
module object. A module is a nonrunnable object; it must be bound into a program
object to be run. To bind one or more modules together, use the Create Program
(CRTPGM) command.

Service programs are a means of packaging the procedures in one or more


modules into a separately bound object. Other ILE programs can access the
procedures in the service program, although there is only one copy of the service
program on the system. The use of service programs facilitates modularity and
maintainability. You can use off-the-shelf service programs developed by third
parties or, conversely, package your own service programs for third-party use. A
service program is created using the Create Service Program (CRTSRVPGM)
command.

You can create a binding directory to contain the names of modules and service
programs that your program or service program may need. A list of binding
directories can be specified when you create a program on the CRTBNDRPG,
CRTSRVPGM, and CRTPGM commands. They can also be specified on the
CRTRPGMOD command; however, the search for a binding directory is done when
the module is bound at CRTPGM or CRTSRVPGM time. A binding directory can
reduce program size because modules or service programs listed in a binding
directory are used only if they are needed.

Figure 5 shows the two approaches to program creation.

RPG IV source specifications


Externally described files
Copy source text

ILE HLL Modules, RPG Module


Service Programs (CRTRPGMOD)

ILE Program ILE Program


(CRTBNDRPG) (CRTPGM)

One-Step Process Two-Step Process

Figure 5. Program Creation in ILE

Once a program is created you can update the program using the Update Program
(UPDPGM) or Update Service Program (UPDSRVPGM) commands. This is useful,
because it means you only need to have the new or changed module objects
available to update the program.

For more information on the one-step process, see Chapter 6, “Creating a Program
with the CRTBNDRPG Command,” on page 59. For more information on the
two-step process, see Chapter 7, “Creating a Program with the CRTRPGMOD and

18 ILE RPG Programmer’s Guide


RPG Programming in ILE

CRTPGM Commands,” on page 75. For more information on service programs, see
Chapter 8, “Creating a Service Program,” on page 91.

Program Management
ILE provides a common basis for:
v Managing program flow
v Sharing resources
v Using application program interfaces (APIs)
v Handling exceptions during a program’s run time

It gives RPG users much better control over resources than was previously
possible.

ILE programs and service programs are activated into activation groups which are
specified at program-creation time. The process of getting a program or service
program ready to run is known as activation. Activation allocates resources within
a job so that one or more programs can run in that space. If the specified activation
group for a program does not exist when the program is called, then it is created
within the job to hold the program’s activation.

An activation group is the key element governing an ILE application’s resources


and behavior. For example, you can scope commitment-control operations to the
activation group level. You can also scope file overrides and shared open data
paths to the activation group of the running application. Finally, the behavior of a
program upon termination is also affected by the activation group in which the
program runs.

For more information on activation groups, see “Managing Activation Groups” on


page 110.

You can dynamically allocate storage for a run-time array using the bindable APIs
provided for all ILE programming languages. These APIs allow single- and
mixed-language applications to access a central set of storage management
functions and offer a storage model to languages that do not now provide one.
RPG offers some storage management capabilities using operation codes. For more
information on storage management, see “Managing Dynamically-Allocated
Storage” on page 113.

Program Call
In ILE, you can write applications in which ILE RPG programs and OPM RPG/400
programs continue to interrelate through the traditional use of dynamic program
calls. When using such calls, the calling program specifies the name of the called
program on a call statement. The called program’s name is resolved to an address
at run time, just before the calling program passes control to the called program.

You can also write ILE applications that can interrelate with faster static calls.
Static calls involve calls between procedures. A procedure is a self-contained set of
code that performs a task and then returns to the caller. An ILE RPG module
consists of an optional main procedure followed by zero or more subprocedures.
Because the procedure names are resolved at bind time (that is, when you create
the program), static calls are faster than dynamic calls.

Static calls also allow

Chapter 2. RPG Programming in ILE 19


RPG Programming in ILE

v Operational descriptors
v Omitted parameters
v The passing of parameters by value
v The use of return values
v A greater number of parameters to be passed

Operational descriptors and omitted parameters can be useful when calling


bindable APIs or procedures written in other ILE languages.

For information on running a program refer to Chapter 9, “Running a Program,”


on page 103. For information on program/procedure call, refer to Chapter 10,
“Calling Programs and Procedures,” on page 129.

Source Debugging
Use WebSphere Development Studio Client for iSeries. This is the recommended
method and documentation about debugging programs and appears in that
product’s online help. With the integrated iSeries debugger you can debug your
program running on the iSeries server from a graphical user interface on your
workstation. You can also set breakpoints directly in your source before running
the debugger. The integrated iSeries debugger client user interface also enables you
to control program execution. For example, you can run your program, set line,
watch, and service entry point breakpoints, step through program instructions,
examine variables, and examine the call stack. You can also debug multiple
applications, even if they are written in different languages, from a single debugger
window. Each session you debug is listed separately in the Debug view.

In ILE, you can perform source-level debugging on any single- or mixed-language


ILE application. The ILE source debugger also supports OPM programs. You can
control the flow of a program by using debug commands while the program is
running. You can set conditional and unconditional job or thread breakpoints prior
to running the program. After you call the program, you can then step through a
specified number of statements, and display or change variables. When a program
stops because of a breakpoint, a step command, or a run-time error, the pertinent
module is shown on the display at the point where the program stopped. At that
point, you can enter more debug commands.

For information on the debugger, refer to Chapter 12, “Debugging Programs,” on


page 197.

Bindable APIs
ILE offers a number of bindable APIs that can be used to supplement the function
currently offered by ILE RPG. The bindable APIs provide program calling and
activation capability, condition and storage management, math functions, and
dynamic screen management.

Some APIs that you may wish to consider using in an ILE RPG application
include:
v CEETREC – Signal the Termination-Imminent Condition
v CEE4ABN – Abnormal End
v CEECRHP – Create your own heap
v CEEDSHP – Discard your own heap
v CEEFRST – Free Storage in your own heap
20 ILE RPG Programmer’s Guide
RPG Programming in ILE

v CEEGTST – Get Heap Storage in your own heap


v CEECZST – Reallocate Storage in your own heap
v CEEDOD – Decompose Operational Descriptor

Note: You cannot use these or any other ILE bindable APIs from within a program
created with DFTACTGRP(*YES). This is because bound calls are not
allowed in this type of program.

For more information on these ILE bindable APIs, see Chapter 9, “Running a
Program,” on page 103.

Multithreaded Applications
The iSeries system now supports multithreading. ILE RPG does not directly
support initiating or managing program threads. However, ILE RPG procedures
can run as threads in multithreaded environments. If you want to call an ILE RPG
procedure in a multithreaded application, you must ensure that the ILE RPG
procedure is threadsafe. You must also ensure that any system functions that your
procedure accesses are also threadsafe.

The THREAD(*SERIALIZE) control specification keyword can be specified to help


you achieve thread safety for an ILE RPG module. Specifying
THREAD(*SERIALIZE) will protect most of your variables and all your internal
control structures from being accessed improperly by multiple threads. The thread
safe module will be locked when a procedure in the module is entered and
unlocked when when no procedure in the module is still running. This serialized
access, ensures that only one thread is active in any one module, within an
activation group, at any one time. However, it is still up to the programmer to
handle thread safety for storage that is shared across modules. This is done by
adding logic in the application to synchronize access to the storage.

For more information, see “Multithreading Considerations” on page 158.

Chapter 2. RPG Programming in ILE 21


22 ILE RPG Programmer’s Guide
Chapter 3. Program Creation Strategies
There are many approaches you can take in creating programs using an ILE
language. This section presents three common strategies for creating ILE programs
using ILE RPG or other ILE languages.
1. Create a program using CRTBNDRPG to maximize OPM compatibility.
2. Create an ILE program using CRTBNDRPG.
3. Create an ILE program using CRTRPGMOD and CRTPGM.

The first strategy is recommended as a temporary one. It is intended for users who
have OPM applications and who, perhaps due to lack of time, cannot move their
applications to ILE all at once. The second strategy can also be a temporary one. It
allows you time to learn more about ILE, but also allows you to immediately use
some of its features. The third strategy is more involved, but offers the most
flexibility.

Both the first and second strategy make use of the one-step program creation
process, namely, CRTBNDRPG. The third strategy uses the two-step program
creation process, namely, CRTRPGMOD followed by CRTPGM.

Strategy 1: OPM-Compatible Application


Strategy 1 results in an ILE program that interacts well with OPM programs. It
allows you to take advantage of RPG IV enhancements, but not all of the ILE
enhancements. You may want such a program temporarily while you complete
your migration to ILE.

Method
Use the following general approach to create such a program:
1. Convert your source to RPG IV using the CVTRPGSRC command.
Be sure to convert all /COPY members that are used by the source you are
converting.
2. Create a program object using the CRTBNDRPG command, specifying
DFTACTGRP(*YES).

Specifying DFTACTGRP(*YES) means that the program object will run only in the
default activation group. (The default activation group is the activation group
where all OPM programs are run.) As a result, the program object will interact
well with OPM programs in the areas of override scoping, open scoping, and
RCLRSC.

When you use this approach you cannot make use of ILE static binding. This
means that you cannot code a bound procedure call in your source, nor can you
use the BNDDIR or ACTGRP parameters on the CRTBNDRPG command when
creating this program.

Example of OPM-Compatible Program


Figure 6 on page 24 shows the run-time view of a sample application where you
might want an OPM-compatible program. The OPM application consisted of a CL

© Copyright IBM Corp. 1994, 2004 23


OPM-Compatible Application

program and two RPG programs. In this example, one of the RPG programs has
been moved to ILE; the remaining programs are unchanged.

Job
Default Activation Group

*PGM(X)

OPM CL

*PGM(Y)

ILE RPG

*PGM(Z)

OPM RPG

Figure 6. OPM-Compatible Application

Effect of ILE
The following deals with the effects of ILE on the way your application handles:
Program call OPM programs behave as before. The system automatically creates
the OPM default activation group when you start your job, and all
OPM applications run in it. One program can call another program
in the default activation group by using a dynamic call.
Data Storage for static data is created when the program is activated,
and it exists until the program is deactivated. When the program
ends (either normally or abnormally), the program’s storage is
deleted. To clean up storage for a program that returns without
ending, use the Reclaim Resource (RCLRSC) command.
Files File processing is the same as in previous releases. Files are closed
when the program ends normally or abnormally.
Errors As in previous releases, the compiler handles errors within each
program separately. The errors you see that originated within your
program are the same as before. However, the errors are now
communicated between programs by the ILE condition manager, so
you may see different messages between programs. The messages
may have new message IDs, so if your CL program monitors for a
specific message ID, you may have to change that ID.

Related Information
Converting to RPG IV “Converting Your Source” on page 420
One-step creation process Chapter 6, “Creating a Program with the
CRTBNDRPG Command,” on page 59
ILE static binding Chapter 10, “Calling Programs and Procedures,” on
page 129; also ILE Concepts

24 ILE RPG Programmer’s Guide


OPM-Compatible Application

Exception handling differences


“Differences between OPM and ILE RPG Exception
Handling” on page 256

Strategy 2: ILE Program Using CRTBNDRPG


Strategy 2 results in an ILE program that can take advantage of ILE static binding.
Your source can contain static procedure calls because you can bind the module to
other modules or service programs using a binding directory. You can also specify
the activation group in which the program will run.

Method
Use the following general approach to create such a program:
1. If starting with RPG III source, convert your source to RPG IV using the
CVTRPGSRC command.
If converting, be sure to convert all /COPY members and any programs that
are called by the source you are converting. Also, if you are using CL to call the
program, you should also make sure that you are using ILE CL instead of OPM
CL.
2. Determine the activation group the program will run in.
You may want to name it after the application name, as in this example.
3. Identify the names of the binding directories, if any, to be used.
It is assumed with this approach that if you are using a binding directory, it is
one that is already created for you. For example, there may be a third-party
service program that you may want to bind to your source. Consequently, all
you need to know is the name of the binding directory.
4. Create an ILE program using CRTBNDRPG, specifying DFTACTGRP(*NO), the
activation group on the ACTGRP parameter, and the binding directory, if any,
on the BNDDIR parameter.

Note that if ACTGRP(*CALLER) is specified and this program is called by a


program running in the default activation group, then this program will behave
according to ILE semantics in the areas of override scoping, open scoping, and
RCLRSC.

The main drawback of this strategy is that you do not have a permanent module
object that you can later reuse to bind with other modules to create an ILE
program. Furthermore, any procedure calls must be to modules or service
programs that are identified in a binding directory. If you want to bind two or
more modules without using a binding directory when you create the program,
you need to use the third strategy.

Example of ILE Program Using CRTBNDRPG


Figure 7 on page 26 shows the run-time view of an application in which an ILE CL
program calls an ILE RPG program that is bound to a supplied service program.
The application runs in the named activation group XYZ.

Chapter 3. Program Creation Strategies 25


ILE Program Using CRTBNDRPG

Job
XYZ Activation Group

*PGM(X)

ILE CL

*PGM(Y)

ILE RPG

*SRVPGM(Z)
Supplied Service
Program

Figure 7. ILE Program Using CRTBNDRPG

Effect of ILE
The following deals with the effects of ILE on the way your program handles:
Program call The system automatically creates the activation group if it does not
already exist, when the application starts.
The application can contain dynamic program calls or static
procedure calls. Procedures within bound programs call each other
by using static calls. Procedures call ILE and OPM programs by
using dynamic calls.
Data The lifetime of a program’s storage is the same as the lifetime of
the activation group. Storage remains active until the activation
group is deleted.
The ILE RPG run time manages data so that the semantics of
ending programs and reinitializing the data are the same as for
OPM RPG, although the actual storage is not deleted as it was
when an OPM RPG program ended. Data is reinitialized if the
previous call to the procedure ended with LR on, or ended
abnormally.
Program data that is identified as exported or imported (using the
keywords EXPORT and IMPORT respectively) is external to the
individual modules. It is known among the modules that are
bound into a program.
Files By default, file processing (including opening, sharing, overriding,
and commitment control) by the system is scoped to the activation
group level. You cannot share files at the data management level
with programs in different activation groups. If you want to share
a file across activation groups, you must open it at the job level by
specifying SHARE(*YES) on an override command or create the file
with SHARE(*YES).
Errors When you call an ILE RPG program or procedure in the same

26 ILE RPG Programmer’s Guide


ILE Program Using CRTBNDRPG

activation group, if it gets an exception that would previously have


caused it to display an inquiry message, now your calling program
will see that exception first.
If your calling program has an error indicator or *PSSR, the
program or procedure that got the exception will end abnormally
without the inquiry message being displayed. Your calling program
will behave the same (the error indicator will be set on or the
*PSSR will be invoked).
When you call an OPM program or a program or main procedure
in a different activation group, the exception handling will be the
same as in OPM RPG, with each program handling its own
exceptions. The messages you see may have new message IDs, so
if you monitor for a specific message ID, you may have to change
that ID.
Each language processes its own errors and can process the errors
that occur in modules written in another ILE language. For
example, RPG will handle any C errors if an error indicator has
been coded. C can handle any RPG errors.

Related Information
Converting to RPG IV “Converting Your Source” on page 420
One-step creation process Chapter 6, “Creating a Program with the
CRTBNDRPG Command,” on page 59
Activation groups “Managing Activation Groups” on page 110
RCLRSC “Reclaim Resources Command” on page 112
ILE static binding Chapter 10, “Calling Programs and Procedures,” on
page 129; also ILE Concepts
Exception handling differences
“Differences between OPM and ILE RPG Exception
Handling” on page 256
Override and open scope “Overriding and Redirecting File Input and
Output” on page 307 and “Sharing an Open Data
Path” on page 311; also ILE Concepts

Strategy 3: ILE Application Using CRTRPGMOD


This strategy allows you to fully utilize the concepts offered by ILE. However,
while being the most flexible approach, it is also more involved. This section
presents three scenarios for creating:
v A single-language application
v A mixed-language application
v An advanced application

The effect of ILE is the same as described in “Effect of ILE” on page 26.

You may want to read about the basic ILE concepts in ILE Concepts before using
this approach.

Chapter 3. Program Creation Strategies 27


ILE Application Using CRTRPGMOD

Method
Because this approach is the most flexible, it includes a number of ways in which
you might create an ILE application. The following list describes the main steps
that you may need to perform:
1. Create a module from each source member using the appropriate command, for
example, CRTRPGMOD for RPG source, CRTCLMOD for CL source, etc..
2. Determine the ILE characteristics for the application, for example:
v Determine which module will contain the procedure that will be the starting
point for the application. The module you choose as the entry module is the
first one that you want to get control. In an OPM application, this would be
the command processing program, or the program called because a menu
item was selected.
v Determine the activation group the application will run in. (Most likely you
will want to run in a named activation group, where the name is based on
the name of the application.)
v Determine the exports and imports to be used.
3. Determine if any of the modules will be bound together to create a service
program. If so, create the service programs using CRTSRVPGM.
4. Identify the names of the binding directories, if any, to be used.
It is assumed with this approach that if you are using a binding directory, it is
one that is already created for you. For example, there may be a third-party
service program that you may want to bind to your source. Consequently, all
you need to know is the name of the binding directory.
5. Bind the appropriate modules and service programs together using CRTPGM,
specifying values for the parameters based on the characteristics determined in
step 2.

An application created using this approach can run fully protected, that is, within
its own activation group. Furthermore, it can be updated easily through use of the
UPDPGM or UPDSRVPGM commands. With these commands you can add or
replace one or more modules without having to re-create the program object.

Single-Language ILE Application Scenario


In this scenario you compile multiple source files into modules and bind them into
one program that is called by an ILE RPG program. Figure 8 on page 29 shows the
run-time view of this application.

28 ILE RPG Programmer’s Guide


ILE Application Using CRTRPGMOD

Job
XY Activation Group

*PGM(X)

RPG

*PGM(Y)
RPG *MODULE(Y1)

RPG *MODULE(Y2)

RPG *MODULE(Y3)

RPG *MODULE(Y4)

Figure 8. Single-Language Application Using CRTRPGMOD and CRTPGM

The call from program X to program Y is a dynamic call. The calls among the
modules in program Y are static calls.

See “Effect of ILE” on page 26 for details on the effects of ILE on the way your
application handles calls, data, files and errors.

Mixed-Language ILE Application Scenario


In this scenario, you create integrated mixed-language applications. The main
module, written in one ILE language, calls procedures written in another ILE
language. The main module opens files that the other modules then share. Because
of the use of different languages, you may not expect consistent behavior.
However, ILE ensures that this occurs.

Figure 9 on page 30 shows the run-time view of an application containing a


mixed-language ILE program where one module calls a non-bindable API,
QUSCRTUS (Create User Space).

Chapter 3. Program Creation Strategies 29


ILE Application Using CRTRPGMOD

Job
Y Activation Group
*PGM(Y)

CL *MODULE(Y1)

RPG *MODULE(Y2)

C *MODULE(Y3) Default Activation Group


*PGM(QUSCRTUS)

RPG *MODULE(Y4)

Figure 9. Mixed-Language Application

The call from program Y to the OPM API is a dynamic call. The calls among the
modules in program Y are static calls.

See “Effect of ILE” on page 26 for details on the effects of ILE on the way your
application handles calls, data, files and errors.

Advanced Application Scenario


In this scenario, you take full advantage of ILE function, including service
programs. The use of bound calls, used for procedures within modules and service
programs, provide improved performance especially if the service program runs in
the same activation group as the caller.

Figure 10 on page 31 shows an example in which an ILE program is bound to two


service programs.

30 ILE RPG Programmer’s Guide


ILE Application Using CRTRPGMOD

Job
XYZ Activation Group
*PGM(X)
CL *MODULE(X1)
*SRVPGM(Y)

RPG *MODULE(X2) RPG

*SRVPGM(Z)
C *MODULE(Z1)

CL *MODULE(Z2)

Figure 10. Advanced Application

The calls from program X to service programs Y and Z are static calls.

See “Effect of ILE” on page 26 for details on the effects of ILE on the way your
application handles calls, data, files and errors.

Related Information
Two-step creation process Chapter 7, “Creating a Program with the
CRTRPGMOD and CRTPGM Commands,” on page
75
Activation groups “Managing Activation Groups” on page 110
ILE static binding Chapter 10, “Calling Programs and Procedures,” on
page 129; also ILE Concepts
Exception Handling Chapter 13, “Handling Exceptions,” on page 251;
also ILE Concepts
Service programs Chapter 8, “Creating a Service Program,” on page
91; also ILE Concepts
Updating a Program “Using the UPDPGM Command” on page 88

A Strategy to Avoid
ILE provides many alternatives for creating programs and applications. However,
not all are equally good. In general, you should avoid a situation where an
application consisting of OPM and ILE programs is split across the OPM default
activation group and a named activation group. In other words, try to avoid the
scenario shown in Figure 11 on page 32.

Chapter 3. Program Creation Strategies 31


A Strategy to Avoid

#
Job
Default Activation Group

*PGM(X)

CL

QILE Activation Group


*PGM(Y)

RPG

*SRVPGM(Z)

RPG

#
# Figure 11. Scenario to Avoid. An application has a CL program in the OPM default activation
# group and ILE programs in a named activation group.

# When an application is split across the default activation group and any named
# activation group, you are mixing OPM behavior with ILE behavior. For example,
programs in the default activation group may be expecting the ILE programs to
free their resources when the program ends. However, this will not occur until the
activation group ends.

Similarly, the scope of overrides and shared ODPs will be more difficult to manage
when an application is split between the default activation group and a named
one. By default, the scope for the named group will be at the activation group
level, but for the default activation group, it can be either call level or job level, not
activation group level.

# Note: Calling an ILE program from the command line, or from an OPM program
# that simply makes a call, is not a problem. The problems, which can all be
# solved, stem from OPM programs and ILE programs using shared resources
# such as overrides and commitment control, and from OPM programs trying
# to using OPM commands such as RCLRSC which have no effect on
# programs running in a named activation group.

32 ILE RPG Programmer’s Guide


Chapter 4. Creating an Application Using Multiple Procedures
The ability to code more than one procedure in an ILE RPG module greatly
enhances your ability to code a modular application. This chapter discusses why
and how you might use such a module in your application. Specifically this
chapter presents:
v Overview of key concepts
v Example of module with more than one procedure
v Coding considerations

Refer to the end of this section to see where to look for more detailed information
on coding modules with multiple procedures.

A Multiple Procedures Module — Overview


An ILE program consists of one or more modules; a module is made up of one or
more procedures. A procedure is any piece of code that can be called with a bound
call. ILE RPG has two kinds of procedures: a main procedure and a subprocedure.
The way to call a subprocedure is with a prototyped call.

Note: In the RPG documentation, the term ’procedure’ refers to both main and
subprocedures.

Main Procedures and Subprocedures


An ILE RPG module consists of a main procedure and zero or more
subprocedures. (If there are subprocedures, the main procedure is optional.) A
main procedure is a procedure that can be specified as the program entry
procedure (and so receive control when an ILE program is first called). The main
procedure is defined in the main source section, which is the set of H, F, D, I, C,
and O specifications that begin a module. In V3R1, all ILE RPG modules had a
main procedure and no other procedures.

A subprocedure is a procedure that is specified after the main source section. A


subprocedure differs from a main procedure primarily in that:
v Names that are defined within subprocedure are not accessible outside the
subprocedure.
v No cycle code is generated for the subprocedure.
v The call interface must be prototyped.
v Calls to subprocedures must be bound procedure calls.
v Only P, D, and C specifications can be used.

Subprocedures can provide independence from other procedures because the data
items are local. Local data items are normally stored in automatic storage, which
means that the value of a local variable is not preserved between calls to the
procedure.

Subprocedures offer another feature. You can pass parameters to a subprocedure


by value, and you can call a subprocedure in an expression to return a value.

© Copyright IBM Corp. 1994, 2004 33


Multiple Procedures Module

Figure 12 shows what a module might look like with multiple procedures.

*MODULE
Main Procedure
H specifications
F specifications Global
Main D specifications - Data items visible Scope
Source throughout module
Section I specifications
C specifications
O specifications

Subprocedure 1
P specification
D specifications - Data items visible only
Local
to Subprocedure 1
Scope
C specifications - Can access local and
global data items
P specifications

Subprocedure 2
P specification
D specifications - Data items visible
Local
only to Subprocedure 2
Scope
C specifications - Can access local and
global data items
P specifications

Program Data - part of main source section

Figure 12. An ILE RPG module with Multiple Procedures

As the picture suggests, you can now code subprocedures to handle particular
tasks. These tasks may be needed by the main procedures or by other modules in
the application. Furthermore, you can declare temporary data items in
subprocedures and not have to worry if you have declared them elsewhere in the
module.

Prototyped Calls
To call a subprocedure, you must use a prototyped call. You can also call any
program or procedure that is written in any language in this way. A prototyped
call is one where the call interface is checked at compile time through the use of a
prototype. A prototype is a definition of the call interface. It includes the following
information:
v Whether the call is bound (procedure) or dynamic (program)
v How to find the program or procedure (the external name)
v The number and nature of the parameters
v Which parameters must be passed, and which are optionally passed

34 ILE RPG Programmer’s Guide


Multiple Procedures Module

v Whether operational descriptors are passed (for a procedure)


v The data type of the return value, if any (for a procedure)

The prototype is used by the compiler to call the program or procedure correctly,
and to ensure that the caller passes the correct parameters. Figure 13 shows a
prototype for a procedure FmtCust, which formats various fields of a record into
readable form. It has two output parameters.

// Prototype for procedure FmtCust (Note the PR on definition


// specification.) It has two output parameters.
D FmtCust PR
D Name 100A
D Address 100A

Figure 13. Prototype for FmtCust Procedure

# To format an address, the application calls a procedure FmtAddr. FmtAddr has


# several input parameters, and returns a varying character field. Figure 14 shows
# the prototype for FmtAddr.

# //---------------------------------------------------------
# // FmtAddr - procedure to produce an address in the form
# //---------------------------------------------------------
# D FmtAddr PR 100A VARYING
# D streetNum 10I 0 CONST
# D streetName 50A CONST
# D city 20A CONST
# D state 15A CONST
# D zip 5P 0 CONST
#
#
# Figure 14. Prototype for FmtAddr Procedure
#
If the program or procedure is prototyped, you call it with CALLP or within an
expression if you want to use the return value. You pass parameters in a list that
follows the name of the prototype, for example, name (parm1 : parm2 : ...).

Figure 15 shows a call to FmtCust. Note that the names of the output parameters,
shown above in Figure 13, do not match those in the call statement. The parameter
names in a prototype are for documentation purposes only. The prototype serves to
describe the attributes of the call interface. The actual definition of call parameters
takes place inside the procedure itself.

C CALLP FmtCust(RPTNAME : RPTADDR)

Figure 15. Calling the FmtCust Procedure

Using prototyped calls you can call (with the same syntax):
v Programs that are on the system at run time
v Exported procedures in other modules or service programs that are bound in the
same program or service program
v Subprocedures in the same module

Chapter 4. Creating an Application Using Multiple Procedures 35


Multiple Procedures Module

# FmtCust calls FmtAddr to format the address. Because FmtCust wants to use the
# return value, the call to FmtAddr is made in an expression. Figure 16 shows the
# call.

# //--------------------------------------------------------------
# // Call the FmtAddr procedure to handle the address
# //--------------------------------------------------------------
# Address = FmtAddress (STREETNUM : STREETNAME :
# CITY : STATE : ZIP);
##
# Figure 16. Calling the FmtAddr Procedure
#
The use of procedures to return values, as in the above figure, allows you to write
any user-defined function you require. In addition, the use of a prototyped call
# interface enables a number of options for parameter passing.
v Prototyped parameters can be passed in several ways: by reference, by value (for
procedures only), or by read-only reference. The default method for RPG is to
pass by reference. However, passing by value or by read-only reference gives
you more options for passing parameters.
v If the prototype indicates that it is allowed for a given parameter, you may be
able to do one or more of the following:
– Pass *OMIT
– Leave out a parameter entirely
– Pass a shorter parameter than is specified (for character and graphic
parameters, and for array parameters)

Example of Module with Multiple Procedures


Now let us look at an example of a multiple procedures module. In this
’mini-application’ we are writing a program ARRSRPT to produce a report of all
customers whose accounts are in arrears. We will create the basic report as a
module, so that it can be bound to other modules, if necessary. There are two main
tasks that are required for this module:
1. Determine that a record of an account from a customer file is in arrears.
2. Format the data into a form that is suitable for the report.

We have decided to code each task as a subprocedure. Conceptually, the module


will look something like that shown in Figure 17 on page 37.

36 ILE RPG Programmer’s Guide


Example of Module with Multiple Procedures

ARRSRPT MODULE
Main Procedure
Open file, read record, write
output records, close files

InArrears
Subprocedure to determine if
customer record is in arrears

FmtCust
Subprocedure to format
customer data into report form

Figure 17. Components of the ARRSRPT Module

Now consider the first subprocedure, InArrears, which is shown in Figure 18 on


page 38. InArrears is called by the main procedure to determine if the current
record is in arrears.

TIP
When coding subprocedures that use global fields, you may want to establish
a naming convention that shows the item to be global. In this example, the
uppercase field names indicate DDS fields. Another option would be to prefix
’g_’, or some other string to indicate global scope.

If the record is in arrears, the subprocedure returns ’1’ to the main procedure.

Chapter 4. Creating an Application Using Multiple Procedures 37


Example of Module with Multiple Procedures

//--------------------------------------------------------------
// InArrears
//
// Parameters: (none)
// Globals: DUEDATE, AMOUNT, CurDate
//
// Returns: ’1’ if the customer is in arrears
//--------------------------------------------------------------
P InArrears B 1
D InArrears PI 1A 2
// Local declarations
D DaysLate S 10I 0 3
D DateDue S D 3
// Body of procedure
/free
DateDue = %date (DUEDATE: *ISO);
DaysLate = %diff (CurDate: DateDue: *d);
// The data in the input file comes from another type
// of computer, and the AMOUNTC field is a character
// string containing the numeric value. This string
// must be converted to the numeric AMOUNT field
// for printing.
# AMOUNT = %dec(AMOUNTC : 31 : 9);
if DaysLate > 60 AND AMOUNT > 100.00;
return ’1’; 4
endif;
return ’0’; 4 5
/end-free
P InArrears E 1

Figure 18. Source for Subprocedure InArrears

Figure 18 shows the main elements that are common to all subprocedures.
1 All subprocedures begin and end with procedure specifications.
2 After the Begin-Procedure specification (B in position 24 of the procedure
specification), you code a procedure interface definition. The return value,
if any, is defined on the PI specification. Any parameters are listed after the
PI specification.
3 Any variables or prototypes that are used by the subprocedure are defined
after the procedure interface definition.
4 The return value, if specified, is returned to the caller with a RETURN
operation.
5 If the record is not in arrears, the subprocedure returns ’0’ to the main
procedure.

For all subprocedures, and also for a main procedure with prototyped entry
parameters, you need to define a procedure interface. A procedure interface
definition is a repeat of the prototype information within the definition of a
procedure. It is used to define the entry parameters for the procedure. The
procedure interface definition is also used to ensure that the internal definition of
the procedure is consistent with the external definition (the prototype). In the case
of InArrears, there are no entry parameters.

Consider next the subprocedure FmtCust, which is shown in Figure 19 on page 39.
FmtCust is called by ARRSRPT to format the relevant fields of a record into an
output record for the final report. (The record represents an account that is in

38 ILE RPG Programmer’s Guide


Example of Module with Multiple Procedures

arrears.) FmtCust uses global data, and so does not have any input parameters. It
formats the data into two output fields: one for the name, and one for the address.

//--------------------------------------------------------------
// FmtCust formats CUSTNAME, CUSTNUM, STREETNAME etc into
// readable forms
//
// Parameters: Name (output)
// Address (output)
// Globals: CUSTNAME, CUSTNUM, STREETNUM, STREETNAME, CITY
// STATE, ZIP
//--------------------------------------------------------------

P FmtCust B
D FmtCust PI
D Name 100A
D Address 100A

/free
//--------------------------------------------------------------
// CUSTNAME and CUSTNUM are formatted to look like this:
// A&P Electronics (Customer number 157)
//--------------------------------------------------------------
Name = CUSTNAME + ’ ’ + ’(Customer number ’
+ %char(CUSTNUM) + ’)’;
# //--------------------------------------------------------------
# // Call the FmtAddr procedure to handle the address
# //--------------------------------------------------------------
#
# Address = FmtAddress (STREETNUM : STREETNAME :
# CITY : STATE : ZIP);
# /end-free
# P FmtCust E

Figure 19. Source for Subprocedure FmtCust

# Finally, consider the last subprocedure of this application, FmtAddr. Notice that
# FmtAddr does not appear in the ARRSRPT module, that is shown in Figure 17 on
# page 37. We decided to place FmtAddr inside another module called FMTPROCS.
# FMTPROCS is a utility module that will contain any conversion procedures that
# other modules might need to use.

# Figure 20 on page 40 shows the source of the module FMTPROCS. Since this is a
# prototyped procedure, it needs the prototype to be available. So that the prototype
# can be shared, we have placed the prototype into a /COPY file.

Chapter 4. Creating an Application Using Multiple Procedures 39


Example of Module with Multiple Procedures

# //=================================================================
# // Source for module FMTPROCS. This module does not have a
# // main procedure, as indicated by the keyword NOMAIN.
# //=================================================================
# H NOMAIN
# //-----------------------------------------------------------------
# // The prototype must be available to EACH module containing
# // a prototyped procedure. The /COPY pulls in the prototype
# // for FmtAddr.
# //-----------------------------------------------------------------
# D/COPY QRPGLESRC,FMTPROC_P
# P FmtAddr B EXPORT
# D FmtAddr PI 100A VARYING
# D streetNum 10I 0 CONST
# D streetName 50A CONST
# D city 20A CONST
# D state 15A CONST
# D zip 5P 0 CONST
# /free
# //--------------------------------------------------------------
# // STREETNUM, STREETNAME, CITY, STATE, and ZIP are formatted to
# // look like:
# // 27 Garbanzo Avenue, Smallville IN 51423
# //--------------------------------------------------------------
# return %char(streetNum) + ’ ’ + %trimr(streetName)
# + ’, ’ + %trim(city) + ’ ’ + %trim(state)
# + ’ ’ + %editc(zip : ’X’);
# P FmtAddr E
##
# Figure 20. Source for module FMTPROCS, containing subprocedure FmtAddr.
#
# FMTPROCS is a NOMAIN module, meaning that it consists only of
subprocedures; there is no main procedure. A NOMAIN module compiles faster
and requires less storage because there is no cycle code that is created for the
module. You specify a NOMAIN module, by coding the NOMAIN keyword on the
control specification. For more information on NOMAIN modules, see “Program
Creation” on page 45.

The Entire ARRSRPT Program


# The ARRSRPT program consists of two modules: ARRSRPT and FMTPROCS.
# Figure 21 on page 41 shows the different pieces of our mini-application.

40 ILE RPG Programmer’s Guide


Example of Module with Multiple Procedures

Figure 21. The ARRSRPT Application

Figure 22 shows the source for the entire ARRSRPT module.

//=================================================================
// Source for module ARRSRPT. Contains a main procedure and
// two subprocedures: InArrears and FmtCust.
//
// Related Module: CVTPROCS (CharToNum called by InArrears)
//=================================================================
//--------------------------------------------------------------
// F I L E S
//
// CUSTFILE - contains customer information
// CUSTRPT - printer file (using format ARREARS)
//--------------------------------------------------------------
FCUSTFILE IP E DISK
FCUSTRPT O E PRINTER
*--------------------------------------------------------------*
* P R O T O T Y P E S
*--------------------------------------------------------------*
# /COPY QRPGLE,FMTPROC_P
*--------------------------------------------------------------*
* InArrears returns ’1’ if the customer is in arrears
*--------------------------------------------------------------*
D InArrears PR 1A
*--------------------------------------------------------------*
* FmtCust formats CUSTNAME, CUSTNUM, STREETNAME etc into
* readable forms
*--------------------------------------------------------------*
D FmtCust PR
D Name 100A
D Address 100A

Figure 22. ILE RPG Complete Source for ARRSRPT Module (Part 1 of 3)

Chapter 4. Creating an Application Using Multiple Procedures 41


Example of Module with Multiple Procedures

*--------------------------------------------------------------*
* G L O B A L D E F I N I T I O N S
*--------------------------------------------------------------*
D CurDate S D
ICUSTREC 01
*--------------------------------------------------------------*
* M A I N P R O C E D U R E
*--------------------------------------------------------------*
C IF InArrears = ’1’
C CALLP FmtCust(RPTNAME : RPTADDR)
C EVAL RPTNUM = CUSTNUM
C WRITE ARREARS
C ENDIF
C *INZSR BEGSR
# C MOVEL UDATE CurDate
C ENDSR

*--------------------------------------------------------------*
* S U B P R O C E D U R E S
*--------------------------------------------------------------*
# //--------------------------------------------------------------
# // InArrears
# //
# // Parameters: (none)
# // Globals: DUEDATE, AMOUNT, CurDate
# //
# // Returns: ’1’ if the customer is in arrears
# //--------------------------------------------------------------
# P InArrears B
# D InArrears PI 1A
# // Local declarations
# D DaysLate S 10I 0
# D DateDue S D
# // Body of procedure
# /free
# DateDue = %date (DUEDATE: *ISO);
# DaysLate = %diff (CurDate: DateDue: *d);
# // The data in the input file comes from another type
# // of computer, and the AMOUNTC field is a character
# // string containing the numeric value. This string
# // must be converted to the numeric AMOUNT field
# // for printing.
# AMOUNT = %dec(AMOUNTC : 31 : 9);
# if DaysLate > 60 AND AMOUNT > 100.00;
# return ’1’;
# endif;
# return ’0’;
# /end-free
# P InArrears E

Figure 22. ILE RPG Complete Source for ARRSRPT Module (Part 2 of 3)

42 ILE RPG Programmer’s Guide


Example of Module with Multiple Procedures

# //--------------------------------------------------------------
# // FmtCust formats CUSTNAME, CUSTNUM, STREETNAME etc into
# // readable forms
# //
# // Parameters: Name (output)
# // Address (output)
# // Globals: CUSTNAME, CUSTNUM, STREETNUM, STREETNAME, CITY
# // STATE, ZIP
# //--------------------------------------------------------------
#
# P FmtCust B
# D FmtCust PI
# D Name 100A
# D Address 100A
#
# /free
# //--------------------------------------------------------------
# // CUSTNAME and CUSTNUM are formatted to look like this:
# // A&P Electronics (Customer number 157)
# //--------------------------------------------------------------
# Name = CUSTNAME + ’ ’ + ’(Customer number ’
# + %char(CUSTNUM) + ’)’;
# //--------------------------------------------------------------
# // Call the FmtAddr procedure to handle the address
# //--------------------------------------------------------------
#
# Address = FmtAddress (STREETNUM : STREETNAME :
# CITY : STATE : ZIP);
# /end-free
# P FmtCust E

Figure 22. ILE RPG Complete Source for ARRSRPT Module (Part 3 of 3)

Note the following about ARRSRPT:


v The definition specifications begin with the prototypes for the prototyped calls.
# A /COPY file is used to supply the prototype for the called procedure FmtAddr.
The prototypes do not have to be first, but you should establish an order for the
different types of definitions for consistency.
v The date field CurDate is a global field, meaning that any procedure in the
module can access it.
v The main procedure is simple to follow. It contains calculation specifications for
the two main tasks: the I/O, and an initialization routine.
v Each subprocedure that follows the main procedure contains the details of one
of the tasks.

Sample output for the program ARRSRPT is shown in Figure 23.

Customer number: 00001


ABC Electronics (Customer number 1)
15 Arboreal Way, Treetop MN 12345
Amount outstanding: $1234.56 Due date: 1995-05-01

Customer number: 00152


A&P Electronics (Customer number 152)
27 Garbanzo Avenue, Smallville MN 51423
Amount outstanding: $26544.50 Due date: 1995-02-11

Figure 23. Output for ARRSRPT

Chapter 4. Creating an Application Using Multiple Procedures 43


Example of Module with Multiple Procedures

Figure 24 and Figure 25 show the DDS source for the files CUSTFILE and
CUSTRPT respectively.

A*================================================================*
A* FILE NAME : CUSTFILE
A* RELATED PGMS : ARRSRPT
A* DESCRIPTIONS : THIS IS THE PHYSICAL FILE CUSTFILE. IT HAS
A* ONE RECORD FORMAT CALLED CUSTREC.
A*================================================================*
A* CUSTOMER MASTER FILE -- CUSTFILE
A R CUSTREC
A CUSTNUM 5 0 TEXT(’CUSTOMER NUMBER’)
A CUSTNAME 20 TEXT(’CUSTOMER NAME’)
A STREETNUM 5 0 TEXT(’CUSTOMER ADDRESS’)
A STREETNAME 20 TEXT(’CUSTOMER ADDRESS’)
A CITY 20 TEXT(’CUSTOMER CITY’)
A STATE 2 TEXT(’CUSTOMER STATE’)
A ZIP 5 0 TEXT(’CUSTOMER ZIP CODE’)
A AMOUNTC 15 TEXT(’AMOUNT OUTSTANDING’)
A DUEDATE 10 TEXT(’DATE DUE’)

Figure 24. DDS for CUSTFILE

A*================================================================*
A* FILE NAME : CUSTRPT
A* RELATED PGMS : ARRSRPT
A* DESCRIPTIONS : THIS IS THE PRINTER FILE CUSTRPT. IT HAS
A* ONE RECORD FORMAT CALLED ARREARS.
A*================================================================*
A R ARREARS
A 2 6
A ’Customer number:’
A RPTNUM 5 0 2 23
A TEXT(’CUSTOMER NUMBER’)
A RPTNAME 100A 3 10
A TEXT(’CUSTOMER NAME’)
A RPTADDR 100A 4 10
A TEXT(’CUSTOMER ADDRESS’)
A 5 10’Amount outstanding:’
A AMOUNT 10 2 5 35EDTWRD(’ $0. ’)
A TEXT(’AMOUNT OUTSTANDING’)
A 5 50’Due date:’
A DUEDATE 10 5 60
A TEXT(’DATE DUE’)

Figure 25. DDS for CUSTRPT

Coding Considerations
This section presents some considerations that you should be aware of before you
begin designing applications with multiple-procedure modules. The items are
grouped into the following categories:
v General
v Program Creation
v Main Procedures
v Subprocedures

44 ILE RPG Programmer’s Guide


Coding Considerations

General Considerations
v When coding a module with multiple procedures, you will want to make use of
/COPY files, primarily to contain any prototypes that your application may
require. If you are creating a service program, you will need to provide both the
service program and the prototypes, if any.
v Maintenance of the application means ensuring that each component is at the
most current level and that any changes do not affect the different pieces. You
may want to consider using a tool such as Application Development Manager to
maintain your applications.
For example, suppose that another programmer makes a change to the /COPY
file that contains the prototypes. When you request a rebuild of your
application, any module or program that makes use of the /COPY file will be
recompiled automatically. You will find out quickly if the changes to the /COPY
file affect the calls or procedure interfaces in your application. If there are
compilation errors, you can then decide whether to accept the change to
prototypes to avoid these errors, or whether to change the call interface.

Program Creation
v If you specify that a module does not have a main procedure then you cannot
use the CRTBNDRPG command to create the program. (A module does not have
a main procedure if the NOMAIN keyword is specified on a control
specification.) This is because the CRTBNDRPG command requires that the
module contain a program entry procedure and only a main procedure can be a
program entry procedure.
v Similarly, when using CRTPGM to create the program, keep in mind that a
NOMAIN module cannot be an entry module since it does not have a program
entry procedure.
v A program that is created to run in the default OPM activation group (by
specifying DFTACTGRP(*YES) on the CRTBNDRPG command) cannot contain
bound procedure calls.

Main Procedure Considerations


v Because the main procedure is the only procedure with a complete set of
specifications available (except the P specification), it should be used to set up
the environment of all procedures in the module.
v A main procedure is always exported, which means that other procedures in the
program can call the main procedure by using bound calls.
v The call interface of a main procedure can be defined in one of two ways:
1. Using a prototype and procedure interface
2. Using an *ENTRY PLIST without a prototype
v The functionality of an *ENTRY PLIST is similar to a prototyped call interface.
However, a prototyped call interface is much more robust since it provides
parameter checking at compile time. If you prototype the main procedure, then
you specify how it is to be called by specifying either the EXTPROC or EXTPGM
keyword on the prototype definition. If EXTPGM is specified, then an external
program call is used; if EXTPROC is specified or if neither keyword is specified,
it will be called by using a procedure call.
v You cannot define return values for a main procedure, nor can you specify that
its parameters be passed by value.

Chapter 4. Creating an Application Using Multiple Procedures 45


Coding Considerations

Subprocedure Considerations
v Any of the calculation operations may be coded in a subprocedure. However, all
files must be defined globally, so all input and output specifications must be
defined in the main source section. Similarly, all data areas must be defined in
the main procedure, although they can be used in a subprocedure.
v The control specification can only be coded in the main source section since it
controls the entire module.
v A subprocedure can be called recursively.Each recursive call causes a new
invocation of the procedure to be placed on the call stack. The new invocation
has new storage for all data items in automatic storage, and that storage is
unavailable to other invocations because it is local. (A data item that is defined
in a subprocedure uses automatic storage unless the STATIC keyword is
specified for the definition.)
The automatic storage that is associated with earlier invocations is unaffected by
later invocations. All invocations share the same static storage, so later
invocations can affect the value held by a variable in static storage.
Recursion can be a powerful programming technique when properly
understood.
v The run-time behavior of a subprocedure differs somewhat from that of a main
procedure, because there is no cycle code for the subprocedure.
– When a subprocedure ends, it simply returns to the caller. None of the usual
termination activities, such as closing of files, occurs until the main procedure
that is associated with the subprocedure itself ends. You should code a
″cleanup″ subprocedure that is called both by the program entry procedure at
application-end, and by a cancel handler enabled for the program entry
procedure.
An alternative is to code the NOMAIN module so that there is no implicit file
opening or data area locking, and that within any subprocedure, an open is
matched by a close, an IN by an OUT, a CRT<temp obj> by a DLT<temp
obj>, and so on. This alternative applies to modules that may have a
subprocedure active when the main procedure is not active.
– Exception handling within a subprocedure differs from a main procedure
primarily because there is no default exception handler for subprocedures. As
a result, situations where the default handler would be called for a main
procedure correspond to abnormal end of the subprocedure.

For Further Information


To find out more about the topics discussed here, consult the following list:

Main Procedures
Topic See
Exception handling “Exception Handling within a Main Procedure” on
page 254
Main Procedure End “Returning from a Main Procedure” on page 153

Subprocedures
Topic See
Defining Chapter on subprocedures, in the WebSphere
Development Studio: ILE RPG Reference

46 ILE RPG Programmer’s Guide


For Further Information

NOMAIN module “Creating a NOMAIN Module” on page 77


Exception handling “Exception Handling within Subprocedures” on
page 255
Procedure Specification Chapter on procedure specifications, in the
WebSphere Development Studio: ILE RPG Reference
Procedure Interface Chapter on defining data and prototypes in the
WebSphere Development Studio: ILE RPG Reference
Subprocedure End “Returning from a Subprocedure” on page 155

Prototyped Call
Topic See
Free-form call “Using a Prototyped Call” on page 134
General Information WebSphere Development Studio: ILE RPG Reference,
Chapter 24
Passing parameters “Passing Prototyped Parameters” on page 136
Prototypes Chapter on defining data and prototypes in the
WebSphere Development Studio: ILE RPG Reference

Chapter 4. Creating an Application Using Multiple Procedures 47


For Further Information

48 ILE RPG Programmer’s Guide


Part 2. Creating and Running an ILE RPG Application
This section provides you with the information that is needed to create and run
ILE RPG programs. It describes how to:
v Enter source statements
v Create modules
v Read compiler listings
v Create programs
v Create service programs
v Run programs
v Pass parameters
v Manage the run time
v Call other programs or procedures

Use WebSphere Development Studio Client for iSeries. This is the recommended
method and documentation about creating and running an ILE RPG application
appears in that product’s online help.

Many Integrated Language Environment terms and concepts are discussed briefly
in the following pages. These terms and concepts are more fully discussed in ILE
Concepts.

© Copyright IBM Corp. 1994, 2004 49


50 ILE RPG Programmer’s Guide
Chapter 5. Using Source Files
This chapter provides the information you need to enter RPG source statements. It
also briefly describes the tools necessary to complete this step.

To enter RPG source statements into the system, use one of the following methods:
v Interactively using SEU
v Interactively using Remote Systems LPEX Editor.

Use WebSphere Development Studio Client for iSeries. This is the recommended
method and documentation about editing source appears in that product’s online
help. Your program editing tasks are simplified with the Remote Systems LPEX
editor. The editor can access source files on your workstation or your iSeries server.
When a compilation results in errors, you can jump directly from the compiler
messages to an editor containing the source. The editor opens with the cursor
positioned at the offending source statements so that you can correct them.

Initially, you may want to enter your source statements into a file called
QRPGLESRC. New members of the file QRPGLESRC automatically receive a
default type of RPGLE. Furthermore, the default source file for the ILE RPG
commands that create modules and bind them into program objects is
QRPGLESRC. IBM® supplies a source file QRPGLESRC in library QGPL. It has a
record length of 112 characters.

Note: You can use mixed case when entering source. However, the ILE RPG
compiler will convert most of the source to uppercase when it compiles it. It
will not convert literals, array data or table data.

# Your source can be in two different kinds of files:


# 1. Source physical files
# 2. IFS (Integrated File System) files

Using Source Physical Files

Creating a Library and Source Physical File


Source statements are entered into a member of a source physical file. Before you
can enter your program, you must have a library and a source physical file.

To create a library, use the CRTLIB command. To create a source physical, use the
Create Source Physical file (CRTSRCPF) command. The recommended record
length of the file is 112 characters. This record length takes into account the new
ILE RPG structure as shown in Figure 26 on page 52.

© Copyright IBM Corp. 1994, 2004 51


12 80 20

Seq#/Date Code Comments

Minimum Record Length


(92 characters)

Recommended Record Length


(112 characters)

Figure 26. ILE RPG Record Length Breakdown

Since the system default for a source physical file is 92 characters, you should
explicitly specify a minimum record length of 112. If you specify a length less than
92 characters, the program may not compile since you may be truncating source
code.

For more information about creating libraries and source physical files, refer to the
ADTS for AS/400: Source Entry Utility manual and the ADTS/400: Programming
Development Manager manual.

Using the Source Entry Utility (SEU)


You can use the Source Entry Utility (SEU) to enter your source statements. SEU
also provides prompting for the different specification templates as well as syntax
checking. To start SEU, use the STRSEU (Start Source Entry Utility) command. For
other ways to start and use SEU, refer to the ADTS for AS/400: Source Entry Utility
manual.

If you name your source file QRPGLESRC, SEU automatically sets the source type
to RPGLE when it starts the editing session for a new member. Otherwise, you
have to specify RPGLE when you create the member.

If you need prompting after you type STRSEU, press F4. The STRSEU display
appears, lists the parameters, and supplies the default values. If you supply
parameter values before you request prompting, the display appears with those
values filled in.

In the following example you enter source statements for a program which will
print employee information from a master file. This example shows you how to:
v Create a library
v Create a source physical file
v Start an SEU editing session
v Enter source statements.
1. To create a library called MYLIB, type:
CRTLIB LIB(MYLIB)

The CRTLIB command creates a library called MYLIB.


2. To create a source physical file called QRPGLESRC type:
CRTSRCPF FILE(MYLIB/QRPGLESRC) RCDLEN(112)
TEXT(’Source physical file for ILE RPG programs’)

The CRTSRCPF command creates a source physical file QRPGLESRC in library


MYLIB.
3. To start an editing session and create source member EMPRPT type:

52 ILE RPG Programmer’s Guide


Using SEU

STRSEU SRCFILE(MYLIB/QRPGLESRC)
SRCMBR(EMPRPT)
TYPE(RPGLE) OPTION(2)

Entering OPTION(2) indicates that you want to start a session for a new
member. The STRSEU command creates a new member EMPRPT in file
QRPGLESRC in library MYLIB and starts an edit session.

The SEU Edit display appears as shown in Figure 27. Note that the screen is
automatically shifted so that position 6 is (for specification type) at the left
edge.

Columns . . . : 6 76 Edit MYLIB/QRPGLESRC


SEU==> ___________________________________________________________ EMPRPT
FMT H HKeywords++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*************** Beginning of data *************************************
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
’’’’’’’
****************** End of data ****************************************
F3=Exit F4=Prompt F5=Refresh F9=Retrieve F10=Cursor
F16=Repeat find F17=Repeat change F24=More keys
Member EMPRPT added to file MYLIB/QRPGLESRC. +

Figure 27. Edit Display for a New Member

4. Type the following source in your SEU Edit display, using the following SEU
prefix commands to provide prompting:
v IPF — for file description specifications
v IPD — for definition specifications
v IPI — for input specifications
v IPC — for calculation specifications
v IPCX — for calculation specifications with extended Factor 2
v IPO — for output specifications
v IPP — for output specifications continuation
v IPPR — for procedure specifications

Chapter 5. Using Source Files 53


Using SEU

*===============================================================*
* MODULE NAME: EMPRPT
* RELATED FILES: EMPMST (PHYSICAL FILE)
* QSYSPRT (PRINTER FILE)
* DESCRIPTION: This program prints employee information
* from the file EMPMST.
*===============================================================*
FQSYSPRT O F 80 PRINTER
FEMPMST IP E K DISK
D TYPE S 8A
D EMPTYPE PR 8A
D CODE 1A
IEMPREC 01
C EVAL TYPE = EMPTYPE(ETYPE)
OPRINT H 1P 2 6
O 50 ’EMPLOYEE INFORMATION’
O H 1P
O 12 ’NAME’
O 34 ’SERIAL #’
O 45 ’DEPT’
O 56 ’TYPE’
O D 01
O ENAME 20
O ENUM 32
O EDEPT 45
O TYPE 60
* Procedure EMPTYPE returns a string representing the employee
* type indicated by the parameter CODE.
P EMPTYPE B
D EMPTYPE PI 8A
D CODE 1A
C SELECT
C WHEN CODE = ’M’
C RETURN ’Manager’
C WHEN CODE = ’R’
C RETURN ’Regular’
C OTHER
C RETURN ’Unknown’
C ENDSL
P EMPTYPE E

Figure 28. Source for EMPRPT member

5. Press F3 (Exit) to go to the Exit display. Type Y (Yes) to save EMPRPT.


The member EMPRPT is saved.

Figure 29 on page 55 shows the DDS which is referenced by the EMPRPT source.

54 ILE RPG Programmer’s Guide


Using SEU

A*****************************************************************
A* DESCRIPTION: This is the DDS for the physical file EMPMST. *
A* It contains one record format called EMPREC. *
A* This file contains one record for each employee *
A* of the company. *
A*****************************************************************
A*
A R EMPREC
A ENUM 5 0 TEXT(’EMPLOYEE NUMBER’)
A ENAME 20 TEXT(’EMPLOYEE NAME’)
A ETYPE 1 TEXT(’EMPLOYEE TYPE’)
A EDEPT 3 0 TEXT(’EMPLOYEE DEPARTMENT’)
A ENHRS 3 1 TEXT(’EMPLOYEE NORMAL WEEK HOURS’)
A K ENUM

Figure 29. DDS for EMPRPT

To create a program from this source use the CRTBNDRPG command, specifying
DFTACTGRP(*NO).

Using SQL Statements


The DB2 UDB for iSeries® database can be accessed from an ILE RPG program by
embedding SQL statements into your program source. Use the following rules to
enter your SQL statements:
v Enter your SQL statements on the Calculation specification
v Start your SQL statements using the delimiter /EXEC SQL in positions 7-15
(with the / in position 7)
v You can start entering your SQL statements on the same line as the starting
delimiter
v Use the continuation line delimiter (a + in position 7) to continue your
statements on any subsequent lines
v Use the ending delimiter /END-EXEC in positions 7-15 (with the slash in
position 7) to signal the end of your SQL statements.

Note: SQL statements cannot go past position 80 in your program.

Figure 30 shows an example of embedded SQL statements.

...+....1....+....2....+....3....+....4....+....5....+....6....+....7..
C
C (ILE RPG calculation operations)
C
C/EXEC SQL (the starting delimiter)
C+
C+ (continuation lines containing SQL statements)
C+
.
.
.
C/END-EXEC (the ending delimiter)
C
C (ILE RPG calculation operations)
C

Figure 30. SQL Statements in an ILE RPG Program

You must enter a separate command to process the SQL statements. For more
information, refer to the DB2 Universal Database for AS/400 section of the Database

Chapter 5. Using Source Files 55


Using SQL Statements

and File Systems category in the iSeries 400 Information Center at this Web site -
http://www.ibm.com/eserver/iseries/infocenter.

Refer to the ADTS for AS/400: Source Entry Utility manual for information about
how SEU handles SQL statement syntax checking.

# Using IFS Source Files


# The CRTBNDRPG and CRTRPGMOD commands include parameters to allow the
# source files to be either in the QSYS file system of in the IFS sile system. These are:
# SRCSTMF
# SRCSTMF is used instead of SRCFILE and SRCMBR to indicate a stream
# file is the main source file.
# INCDIR
# INCDIR is used to list the directories that will contain copy files.

# The stream file specified for the SRCSTMF can be an absolute path to the file
# (beginning with a slash), or it can be a path relative to the current directory.

# Include files
# The /COPY and /INCLUDE directives allow the specification of files in either the
# QSYS file system or the IFS file system. In cases where the compiler cannot tell
# which file system the directive refers to, the search will begin in the file system of
# the file containing the /COPY directive.

# When the compiler encounters a /COPY statement, the statement could refer to a
# file in the IFS or in the QSYS file system. If the name begins with a slash or is
# specified in single quotes, the name can only refer to a file in the IFS. A name in
# the IFS can be specified in double quotes as well. Where only part of the name is
# in double quotes, for example:
# /copy "SOME-LIB"/QRPGLESRC,MBR

# the name can only be a QSYS file system name.

# If the name could be either in the QSYS file system or the IFS, the file system of
# the file containing the /COPY statement will be searched first. Note that
# upper-casing occurs for the QSYS file system (except with extended names
# specified with double quotes, such as ″A/B″) but not for the IFS. (The IFS is not
# case sensitive.)
# Table 17. /Copy File Name Intepretation for QSYS and IFS
# /Copy statement QSYS interpretation IFS interpretation (see
# below for the meaning of
# ″.suffix″)
# /COPY MYMBR FILE(*LIBL/QRPGLESRC) MYMBR or MYMBR.suffix in
# MBR(MYMBR) one of the directories in the
# include path
# /COPY mymbr FILE(*LIBL/QRPGLESRC) mymbr or mymbr.suffix in
# MBR(MYMBR) one of the directories in the
# include path

56 ILE RPG Programmer’s Guide


Using IFS Source Files

# Table 17. /Copy File Name Intepretation for QSYS and IFS (continued)
# /Copy statement QSYS interpretation IFS interpretation (see
# below for the meaning of
# ″.suffix″)
# /COPY myfile,mymbr FILE(*LIBL/MYFILE) myfile,mymbr or
# MBR(MYMBR) myfile,mymbr.suffix (note
# that MYFILE,MYMBR is a
# valid name in the IFS file
# system)
# /COPY mylib/myfile,mymbr FILE(MYLIB/MYFILE) mylib/myfile,mymbr
# MBR(MYMBR) (directory mylib and file
# myfile,mymbr)
# /COPY ″A/b″,mymbr FILE(*LIBL/″A/b″) n/a (only part of name is in
# MBR(MYMBR) double quotes
# /COPY ″A/B″ FILE(*LIBL/QRPGLESRC) A/B
# MBR(″A/B″)
# /COPY a b FILE(*LIBL/QRPGLESRC) a or a.suffix (everything
# MBR(A) (everything after a after a blank is assumed
# blank is assumed to be a to be a comment)
# comment)
# /COPY ’a b’ N/A (name in single quotes) a b or a b.suffix
# /COPY N/A (name begins with /home/mydir/myfile.rpg
# /home/mydir/myfile.rpg slash)
# /COPY /QSYS.LIB/ N/A (name begins with /QSYS.LIB/L.LIB/F.FILE/
# L.LIB/F.FILE/M.MBR slash) M.MBR (which is actually a
# file in the QSYS file system,
# but is considered to be an
# IFS file by RPG)
#

# Note: When searching for files in the IFS, if the file name does not contain a dot,
# the RPG compiler will look for files with the following suffixes (in this
# order):
# 1. no suffix (abc)
# 2. .rpgleinc (abc.rpgleinc)
# 3. .rpgle (abc.rpgle)

# Search Path Within The IFS


# You have two ways to indicate where /COPY and /INCLUDE files can be found
# in the IFS:
# 1. The INCDIR parameter, which lists the directories in the order you want them
# to be searched.
# 2. The RPGINCDIR environment variable, which has a colon-separated list of
# directores in the order you want them to be searched. To set the environment
# variable, use the ADDENVVAR or CHGENVVAR command.
# For Example: ADDENVVAR ENVVAR(RPGINCDIR)
# VALUE(’/home/mydir:/project/prototypes’)ADDENVVAR

# When searching for a relative file in the IFS (one whose path does not begin with
# /), the file will be searched for in the following places, in this order
# 1. The current directory.
# 2. The path specified by the INCDIR comand parameter.

Chapter 5. Using Source Files 57


Using IFS Source Files

# 3. The directories in the RPGINCDIR environment variable.


# 4. The source directory (if the source is an IFS file).

# For example, if:


# v The current directory is /home/auser.
# v The INCDIR parameter is /driver/v5r2/inc:/driver/v5r1/inc.
# v The RPGINCDIR environment variable is /home/auser/temp.
# v The source is in directory /home/auser/src.
# The directory search path takes precedence over the default-suffix order. If a file
# with no extension is searched for in several different directories, all suffixes will be
# tried in each directory before the next directory is tried.
# Table 18. Search Order for /Copy Files
# /Copy statement Files searched for
# Assume the source file containing the In IFS:
# /COPY is /driver/src/main.rpg,
# in the IFS /home/auser/file.rpg
# /driver/v5r2/inc/file.rpg
# /COPY file.rpg /driver/v5r1/inc/file.rpg
# /home/auser/temp/file.rpg
# /home/auser/src/file.rpg
#
# In QSYS:
#
# FILE(*LIBL/QRPGLESRC) MBR(FILE.RPG)
# Assume the source file containing the In QSYS:
# /COPY is MYLIB/QRPGLESRC
# MYMBR, in the QSYS file system FILE(*LIBL/QRPGLESRC) MBR(FILE)
#
# /COPY file In IFS:
#
# /home/auser/file
# /home/auser/file.rpgleinc
# /home/auser/file.rpgle
#
# /driver/v5r2/inc/file
# /driver/v5r2/inc/file.rpgleinc
# /driver/v5r2/inc/file.rpgle
#
# /driver/v5r1/inc/file
# /driver/v5r1/inc/file.rpgleinc
# /driver/v5r1/inc/file.rpgle
#
# /home/auser/temp/file
# /home/auser/temp/file.rpgleinc
# /home/auser/temp/file.rpgle
#
# /home/auser/src/file
# /home/auser/src/file.rpgleinc
# /home/auser/src/file.rpgle
#
#

58 ILE RPG Programmer’s Guide


Chapter 6. Creating a Program with the CRTBNDRPG
Command
This chapter shows you how to create an ILE program using RPG IV source with
the Create Bound RPG Program (CRTBNDRPG) command. With this command
you can create one of two types of ILE programs:
1. OPM-compatible programs with no static binding
2. Single-module ILE programs with static binding

Whether you obtain a program of the first type or the second type depends on
whether the DFTACTGRP parameter of CRTBNDRPG is set to *YES or *NO
respectively.

Creating a program of the first type produces a program that behaves like an OPM
program in the areas of open scoping, override scoping, and RCLRSC. This high
degree of compatibility is due in part to its running in the same activation group
as OPM programs, namely, in the default activation group.

However, with this high compatibility comes the inability to have static binding.
Static binding refers to the ability to call procedures (in other modules or service
programs) and to use procedure pointers. The inability to have static binding
means that you cannot:
v Use the CALLB operation in your source
v Call a prototyped procedure
v Bind to other modules during program creation

Creating a program of the second type produces a program with ILE characteristics
such as static binding. You can specify at program-creation time the activation
group the program is to run in, and any modules for static binding. In addition,
you can call procedures from your source.

Use WebSphere Development Studio Client for iSeries. This is the recommended
method and documentation about creating an ILE RPG program appears in that
product’s online help.

Using the CRTBNDRPG Command


The Create Bound RPG (CRTBNDRPG) command creates a program object from
RPG IV source in one step. It also allows you to bind in other modules or service
programs using a binding directory.

The command starts the ILE RPG compiler and creates a temporary module object
in the library QTEMP. It then binds it into a program object of type *PGM. Once
the program object is created, the temporary module used to create the program is
deleted.

The CRTBNDRPG command is useful when you want to create a program object
from standalone source code (code that does not require modules to be bound
together), because it combines the steps of creating and binding. Furthermore, it
allows you to create an OPM-compatible program.

© Copyright IBM Corp. 1994, 2004 59


Using the CRTBNDRPG Command

Note: If you want to keep the module object in order to bind it with other
modules into a program object, you must create the module using the
CRTRPGMOD command. For more information see Chapter 7, “Creating a
Program with the CRTRPGMOD and CRTPGM Commands,” on page 75.

You can use the CRTBNDRPG command interactively, in batch, or from a


Command Language (CL) program. If you are using the command interactively
and require prompting, type CRTBNDRPG and press F4 (Prompt). If you need
help, type CRTBNDRPG and press F1 (Help).

Table 19 summarizes the parameters of the CRTBNDRPG command and shows


their default values.
Table 19. CRTBNDRPG Parameters and Their Default Values Grouped by Function
Program Identification
# PGM(*CURLIB/*CTLSPEC) Determines created program name and library
# SRCFILE(*LIBL/QRPGLESRC) If specified, identifies source file and library
# SRCMBR(*PGM) If specified, identifies file member containing source specifications
SRCSTMF(path) If specified, indicates the path to the source file in the IFS
# INCDIR(’path to directory 1:path to directory Identifies a list of directories to search for /copy and /include files
# 2’)
TEXT(*SRCMBRTXT) Provides brief description of program
Program Creation
GENLVL(10) Conditions program creation to error severity (0-20)
OPTION(*DEBUGIO) *DEBUGIO/*NODEBUGIO, determines if breakpoints are generated
for input and output specifications
OPTION(*GEN) *GEN/*NOGEN, determines if program is created
OPTION(*NOSRCSTMT) Specifies how the compiler generates statement numbers for
debugging
DBGVIEW(*STMT) Specifies type of debug view, if any, to be included in program
OPTIMIZE(*NONE) Determines level of optimization, if any
REPLACE(*YES) Determines if program should replace existing program
BNDDIR(*NONE) Specifies the binding directory to be used for symbol resolution
USRPRF(*USER) Specifies the user profile that will run program
AUT(*LIBCRTAUT) Specifies type of authority for created program
TGTRLS(*CURRENT) Specifies the release level the object is to be run on
ENBPFRCOL(*PEP) Specifies whether performance collection is enabled
DEFINE(*NONE) Specifies condition names that are defined before the compilation
begins
PRFDTA(*NOCOL) Specifies the program profiling data attribute
Compiler Listing
OUTPUT(*PRINT) Determines if there is a compiler listing
INDENT(*NONE) Determines if indentation should show in listing, and identifies
character for marking it
OPTION(*XREF *NOSECLVL *SHOWCPY Specifies the contents of compiler listing
*EXPDDS *EXT *NOSHOWSKP
*NOSRCSTMT)
Data Conversion Options

60 ILE RPG Programmer’s Guide


Using the CRTBNDRPG Command

Table 19. CRTBNDRPG Parameters and Their Default Values Grouped by Function (continued)
CVTOPT(*NONE) Specifies how various data types from externally described files are
handled
ALWNULL(*NO) Determines if the program will accept values from null-capable
fields
FIXNBR(*NONE) Determines which decimal data that is not valid is to be fixed by the
compiler
Run-Time Considerations
DFTACTGRP(*YES) Identifies whether this program always runs in the OPM default
activation group
OPTION(*DEBUGIO) *DEBUGIO/*NODEBUGIO, determines if breakpoints are generated
for input and output specifications
ACTGRP(QILE) Identifies the activation group in which the program should run
SRTSEQ(*HEX) Specifies the sort sequence table to be used
LANGID(*JOBRUN) Used with SRTSEQ to specify the language identifier for sort
sequence
TRUNCNBR(*YES) Specifies the action to take when numeric overflow occurs for
packed-decimal, zoned-decimal, and binary fields in fixed-format
operations.
# INFOSTMF(path) Used with PGMINFO, specifies the stream file in the IFS to receive
# the PCML
# PGMINFO(*NONE) *PCML indicates that PCML (Program Call Markup Language)
# should be generated for the program
LICOPT(options) Specifies Licensed Internal Code options.

See Appendix C, “The Create Commands,” on page 443 for the syntax diagram and
parameter descriptions of CRTBNDRPG.

Creating a Program for Source Debugging


In this example you create the program EMPRPT so that you can debug it using
the source debugger. The DBGVIEW parameter on either CRTBNDRPG or
CRTRPGMOD determines what type of debug data is created during compilation.
The parameter provides six options which allow you to select which view(s) you
want:
v *STMT — allows you to display variables and set breakpoints at statement
locations using a compiler listing. No source is displayed with this view.
v *SOURCE — creates a view identical to your input source.
v *COPY — creates a source view and a view containing the source of any /COPY
members.
v *LIST — creates a view similar to the compiler listing.
v *ALL — creates all of the above views.
v *NONE — no debug data is created.

The source for EMPRPT is shown in Figure 28 on page 54.


1. To create the object type:
CRTBNDRPG PGM(MYLIB/EMPRPT) DBGVIEW(*SOURCE) DFTACTGRP(*NO)

Chapter 6. Creating a Program with the CRTBNDRPG Command 61


Using the CRTBNDRPG Command

The program will be created in the library MYLIB with the same name as the
source member on which it is based, namely, EMPRPT. Note that by default, it
will run in the default named activation group, QILE. This program object can
be debugged using a source view.
2. To debug the program type:
STRDBG EMPRPT

Figure 31 shows the screen which appears after entering the above command.

Display Module Source


Program: EMPRPT Library: MYLIB Module: EMPRPT
1 *==============================================================*
2 * MODULE NAME: EMPRPT
3 * RELATED FILES: EMPMST (PHYSICAL FILE)
4 * QSYSPRT (PRINTER FILE)
5 * DESCRIPTION: This program prints employee information
6 * from the file EMPMST.
7 *==============================================================*
8 FQSYSPRT O F 80 PRINTER
9 FEMPMST IP E K DISK
10
11 D TYPE S 8A
12 D EMPTYPE PR 8A
13 D CODE 1A
14
15 IEMPREC 01
More...
Debug . . . _________________________________________________________________
_______________________________________________________________________________
F3=End program F6=Add/Clear breakpoint F10=Step F11=Display variable
F12=Resume F17=Watch variable F18=Work with watch F24=More keys

Figure 31. Display Module Source display for EMPRPT

From this screen (the Display Module Source display) you can enter debug
commands to display or change field values and set breakpoints to control
program flow while debugging.

For more information on debugging see Chapter 12, “Debugging Programs,” on


page 197.

Creating a Program with Static Binding


In this example you create a program COMPUTE using CRTBNDRPG to which
you bind a service program at program-creation time.

Assume that you want to bind the program COMPUTE to services which you have
purchased to perform advanced mathematical computations. The binding directory
to which you must bind your source is called MATH. This directory contains the
name of a service program that contains the various procedures that make up the
services.

To create the object, type:


CRTBNDRPG PGM(MYLIB/COMPUTE)
DFTACTGRP(*NO) ACTGRP(GRP1) BNDDIR(MATH)

The source will be bound to the service program specified in the binding directory
MATH at program-creation time. This means that calls to the procedures in the
service program will take less time than if they were dynamic calls.

62 ILE RPG Programmer’s Guide


Using the CRTBNDRPG Command

When the program is called, it will run in the named activation group GRP1. The
default value ACTGRP parameter on CRTBNDRPG is QILE. However, it is
recommended that you run your application as a unique group to ensure that the
associated resources are fully protected.

Note: DFTACTGRP must be set to *NO in order for you to enter a value for the
ACTGRP and BNDDIR parameters.

For more information on service programs, see Chapter 8, “Creating a Service


Program,” on page 91.

Creating an OPM-Compatible Program Object


In this example you use the CRTBNDRPG command to create an OPM-compatible
program object from the source for the payroll program, shown in Figure 32 on
page 64.
1. To create the object, type:
CRTBNDRPG PGM(MYLIB/PAYROLL)
SRCFILE(MYLIB/QRPGLESRC)
TEXT(’ILE RPG program’) DFTACTGRP(*YES)

The CRTBNDRPG command creates the program PAYROLL in MYLIB, which


will run in the default activation group. By default, a compiler listing is
produced.

Note: The setting of DFTACTGRP(*YES) is what provides the OPM


compatibility. This setting also prevents you from entering a value for
the ACTGRP and BNDDIR parameters. Furthermore, if the source
contains any bound procedure calls, an error is issued and the
compilation ends.
2. Type one of the following CL commands to see the listing that is created:
v DSPJOB and then select option 4 (Display spooled files)
v WRKJOB
v WRKOUTQ queue-name
v WRKSPLF

Chapter 6. Creating a Program with the CRTBNDRPG Command 63


Using the CRTBNDRPG Command

*------------------------------------------------------------------------*
* DESCRIPTION: This program creates a printed output of employee’s pay *
* for the week. *
*------------------------------------------------------------------------*
H DATEDIT(*DMY/)
*------------------------------------------------------------------------*
* File Definitions *
*------------------------------------------------------------------------*
FTRANSACT IP E K DISK
FEMPLOYEE IF E K DISK
FQSYSPRT O F 80 PRINTER
*------------------------------------------------------------------------*
* Variable Declarations *
*------------------------------------------------------------------------*
D Pay S 8P 2
*------------------------------------------------------------------------*
* Constant Declarations *
*------------------------------------------------------------------------*
D Heading1 C ’NUMBER NAME RATE H-
D OURS BONUS PAY ’
D Heading2 C ’______ ________________ ______ _-
D ____ _______ __________’
*------------------------------------------------------------------------*
* For each record in the transaction file (TRANSACT), if the employee *
* is found, compute the employees pay and print the details. *
*------------------------------------------------------------------------*
C TRN_NUMBER CHAIN EMP_REC 99
C IF NOT *IN99
C EVAL (H) Pay = EMP_RATE * TRN_HOURS + TRN_BONUS
C ENDIF
*------------------------------------------------------------------------*
* Report Layout *
* -- print the heading lines if 1P is on *
* -- if the record is found (indicator 99 is off) print the payroll *
* details otherwise print an exception record *
* -- print ’END OF LISTING’ when LR is on *
*------------------------------------------------------------------------*
OQSYSPRT H 1P 2 3
O 35 ’PAYROLL REGISTER’
O *DATE Y 60
O H 1P 2
O 60 Heading1
O H 1P 2
O 60 Heading2
O D N1PN99 2
O TRN_NUMBER 5
O EMP_NAME 24
O EMP_RATE L 33
O TRN_HOURS L 40
O TRN_BONUS L 49
O Pay 60 ’$ 0. ’
O D N1P 99 2
O TRN_NUMBER 5
O 35 ’** NOT ON EMPLOYEE FILE **’
O T LR
O 33 ’END OF LISTING’

Figure 32. A Sample Payroll Calculation Program

64 ILE RPG Programmer’s Guide


Using a Compiler Listing

Using a Compiler Listing


This section discusses how to obtain a listing and how to use it to help you:
v Fix compilation errors
v Fix run-time errors
v Provide documentation for maintenance purposes.

See Appendix D, “Compiler Listings,” on page 465 for more information on the
different parts of the listing and for a complete sample listing.

Obtaining a Compiler Listing


To obtain a compiler listing specify OUTPUT(*PRINT) on either the CRTBNDRPG
command or the CRTRPGMOD command. (This is their default setting.) The
specification OUTPUT(*NONE) will suppress a listing.

Specifying OUTPUT(*PRINT) results in a compiler listing which consists minimally


of the following sections:
v Prologue (command option summary)
v Source Listing, which includes:
– In-Line diagnostic messages
– Match-field table (if using the RPG cycle with match fields)
v Additional diagnostic messages
v Field Positions in Output Buffer
v /COPY Member Table
v Compile Time Data which includes:
– Alternate Collating Sequence records and table or NLSS information and table
– File translation records
– Array records
– Table records
v Message summary
v Final summary
v Code generation report (appears only if there are errors)
v Binding report (applies only to CRTBNDRPG; appears only if there are errors)

The following additional information is included in a compiler listing if the


appropriate value is specified on the OPTION parameter of either create command:
*EXPDDS
Specifications of externally-described files (appear in source section of
listing)
*SHOWCPY
Source records of /COPY members (appear in source section of listing)
*SHOWSKP
Source lines excluded by conditional compilation directives (appear in
source section of listing)
*EXPDDS
Key field information (separate section)
*XREF List of Cross references (separate section)
*EXT List of External references (separate section)

Chapter 6. Creating a Program with the CRTBNDRPG Command 65


Using a Compiler Listing

*SECLVL
Second-level message text (appear in message summary section)

Note: Except for *SECLVL and *SHOWSKP, all of the above values reflect the
default settings on the OPTION parameter for both create commands. You
do not need to change the OPTION parameter unless you do not want
certain listing sections or unless you want second level text to be included.

The information contained in a compiler listing is also dependent on whether


*SRCSTMT or *NOSRCSTMT is specified for the OPTION parameter. For details on
how this information changes, see “″*NOSRCSTMT Source Heading″” on page 472
and “″*SRCSTMT Source Heading″” on page 472.

If any compile option keywords are specified on the control specification, the
compiler options in effect will appear in the source section of the listing.

Customizing a Compiler Listing


You can customize a compiler listing in any or all of the following ways:
v Customize the page heading
v Customize the spacing
v Indent structured operations

Customizing a Page Heading


The page heading information includes the product information line and the title
supplied by a /TITLE directive. The product information line includes the ILE
RPG compiler and library copyright notice, the member, and library of the source
program, the date and time when the module was created, and the page number
of the listing.

You can specify heading information on the compiler listing through the use of the
/TITLE compiler directive. This directive allows you to specify text which will
appear at the top of each page of the compiler listing. This information will
precede the usual page heading information. If the directive is the first record in
the source member, then this information will also appear in the prologue section.

You can also change the date separator, date format, and time separator used in
the page heading and other information boxes throughout the listing. Normally,
the compiler determines these by looking at the job attributes. To change any of
these, use the Change Job (CHGJOB) command. After entering this command you
can:
v Select one of the following date separators: *SYSVAL, *BLANK, slash (/),
hyphen (-) period (.) or comma (,)
v Select one of the following date formats: *SYSVAL, *YMD, *MDY, *DMY, or *JUL
v Select one of the following time separators: *SYSVAL, *BLANK, colon (:), comma
(,) or period (.)

Anywhere a date or time field appears in the listing, these values are used.

Customizing the Spacing


Each section of a listing usually starts on a new page; Each page of the listing
starts with product information, unless the source member contains a /TITLE
directive. If it does, the product information appears on the second line and the
title appears on the first line.

66 ILE RPG Programmer’s Guide


Using a Compiler Listing

You can control the spacing and pagination of the compiler listing through the use
of the /EJECT and /SPACE compiler directives. The /EJECT directive forces a
page break. The /SPACE directive controls line spacing within the listing. For more
information on these directives refer to the WebSphere Development Studio: ILE RPG
Reference.

Indenting Structured Operations


Note: Calculations can only be indented if they are written with traditional syntax.
The RPG compiler does not change the indentation of your free-form
calculations (between /FREE and /END-FREE) in the listing. You may
indent the free-form claculations directly in your source file.

If your source specifications contain structured operations (such as DO-END or


IF-ELSE-END), you may want to have these indented in the source listing. The
INDENT parameter lets you specify whether to show indentation, and specify the
character to mark the indentation. If you do not want indentation, specify
INDENT(*NONE); this is the default. If you do want indentation, then specify up
to two characters to mark the indentation.

For example, to specify that you want structured operations to be indented and
marked with a vertical bar (|) followed by a space, you specify INDENT('| ').

If you request indentation, then some of the information which normally appears
in the source listing is removed, so as to allow for the indentation. The following
columns will not appear in the listing:
v Do Num
v Last Update
v PAGE/LINE

If you specify indentation and you also specify a listing debug view, the
indentation will not appear in the debug view.

Figure 33 on page 68 shows part of source listing which was produced with
indentation. The indentation mark is '| '.

Chapter 6. Creating a Program with the CRTBNDRPG Command 67


Using a Compiler Listing

Line <--------------------- Source Specifications ----------------------------------------------><---- Comments ----> Src Seq


Number ....1....+....2....+<-------- 26 - 35 -------->....4....+....5....+....6....+....7....+....8....+....9....+...10 Id Number
33 C******************************************************************** 002000
34 C* MAINLINE * 002100
35 C******************************************************************** 002200
36 C WRITE FOOT1 002300
37 C WRITE HEAD 002400
38 C EXFMT PROMPT 002500
39 C* 002600
40 C DOW NOT *IN03 002700
41 C CSTKEY | SETLL CMLREC2 ----20 002800
42 C | IF *IN20 002900
43 C | | MOVE ’1’ *IN61 003000
44 C | ELSE 003100
45 C | | EXSR SFLPRC 003200
46 C | END 003300
47 C | IF NOT *IN03 003400
48 C | | IF *IN04 003500
49 C | | | IF *IN61 003600
50 C | | | | WRITE FOOT1 003700
51 C | | | | WRITE HEAD 003800
52 C | | | ENDIF 003900
53 C | | | EXFMT PROMPT 004000
54 C | | ENDIF 004100
55 C | ENDIF 004200
56 C ENDDO 004300
57 C* 004500
58 C SETON LR---- 004600

Figure 33. Sample Source Part of the Listing with Indentation

Correcting Compilation Errors


The main sections of a compiler listing that are useful for fixing compilation errors
are:
v The source section
v The Additional Messages section
v The /COPY table section
v The various summary sections.

In-line diagnostic messages, which are found in the source section, point to errors
which the compiler can flag immediately. Other errors are flagged after additional
information is received during compilation. The messages which flag these errors
are in the source section and Additional Messages section.

To aid you in correcting any compilation errors, you may want to include the
second-level message text in the listing — especially if you are new to RPG. To do
this, specify OPTION(*SECLVL) on either create command. This will add
second-level text to the messages listed in the message summary.

Finally, keep in mind that a compiler listing is a record of your program. Therefore,
if you encounter any errors when testing your program, you can use the listing to
check that the source is coded the way you intended it to be. Parts of the listing,
besides the source statements, which you may want to check include:
v Match field table
If you are using the RPG cycle with match fields, then you can use this to check
that all your match fields are the correct lengths, and in the correct positions.
v Output-buffer positions
Lists the start and end positions along with the literal text or field names. Use
this to check for errors in your output specifications.
v Compile-time data

68 ILE RPG Programmer’s Guide


Using a Compiler Listing

ALTSEQ and FTRANS records and tables are listed. NLSS information and
tables are listed. Tables and arrays are explicitly identified. Use this to confirm
that you have specified the compile-time data in the correct order, and that you
have specified the correct values for the SRTSEQ and LANGID parameters to the
compiler.

Using In-Line Diagnostic Messages


There are two types of in-line diagnostic messages: finger and non-finger. Finger
messages point out exactly where the error occurred. Figure 34 shows an example
of finger in-line diagnostic messages.

Line <---------------------- Source Specifications ----------------------------><---- Comments ----> Do Page Change Src Seq
Number ....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8....+....9....+...10 Num Line Date Id Number
63 C SETOFF _12___ 003100
======> aabb
======> cccccc
*RNF5051 20 a 003100 Resulting-Indicator entry is not valid; defaults to blanks.
*RNF5051 20 b 003100 Resulting-Indicator entry is not valid; defaults to blanks.
*RNF5053 30 c 003100 Resulting-Indicators entry is blank for specified

Figure 34. Sample Finger In-Line Diagnostic Messages

In this example, an indicator has been incorrectly placed in positions 72 - 73


instead of 71 - 72 or 73 - 74. The three fingers ’aa’, ’bb’, and ’cccccc’ identify the
parts of the line where there are errors. The actual columns are highlighted with
variables which are further explained by the messages. In this case, message
RNF5051 indicates that the fields marked by ’aa’ and ’bb’ do not contain a valid
indicator. Since there is no valid indicator the compiler assumes that the fields are
blank. However, since the SETOFF operation requires an indicator, another error
arises, as pointed out by the field ’cccccc’ and message RNF5053.

Errors are listed in the order in which they are found. As a general rule, you
should focus on correcting the first few severity 30 and 40 errors, since these are
often the cause of other errors.

Non-finger in-line diagnostic messages also indicate errors. However, they are not
issued immediately following the line in error. Figure 35 shows an example of the
non-finger in-line diagnostic messages.

Line <---------------------- Source Specifications ----------------------------><---- Comments ----> Do Page Change Src Seq
Number ....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8....+....9....+...10 Num Line Date Id Number
1 D FLD1 S +5 LIKE(FLD2) 000100
2 D FLD2 S D 000200
*RNF3479 20 1 000100 A length adjustment is not allowed for a field of the
specified data type.

Figure 35. Sample Non-Finger In-Line Diagnostic Messages

In this example, FLD1 is defined like FLD2 with a length 5 bytes greater. Later,
FLD2 is defined as a date, which makes the length adjustment in the definition of
FLD1 invalid. Message RNF3479 is issued pointing at listing line 1. Note that the
SEU sequence number (000100) is also given, to aid you in finding the source line
in error more quickly. (The SEU sequence number can also be found at listing line
1).

Using Additional-Diagnostic Messages


The Additional Diagnostic Messages section identifies errors which arise when one
or more lines of code are viewed collectively. These messages are not placed within
the code where the problem is; in general, the compiler does not know at the time
of checking that portion of the source that a problem exists. However, when

Chapter 6. Creating a Program with the CRTBNDRPG Command 69


Using a Compiler Listing

possible, the message line includes either the listing Line Number and SEU
sequence number, or the Statement Number of a source line which is related to the
message.

Browsing a Compiler Listing Using SEU


The SEU Split/Browse session (F15) allows you to browse a compiler listing in the
output queue. You can review the results of a previous compilation while making
the required changes to your source code.

While browsing the compiler listing, you can scan for errors and correct those
source statements that have errors. To scan for errors, type F *ERR on the SEU
command line of the browse session. The line with the first (or next) error is
highlighted, and the first-level text of the same message appears at the bottom of
the screen. You can see the second-level text by placing your cursor on the message
at the bottom and then pressing F1 (Help).

When possible, the error messages in the listing identify the SEU sequence number
of the line in error. The sequence number is found just before the message text.

For complete information on browsing a compiler listing, see ADTS for AS/400:
Source Entry Utility.

Correcting Run-time Errors


The source section of the listing is also useful for correcting run-time errors. Many
run-time error messages identify a statement number where the error in question
occurred.

If OPTION(*NOSRCSTMT) is specified, the Line Number on the left side of the


compiler listing corresponds to the statement number in the run-time error
message. The source ID number and the SEU sequence number on the right side of
the compiler listing identify the source member and record. You can use the two
together, especially if you are editing the source using SEU, to determine which
line needs to be examined.

If OPTION(*SRCSTMT) is specified, the Statement Number on the right side of the


compiler listing corresponds to the statement number in the run-time error
message. If the statement is from the main source member, this is the same as the
statement on the left side of the compiler listing, and is also the same as the SEU
sequence number.

If you have a /COPY member, you can find the source ID number of the actual file
in the /COPY Member table at the end of the listing. For an example of a /COPY
Member table, see “/COPY Member Table” on page 474.

Coordinating Listing Options with Debug View Options


Correcting run-time errors often involves debugging a program. The following
considerations may help you when you go to debug your program:
v If you use the source debugger to debug your program you have a choice of
debug views: *STMT, *SOURCE, *LIST, *COPY, *ALL.
v If you plan to use a compiler listing as an aid while debugging, then you can
obtain one by specifying OUTPUT(*PRINT). A listing is important if you intend
to debug using a statement (*STMT) view since the statement numbers for
setting breakpoints are those identified in the source listing. The statement
numbers are listed in the column labeled as the Line Number when

70 ILE RPG Programmer’s Guide


Using a Compiler Listing

OPTION(*NOSRCSTMT) is specified, and in the column labeled as the Statement


Number when OPTION(*SRCSTMT) is specified.
v If you know that you will have considerable debugging to do, you may want to
compile the source with DBGVIEW(*ALL), OUTPUT(*PRINT) and
OPTION(*SHOWCPY). This will allow you to use either a source or listing view,
and it will include /COPY members.
v If you specify DBGVIEW(*LIST), the information available to you while
debugging depends on what you specified for the OPTION parameter. The view
will include /COPY members and externally described files only if you specify
OPTION(*SHOWCPY *EXPDDS) — these are the defaults.

Using a Compiler Listing for Maintenance


A compiler listing of an error-free program can be used as documentation when:
v Teaching the program to a new programmer.
v Updating the program at a later date.

In either case it is advisable to have a full listing, namely, one produced with
OUTPUT(*PRINT) and with OPTION(*XREF *SHOWCPY *EXPDDS *EXT
*SHOWSKP).

Note: Except for *SHOWSKP, this is the default setting for each of these
parameters on both create commands.

Of particular value for program maintenance is the Prologue section of the listing.
This section tells you:
v Who compiled the module/program
v What source was used to produce the module/program
v What options were used when compiling the module/program

You may need to know about the command options (for example, the debug view
selected, or the binding directory used) when you make later changes to the
program.

The following specifications for the OPTION parameter provide additional


information as indicated:
v *SHOWCPY and *EXPDDS provide a complete description of the program,
including all specifications from /COPY members, and generated specifications
from externally described files.
v *SHOWSKP allows you to see the statements that are ignored by the compiler as
a result of /IF, /ELSEIF, /ELSE, OR /EOF directives.
v *XREF allows you to check the use of files, fields, and indicators within the
module/program.
v *EXT allows you to see which procedures and fields are imported or exported
by the module/program. It also identifies the actual files which were used for
generating the descriptions for externally described files and data structures.

Accessing the RETURNCODE Data Area


Both the CRTBNDRPG and CRTRPGMOD (see “Using the CRTRPGMOD
Command” on page 76) commands create and update a data area with the status
of the last compilation. This data area is named RETURNCODE, is 400 characters
long, and is placed into library QTEMP.

Chapter 6. Creating a Program with the CRTBNDRPG Command 71


Accessing the RETURNCODE Data Area

To access the RETURNCODE data area, specify RETURNCODE in factor 2 of a


*DTAARA DEFINE statement.

The data area RETURNCODE has the following format:


Byte Content and Meaning
1 For CRTRPGMOD, character '1' means that a module was created
in the specified library. For CRTBNDRPG, character '1' means a
module with the same name as the program name was created in
QTEMP.
2 Character '1' means that the compilation failed because of compiler
errors.
3 Character '1' means that the compilation failed because of source
errors.
4 Not set. Always '0'.
5 Character '1' means the translator was not called because either
OPTION(*NOGEN) was specified on the CRTRPGMOD or
CRTBNDRPG command; or the compilation failed before the
translator was called.
6-10 Number of source statements
11-12 Severity level from command
13-14 Highest severity of diagnostic messages
15-20 Number of errors that are found in the module (CRTRPGMOD) or
program (CRTBNDRPG).
21-26 Compile date
27-32 Compile time
33-100 Not set. Always blank
101-110 Module (CRTRPGMOD) name or program (CRTBNDRPG) name.
111-120 Module (CRTRPGMOD) library name or program (CRTBNDRPG)
library name.
121-130 Source file name
131-140 Source file library name
141-150 Source file member name
151-160 Compiler listing file name
161-170 Compiler listing library name
171-180 Compiler listing member name
181-329 Not set. Always blank
330-334 Total elapsed compile time to the nearest 10th of a second (or -1 if
an error occurs while this time is being calculated)
335 Not set. Always blank
336-340 Elapsed compile time to the nearest 10th of a second (or -1 if an
error occurs while this time is being calculated)
341-345 Elapsed translator time to the nearest 10th of a second (or -1 if an
error occurs while this time is being calculated)

72 ILE RPG Programmer’s Guide


Accessing the RETURNCODE Data Area

346-379 Not set. Always blank


380-384 Total compile CPU time to the nearest 10th of a second
385 Not set. Always blank
386-390 CPU time that is used by compiler to the nearest 10th of a second
391-395 CPU time that is used by the translator to the nearest 10th of a
second
396-400 Not set. Always blank

Chapter 6. Creating a Program with the CRTBNDRPG Command 73


Accessing the RETURNCODE Data Area

74 ILE RPG Programmer’s Guide


Chapter 7. Creating a Program with the CRTRPGMOD and
CRTPGM Commands
The two-step process of program creation consists of compiling source into
modules using CRTRPGMOD and then binding one or more module objects into a
program using CRTPGM. With this process you can create permanent modules.
This in turn allows you to modularize an application without recompiling the
whole application. It also allows you to reuse the same module in different
applications.

This chapter shows how to:


v Create a module object from RPG IV source
v Bind modules into a program using CRTPGM
v Read a binder listing
v Change a module or program

Use WebSphere Development Studio Client for iSeries. This is the recommended
method and documentation about creating an ILE RPG program appears in that
product’s online help.

Creating a Module Object


A module is a nonrunnable object (type *MODULE) that is the output of an ILE
compiler. It is the basic building block of an ILE program.

An ILE RPG module consists of one or more procedures, and the file control blocks
and static storage used by all the procedures in the module. The procedures that
can make up an ILE RPG module are:
v an optional main procedure which consists of the set of H, F, D, I, C, and O
specifications that begin the source. The main procedure has its own LR
semantics and logic cycle; neither of which is affected by those of other ILE RPG
modules in the program.
v zero or more subprocedures, which are coded on P, D, and C specifications.
Subprocedures do not use the RPG cycle. A subprocedure may have local
storage that is available for use only by the subprocedure itself.

The main procedure (if coded) can always be called by other modules in the
program. Subprocedures may be local to the module or exported. If they are local,
they can only be called by other procedures in the module; if they are exported
from the module, they can be called by any procedure in the program.

Module creation consists of compiling a source member, and, if that is successful,


creating a *MODULE object. The *MODULE object includes a list of imports and
exports referenced within the module. It also includes debug data if you request
this at compile time.

A module cannot be run by itself. You must bind one or more modules together to
create a program object (type *PGM) which can then be run. You can also bind one
or more modules together to create a service program object (type *SRVPGM). You
then access the procedures within the bound modules through static procedure
calls.

© Copyright IBM Corp. 1994, 2004 75


Creating a Module Object

This ability to combine modules allows you to:


v Reuse pieces of code. This generally results in smaller programs. Smaller
programs give you better performance and easier debugging capabilities.
v Maintain shared code with little chance of introducing errors to other parts of
the overall program.
v Manage large programs more effectively. Modules allow you to divide your old
program into parts that can be managed separately. If the program needs to be
enhanced, you only need to recompile those modules which have been changed.
v Create mixed-language programs where you bind together modules written in
the best language for the task required.

For more information about the concept of modules, refer to ILE Concepts.

Using the CRTRPGMOD Command


You create a module using the Create RPG Module (CRTRPGMOD) command. You
can use the command interactively, as part of a batch input stream, or from a
Command Language (CL) program.

If you are using the command interactively and need prompting, type
CRTRPGMOD and press F4 (Prompt). If you need help, type CRTRPGMOD and
press F1 (Help).

Table 20 lists the parameters of the CRTRPGMOD command and their


system-supplied defaults. The syntax diagram of the command and a description
of the parameters are found in Appendix C, “The Create Commands,” on page 443.
Table 20. CRTRPGMOD Parameters and Their Default Values Grouped by Function
Module Identification
# MODULE(*CURLIB/*CTLSPEC) Determines created module name and library
# SRCFILE(*LIBL/QRPGLESRC) If specified, identifies source file and library
# SRCMBR(*MODULE) If specified, identifies file member containing source specifications
SRCSTMF(path) If specified, indicates the path to the source file in the IFS
# INCDIR(’path to directory 1:path to directory Identifies a list of modules to search for /copy and /include files
# 2’)
TEXT(*SRCMBRTXT) Provides brief description of module
Module Creation
GENLVL(10) Conditions module creation to error severity (0-20)
OPTION(*DEBUGIO) *DEBUGIO/*NODEBUGIO, determines if breakpoints are generated
for input and output specifications
OPTION(*GEN) *GEN/*NOGEN, determines if module is created
OPTION(*NOSRCSTMT) Specifies how the compiler generates statement numbers for
debugging
DBGVIEW(*STMT) Specifies type of debug view, if any, to be included in module
OPTIMIZE(*NONE) Determines level of optimization, if any
REPLACE(*YES) Determines if module should replace existing module
AUT(*LIBCRTAUT) Specifies type of authority for created module
TGTRLS(*CURRENT) Specifies the release level the object is to be run on
BNDDIR(*NONE) Specifies the binding directory to be used for symbol resolution

76 ILE RPG Programmer’s Guide


Creating a Module Object

Table 20. CRTRPGMOD Parameters and Their Default Values Grouped by Function (continued)
ENBPFRCOL(*PEP) Specifies whether performance collection is enabled
DEFINE(*NONE) Specifies condition names that are defined before the compilation
begins
PRFDTA(*NOCOL) Specifies the program profiling data attribute
Compiler Listing
OUTPUT(*PRINT) Determines if there is a compiler listing
INDENT(*NONE) Determines if indentation should show in listing, and identify
character for marking it
OPTION(*XREF *NOSECLVL *SHOWCPY Specifies the contents of compiler listing
*EXPDDS *EXT *NOSHOWSKP
*NOSRCSTMT)
Data Conversion Options
CVTOPT(*NONE) Specifies how various data types from externally described files are
handled
ALWNULL(*NO) Determines if the module will accept values from null-capable fields
FIXNBR(*NONE) Determines which decimal data that is not valid is to be fixed by the
compiler
Run-Time Considerations
SRTSEQ(*HEX) Specifies the sort sequence table to be used
OPTION(*DEBUGIO) *DEBUGIO/*NODEBUGIO, determines if breakpoints are generated
for input and output specifications
LANGID(*JOBRUN) Used with SRTSEQ to specify the language identifier for sort
sequence
# INFOSTMF(path) Used with PGMINFO, specifies the stream file in the IFS to receive
# the PCML
# PGMINFO(*NONE) *PCML indicates that PCML (Program Call Markup Language)
# should be generated for the module
TRUNCNBR(*YES) Specifies action to take when numeric overflow occurs for
packed-decimal, zoned-decimal, and binary fields in fixed format
operations.
LICOPT(options) Specifies Licensed Internal Code options.

When requested, the CRTRPGMOD command creates a compiler listing which is


for the most part identical to the listing that is produced by the CRTBNDRPG
command. (The listing created by CRTRPGMOD will never have a binding
section.)

For information on using the compiler listing, see “Using a Compiler Listing” on
page 65. A sample compiler listing is provided in Appendix D, “Compiler
Listings,” on page 465.

Creating a NOMAIN Module


In this example you create an NOMAIN module object TRANSSVC using the
CRTRPGMOD command and its default settings. TRANSSVC contains prototyped
procedures that perform transaction services for procedures in other modules. The
source for TRANSSVC is shown in Figure 36 on page 79. The prototypes for the
procedures in TRANSSVC are stored in a /COPY member, as shown in Figure 37
on page 80.
1. To create a module object, type:

Chapter 7. Creating a Program with the CRTRPGMOD and CRTPGM Commands 77


Creating a Module Object

CRTRPGMOD MODULE(MYLIB/TRANSSVC) SRCFILE(MYLIB/QRPGLESRC)

The module will be created in the library MYLIB with the name specified in the
command, TRANSSVC. The source for the module is the source member
TRANSSVC in file QRPGLESRC in the library MYLIB.

You bind a module containing NOMAIN to another module using one of the
following commands:
a. CRTPGM command
b. CRTSRVPGM command
c. CRTBNDRPG command where the NOMAIN module is included in a
binding directory.
2. Once it is bound, this module object can be debugged using a statement view.
A compiler listing for the module is also produced.
3. Type one of the following CL commands to see the compiler listing.
v DSPJOB and then select option 4 (Display spooled files)
v WRKJOB
v WRKOUTQ queue-name
v WRKSPLF

78 ILE RPG Programmer’s Guide


Creating a Module Object

*=================================================================*
* MODULE NAME: TRANSSVC (Transaction Services)
* RELATED FILES: N/A
* RELATED SOURCE: TRANSRPT
* EXPORTED PROCEDURES: Trans_Inc -- calculates the income
* for the transaction using the data in the fields in the
* parameter list. It returns to the caller after all
* the calculations are done.
*
* Prod_Name -- retrieves the product name based on the
* input parameter with the product number.
*=================================================================*
* This module contains only subprocedures; it is a NOMAIN module.
H NOMAIN
*------------------------------------------------------------------
* Pull in the prototypes from the /COPY member
*------------------------------------------------------------------
/COPY TRANSP
*------------------------------------------------------------------
* Subprocedure Trans_Inc
*------------------------------------------------------------------
P Trans_Inc B EXPORT
D Trans_Inc PI 11P 2
D ProdNum 10P 0 VALUE
D Quantity 5P 0 VALUE
D Discount 2P 2 VALUE
D Factor S 5P 0
*
C SELECT
C WHEN ProdNum = 1
C EVAL Factor = 1500
C WHEN ProdNum = 2
C EVAL Factor = 3500
C WHEN ProdNum = 5
C EVAL Factor = 20000
C WHEN ProdNum = 8
C EVAL Factor = 32000
C WHEN ProdNum = 12
C EVAL Factor = 64000
C OTHER
C EVAL Factor = 0
C ENDSL
C RETURN Factor * Quantity * (1 - Discount)
P Trans_Inc E

Figure 36. Source for TRANSSVC member (Part 1 of 2)

Chapter 7. Creating a Program with the CRTRPGMOD and CRTPGM Commands 79


Creating a Module Object

*------------------------------------------------------------------
* Subprocedure Prod_Name
*------------------------------------------------------------------
P Prod_Name B EXPORT
D Prod_Name PI 40A
D ProdNum 10P 0 VALUE
*
C SELECT
C WHEN ProdNum = 1
C RETURN ’Large’
C WHEN ProdNum = 2
C RETURN ’Super’
C WHEN ProdNum = 5
C RETURN ’Super Large’
C WHEN ProdNum = 8
C RETURN ’Super Jumbo’
C WHEN ProdNum = 12
C RETURN ’Incredibly Large Super Jumbo’
C OTHER
C RETURN ’***Unknown***’
C ENDSL
P Prod_Name E

Figure 36. Source for TRANSSVC member (Part 2 of 2)

* Prototype for Trans_Inc


D Trans_Inc PR 11P 2
D Prod 10P 0 VALUE
D Quantity 5P 0 VALUE
D Discount 2P 2 VALUE

* Prototype for Prod_Name


D Prod_Name PR 40A
D Prod 10P 0 VALUE

Figure 37. Source for TRANSP /COPY member

Creating a Module for Source Debuggi