Before using this information and the product it supports, be sure to read the general information under “Notices” on page xi.
Third Edition (May 1999)
This edition applies to Version 4, Release 4, Modification 0, of IBM Application System/400 Integrated Language Environment RPG
for AS/400 (Program 5769-RG1) 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-01.
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
2G/KB7/1150/TOR
1150 Eglinton Avenue East
North York, Ontario, Canada M3C 1H7
You can also send your comments by facsimile (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, 1999. All rights reserved.
Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication or disclosure is subject to
restrictions set forth in GSA ADP Schedule Contract with IBM Corp.
This information was developed for products and services offered in the U.S.A. IBM
may not offer the products, services, or features discussed in this document in
other countries. Consult your local IBM representative for information on the products and services currently available in your area. Any reference to an IBM
product, program, or service is not intended to state or imply that only that IBM
product, program, or service may be used. Any functionally equivalent product,
program, or service that does not infringe any IBM intellectual property right may be
used instead. However, it is the user's responsibility to evaluate and verify the operation of any non-IBM product, program, or service.
IBM may have patents or pending patent applications covering subject matter
described in this document. The furnishing of this document does not give you any
license to these patents. You can send license inquiries, in writing, to:
IBM Director of Licensing
IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.
The following paragraph does not apply to the United Kingdom or any other
country where such provisions are inconsistent with local law: INTERNA-
TIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS PUBLICATION
“AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR
PURPOSE. Some states do not allow disclaimer of express or implied warranties in
certain transactions, therefore, this statement may not apply to you.
This information could include technical inaccuracies or typographical errors.
Changes are periodically made to the information herein; these changes will be
incorporated in new editions of the publication. IBM may make improvements
and/or changes in the product(s) and/or the program(s) described in this publication
at any time without notice.
Any references in this information to non-IBM Web sites are provided for convenience only and do not in any manner serve as an endorsement of those Web sites.
The materials at those Web sites are not part of the materials for this IBM product
and use of those Web sites is at your own risk.
Licensees of this program who wish to have information about it for the purpose of
enabling: (i) the exchange of information between independently created programs
and other programs (including this one) and (ii) the mutual use of the information
which has been exchanged, should contact:
IBM Canada Ltd.
Department 071
1150 Eglinton Avenue East
North York, Ontario M3C 1H7
Canada
Copyright IBM Corp. 1994, 1999 xi
Such information may be available, subject to appropriate terms and conditions,
including in some cases, payment of a fee.
The licensed program described in this information and all licensed material available for it are provided by IBM under terms of the IBM Customer Agreement, IBM
International Program License Agreement, or any equivalent agreement between
us.
This information contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the
names of individuals, companies, brands, and products. All of these names are
fictitious and any similarity to the names and addresses used by an actual business
enterprise is entirely coincidental.
Programming Interface Information
This publication is intended to help you create programs using RPG IV source. This
publication documents General-Use Programming Interface and Associated Guidance Information provided by the ILE RPG for AS/400 compiler.
General-Use programming interfaces allow the customer to write programs that
obtain the services of the ILE RPG for AS/400 compiler.
Trademarks and Service Marks
The following terms are trademarks of the International Business Machines Corporation in the United States, or other countries, or both:
Domino is a trademark of the Lotus Development Corporation in the United States,
or other countries, or both.
Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and/or other countries.
VisualAge
Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States and/or other countries.
UNIX is a registered trademark in the United States and/or other countries licensed
exclusively through X/Open Company Limited.
Other company, product, and service names may be the trademarks or service
marks of others.
xiiILE RPG for AS/400 Programmer's Guide
Registered trademarks and unregistered trademarks are denoted by and
respectively.
Notices xiii
xivILE RPG for AS/400 Programmer's Guide
About This Guide
This guide provides information that shows how to use the ILE RPG for AS/400
compiler (ILE RPG) in the Integrated Language Environment. ILE RPG is an
implementation of the RPG IV language on the AS/400 system 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:
¹ Enter RPG IV source statements
¹ Create modules
¹ Bind modules
¹ Run an ILE program
¹ Call other objects
¹ Debug an ILE program
¹ Handle exceptions
¹ Define and process files
¹ Access devices
¹ Convert programs from an RPG III format to RPG IV format
¹ 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
AS/400 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
SC09-2508-02 .
Before using this guide, you should:
¹ Know how to use applicable AS/400 menus and displays, or Control Language
(CL) commands.
ILE RPG for AS/400 Reference
,
¹ Have the appropriate authority to the CL commands and objects described
here.
¹ Have a firm understanding of ILE as described in detail in the
SC41-5606-03.
Copyright IBM Corp. 1994, 1999 xv
ILE Concepts
,
Prerequisite and Related Information
Use the AS/400 Information Center as your starting point for looking up AS/400
technical information. You can access the Information Center from the AS/400e
Information Center CD-ROM (English version: SK3T-2027-01) or from one of these
Web sites:
The AS/400 Information Center contains important topics such as logical partitioning, clustering, Java, TCP/IP, Web serving, and secured networks. It also contains Internet links to Web sites such as the AS/400 Online Library and the AS/400
Technical Studio. Included in the Information Center is a link that describes at a
high level the differences in information between the Information Center and the
Online Library.
For a list of related publications, see the “Bibliography” on page 439.
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 AS/400
documentation.
¹ If you prefer to send comments by mail, use the the following address:
IBM Canada Ltd. Laboratory
Information Development
2G/KB7/1150/TOR
1150 Eglinton Avenue East
North York, Ontario, Canada M3C 1H7
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 rep-
resentative for postage-paid mailing.
¹ If you prefer to send comments by FAX, use the following number:
– 1-416-448-6161
¹ If you prefer to send comments electronically, use one of these e-mail
addresses:
– Comments on books:
torrcf@ca.ibm.com
IBMLink: toribm(torrcf)
– Comments on the AS/400 Information Center:
RCHINFOC@us.ibm.com
Be sure to include the following:
¹ The name of the book.
¹ The publication number of the book.
¹ The page number or topic to which your comment applies.
xviILE RPG for AS/400 Programmer's Guide
What's New This Release?
|
|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:
|¹ 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.
|¹ 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 proce|dures 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.
|¹ 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.
|– Support for conversions between UCS-2 fields or graphic fields with dif|ferent 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:
|¹ New parameters for the OPTION control specification keyword and on the
|create commands:
About This Guidexvii
|– *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 spec|ifications 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 calcu|lation, rather than stepping through the input specifications.
|¹ New special words for the INZ definition specification keyword:
|– INZ(*EXTDFT) allows you to use the default values in the DDS for initial-
|izing externally described data structure subfields.
|– Character variables initialized by INZ(*USER) are initialized to the name of
|the current user profile.
|¹ The new %XFOOT built-in function sums all elements of a specified array
|expression.
|¹ 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.
|¹ The new FOR operation code performs an iterative loop and allows free-form
|expressions for the initial, increment, and limit values.
|¹ The new LEAVESR operation code can be used to exit from any point within a
|subroutine.
|¹ The new *NEXT parameter on the OVERLAY(name:*NEXT) keyword indicates
|that a subfield overlays another subfield at the next available position.
|¹ The ability to use hexadecimal literals with integer and unsigned integer fields
|in initialization and free-form operations, such as EVAL, IF, etc.
|¹ New control specification keyword OPENOPT{(*NOINZOFL | *INZOFL)} to indi|cate whether the overflow indicators should be reset to *OFF when a file is
|opened.
|¹ 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.
|OPTION(*{NO}SRCSTMT)|*SRCSTMT allows you to request
|cation keywords
|that the compiler use SEU sequence
|numbers and source IDs when gen-
|erating 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 break-
|points are generated for input and
|output specifications.
|Definition spec-
|INZ(*EXTDFT)|All externally described data struc-
|ification
|ture subfields can now be intialized
|keywords
|to the 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(*RIGHTADJ)|OPTIONS(*RIGHTADJ) specified on
|a value or constant 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 spec-
|3 and 20 digits allowed for
|Added to the list of allowed values
|ification posi-
|I and U data types
|for internal data types to support
|tions 33-39 (To
|1-byte and 8-byte integer and
|Position/Length)
|unsigned data.
|Command
|OPTION|*NOSRCSTMT, *SRCSTMT,
|parameter
|*NODEBUGIO, and *DEBUGIO have
|been added to the OPTION param-
|eter on the CRTBNDRPG and
|CRTRPGMOD commands.
About This Guidexix
|
|Control specifi-
|CCSID(*GRAPH:
|Sets the default graphic CCSID for
|cation keywords
|*IGNORE | *SRC |
|the module. This setting is used for
|number)
|literals, compile-time data and
Table 2 (Page 1 of 2). New Language Elements Since V4R2
Language UnitElementDescription
|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{(*NO | *YES)}|Indicates whether the overflow indi-
|cators should be reset to *OFF when
|a file is opened.
|THREAD(*SERIALIZE)|Indicates that the module is enabled
|to run in a multithreaded environ-
|ment. Access to the procedures in
|the module is to be serialized.
|Definition spec-
|CCSID(number | *DFT)|Sets the graphic and UCS-2 CCSID
|ification
|for the definition.
|keywords
|Built-in functions|%DIV(n:m)|Performs integer division on the two
|operands n and m; the result is n/m.
|The operands must be numeric
|values with zero decimal positions.
|%GRAPH(char-expr |
|Converts to graphic data from single-
|graph-expr | UCS2-expr {:
|byte character, graphic, or UCS-2
|ccsid})
|data.
|%REM(n:m)|Performs the integer remainder oper-
|ation 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 | graph-
|Converts to UCS-2 data from single-
|expr | UCS2-expr {: ccsid})
|byte character, graphic, or UCS-2
|data.
|%XFOOT(array-expr)|Produces the sum of all the ele-
|ments in the specified array
|expression.
xxILE RPG for AS/400 Programmer's Guide
|
Table 2 (Page 2 of 2). New Language Elements Since V4R2
|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.
| Changes to this Guide Since V4R2
|This V4R4 guide,
|in many places from the V4R2 guide,
ILE RPG for AS/400 Programmer's Guide
ILE RPG for AS/400 Programmer's Guide
, SC09-2507-02, differs
,
|SC09-2507-01. Most of the changes are related to the enhancements that have
|been made since V3R7; others reflect minor technical corrections. To assist you in
|using this manual, technical changes and enhancements are noted with a vertical
|bar (|).
About This Guidexxi
xxiiILE RPG for AS/400 Programmer's Guide
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:
¹ Overview of RPG IV language
¹ Role of Integrated Language Environment components in RPG programming
¹ Integrated Language Environment program creation strategies
¹ Overview of coding a module with more than one procedure and prototyped
calls
Copyright IBM Corp. 1994, 1999 1
2ILE RPG for AS/400 Programmer's Guide
RPG IV Overview
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:
¹ Coding specifications
¹ The program cycle
¹ Indicators
¹ Operation codes
For more information on RPG IV, see the
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 positiondependent. 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.
ILE RPG for AS/400 Reference
.
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, 1999 3
Cycle Programming
When a system processes data, it must do the processing in a particular order.
This logical order is provided by:
¹ The ILE RPG compiler
¹ 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.
RPG IV Overview
Start
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 speci-
fied on the control specification.
Figure 1 shows the specific steps in the general flow of the RPG program cycle.
Perform
detail
calculations
Write
heading and
detail lines
Move fields
Get input
record
No
LR on
Yes
Perform
total
calculations
Write
total
output
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).
4ILE RPG for AS/400 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 proc-
essing 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:
¹ handles input parameters, opens files, initializes program data
¹ writes the records conditioned by the 1P (first page) indicator
¹ 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
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.
on
. The program processes the total calculations and total
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 Language5
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.
This section illustrates a simple ILE RPG program that performs payroll calculations.
Problem Statement
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:
A R EMP_REC
A EMP_NUMBER5TEXT('EMPLOYEE NUMBER')
A EMP_NAME16TEXT('EXPLOYEE NAME')
A EMP_RATE5 2TEXT('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:
A R TRN_REC
A TRN_NUMBER5TEXT('EMPLOYEE NUMBER')
A TRN_HOURS4 1TEXT('HOURS WORKED')
A TRN_BONUS6 2TEXT('BONUS')
TRN_HOURSTRN_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
D PayS8P 2
D Heading1C'NUMBER NAMERATEHD OURS BONUSPAY'
D Heading2C'______ ________________ ______ _D____ _______ __________'
D CalcPayPR8P 2
DRate5P 2 VALUE
DHours10U 0 VALUE
DBonus5P 2 VALUE
Example of an ILE RPG Program
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.
OQSYSPRT H1P2 3
O35 'PAYROLL REGISTER'
O *DATEY60
O H1P2
O 60 Heading1
O H1P2
O 60 Heading2
O DN1PN992
O TRN_NUMBER5
O EMP_NAME24
O EMP_RATEL33
OTRN_HOURS L 40
OTRN_BONUS L 49
O Pay60 '$0. '
O DN1P 992
O TRN_NUMBER5
O35 '** NOT ON EMPLOYEE FILE **'
O TLR
O33 'END OF LISTING'
The output specifications describe what fields are to be written on the QSYSPRT
output:
¹ 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.
¹ 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.
¹ 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 Language9
P CalcPayB
D CalcPayPI8P 2
DRate5P 2 VALUE
DHours10U 0 VALUE
DBonus5P 2 VALUE
D OvertimeS5P 2 INZ(0)
* Calculate the total pay and return it to the caller
CRETURNRate * Hours + Bonus + Overtime
P CalcPayE
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.
Example of an ILE RPG Program
*------------------------------------------------------------------------*
* DESCRIPTION: This program creates a printed output of employee's pay *
*for the week.*
*------------------------------------------------------------------------*
D Heading1C'NUMBER NAMERATEHD OURS BONUSPAY'
D Heading2C'______ ________________ ______ _D____ _______ __________'
*------------------------------------------------------------------------*
* Prototype Definition for subprocedure CalcPay*
*------------------------------------------------------------------------*
D CalcPayPR8P 2
DRate5P 2 VALUE
DHours10U 0 VALUE
DBonus5P 2 VALUE
*------------------------------------------------------------------------*
* For each record in the transaction file (TRANSACT), if the employee*
* is found, compute the employee's pay and print the details.*
*------------------------------------------------------------------------*
C TRN_NUMBERCHAIN EMP_REC99
C IFNOT *IN99
CEVALPAY = CalcPay(EMP_RATE : TRN_HOURS :
C 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 H1P2 3
O35 'PAYROLL REGISTER'
O *DATEY60
O H1P2
O 60 Heading1
O H1P2
O 60 Heading2
O DN1PN992
O TRN_NUMBER5
O EMP_NAME24
O EMP_RATEL33
OTRN_HOURS L 40
OTRN_BONUS L 49
O Pay60 '$0. '
O DN1P 992
O TRN_NUMBER5
O35 '** NOT ON EMPLOYEE FILE **'
O TLR
O33 'END OF LISTING'
Figure 4 (Part 2 of 3). A Sample Payroll Calculation Program
Chapter 1. Overview of the RPG IV Programming Language11
* Calculate the total pay and return it to the caller
CRETURNRate * Hours + Bonus + Overtime
P CalcPayE
Figure 4 (Part 3 of 3). A Sample Payroll Calculation Program
Using the OS/400 System
Using the OS/400 System
The operating system that controls all of your interactions with the AS/400 system
is called the Operating System/400 (OS/400) system. From your workstation, the
OS/400 system allows you to:
¹ Sign on and sign off
¹ Interact with the displays
¹ Use the online help information
¹ Enter control commands and procedures
¹ Respond to messages
¹ Manage files
¹ 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:
|
|You can also order the
http://publib.boulder.ibm.com/
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 AS/400
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.
12ILE RPG for AS/400 Programmer's Guide
AS/400 Tools
Table 3. Commonly Used CL Commands
ActionCL commandResult
Using System MenusGO MAINDisplay main menu
GO INFODisplay help menu
GO CMDRPGList commands for RPG
GO CMDCRTList commands for creating
GO CMDxxxList commands for 'xxx'
CallingCALL program-nameRuns a program
CompilingCRTxxxMODCreates xxx Module
CRTBNDxxxCreates Bound xxx Program
BindingCRTPGMCreates a program from ILE
modules
CRTSRVPGMCreates a service program
UPDPGMUpdates a bound program object
The AS/400 system offers a full set of tools that you may find useful for programming.
Application Development ToolSet for AS/400
Application Development ToolSet for AS/400 (ADTS) provides an integrated suite of
host-based tools designed to meet the needs of the application developer. This
product provides tools for manipulating source, objects, and database files on the
AS/400 system. Some of the tools provided are: PDM, SEU, and SDA. A menu
driven interface is available from which you can perform all of the tasks involved in
application development, such as object management, editing, compiling and
debugging.
Application Development Manager
Application Development Manager provides application development organizations
with a mechanism for efficient and effective management of application objects
throughout the life of the application. This feature of ADTS allows a group of developers to create, manage, and organize multiple versions of their application through
the Programming Development Manager (PDM) interface or directly from the
AS/400 command line.
An application development team using ADM can:
Chapter 1. Overview of the RPG IV Programming Language13
AS/400 Tools
¹ Define a flexible environment where production, testing, and maintenance can
be managed simultaneously
¹ Organize several developers working on the same application
¹ Build (or compile) an application quickly and easily, compiling only those com-
ponents that need compiling
¹ Create and maintain several versions of an application
Application Dictionary Services
Application Dictionary Services is an impact analysis tool that speeds up the analysis of applications. The tool stores the information about the application objects
and their relationships to other application objects in a dictionary. A dictionary
extracts the cross-reference information about all of the objects in an application's
libraries, and saves it in a set of database files stored in a library. As application
objects and their relationships to other objects change, the information in the dictionary is automatically updated.
You can use this feature of ADTS to:
¹ Determine the impact of changing a field
¹ Work with fields, files, or programs that would be affected by changing a field
¹ Re-create all of the objects affected by changing a field
¹ View the structure of an application
¹ Determine the field reference hierarchy
¹ Create, modify, or delete programs or files that are documented in a dictionary
¹ Modify any fields or records that are documented in a dictionary
¹ Examine the calling hierarchy
IBM VisualAge RPG and Cooperative Development Environment for
AS/400
IBM VisualAge RPG and Cooperative Development Environment for AS/400 is a
workstation (Windows) product that includes two server access programs:
¹ CoOperative Development Environment/400 (CODE/400)
¹ VisualAge RPG
CODE/400 contains features to help edit, compile, and debug: RPG, ILE RPG,
COBOL, ILE COBOL, Control Language (CL), ILE C, and ILE CL host source programs; design display, printer, and database host files; and manage the components that make up your application. This enhances program development and
moves the program development workload off the host. The application, when built,
runs on an AS/400. For RPG and ILE RPG application development and maintenance, CODE/400 provides:
¹ Language sensitive editing— includes token highlighting, format lines, a full
suite of prompts, and online help.
¹ Incremental syntax checking— provides immediate error feedback as each line
of source is entered
14ILE RPG for AS/400 Programmer's Guide
AS/400 Tools
¹ Program verification— performs, at the workstation, the full range of syntax and
semantic checking that the compiler does, without generating object code
¹ Program conversion— performs, at the workstation, an OPM to ILE RPG con-
version
¹ A windowed environment for submitting host compiles and binds
¹ Source-level debugging
¹ A DDS design utility—allows you to easily change screens, reports, and data-
base files
¹ Access to Application Dictionary Services.
VisualAge RPG offers a visual development environment on the workstation platform for RPG application developers to develop, maintain, and document
client/server applications. Applications can be edited, compiled, and debugged on
your workstation. The applications, when built, are started on a workstation and can
access AS/400 host data and other AS/400 objects. Its integrated components
allow application developers to preserve their current skills and easily develop
AS/400 RPG applications with graphical user interfaces.
If you want to learn more about CODE/400 and VisualAge RPG, see the most
current information available on the World Wide Web at:
http://www.software.ibm.com/ad/varpg/
Chapter 1. Overview of the RPG IV Programming Language15
AS/400 Tools
16ILE RPG for AS/400 Programmer's Guide
RPG Programming in ILE
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 AS/400 system.
ILE is a recent approach to programming on the AS/400 system. It is the result of
major enhancements to the AS/400 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 4 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 4. Programming Languages Supported on the AS/400
Compared to OPM, ILE provides RPG users with improvements or enhancements
in the following areas of application development:
¹ Program creation
¹ Program management
¹ Program call
¹ Source debugging
¹ 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.
Copyright IBM Corp. 1994, 1999 17
RPG Programming in ILE
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
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,
Service Programs
ILE Program
(CRTBNDRPG)
One-Step ProcessTwo-Step Process
RPG Module
(CRTRPGMOD)
ILE Program
(CRTPGM)
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 57. For more information on the two-
18ILE RPG for AS/400 Programmer's Guide
RPG Programming in ILE
step process, see Chapter 7, “Creating a Program with the CRTRPGMOD and
CRTPGM Commands” on page 73. For more information on service programs, see
Chapter 8, “Creating a Service Program” on page 91.
Program Management
ILE provides a common basis for:
¹ Managing program flow
¹ Sharing resources
¹ Using application program interfaces (APIs)
¹ 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.
Program Call
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 109.
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 mixedlanguage 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.
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
Chapter 2. RPG Programming in ILE19
RPG Programming in ILE
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
¹ Operational descriptors
¹ Omitted parameters
¹ The passing of parameters by value
¹ The use of return values
¹ 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 127.
Source Debugging
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 11, “Debugging Programs” on
page 163.
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:
¹ CEETREC – Signal the Termination-Imminent Condition
¹ CEE4ABN – Abnormal End
¹ CEECRHP – Create your own heap
¹ CEEDSHP – Discard your own heap
¹ CEEFRST – Free Storage in your own heap
¹ CEEGTST – Get Heap Storage in your own heap
¹ CEECZST – Reallocate Storage in your own heap
20ILE RPG for AS/400 Programmer's Guide
RPG Programming in ILE
¹ 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 and also the
Multithreaded Applications
|
|The AS/400 now supports multithreading. ILE RPG does not directly support initi|ating 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(*SEREALIZE) 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 acti|vation 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.
System API Reference
.
|For more information, see “Multithreading Considerations” on page 157.
Chapter 2. RPG Programming in ILE21
RPG Programming in ILE
22ILE RPG for AS/400 Programmer's Guide
OPM-Compatible Application
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.
Copyright IBM Corp. 1994, 1999 23
Example of OPM-Compatible Program
Figure 6 shows the run-time view of a sample application where you might want an
OPM-compatible program. The OPM application consisted of a CL 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-Compatible Application
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 callOPM 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.
DataStorage 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.
FilesFile processing is the same as in previous releases. Files are
closed when the program ends normally or abnormally.
ErrorsAs 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.
24ILE RPG for AS/400 Programmer's Guide
ILE Program Using CRTBNDRPG
Related Information
Converting to RPG IV“Converting Your Source” on page 382
One-step creation processChapter 6, “Creating a Program with the
CRTBNDRPG Command” on page 57
ILE static bindingChapter 10, “Calling Programs and
Procedures” on page 127; also
ILE Con-
cepts
Exception handling differences“Differences between OPM and ILE RPG
Exception Handling” on page 222
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.
Chapter 3. Program Creation Strategies25
Example of ILE Program Using CRTBNDRPG
Figure 7 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.
Job
XYZ Activation Group
*PGM(X)
ILE CL
*PGM(Y)
ILE RPG
*SRVPGM(Z)
Supplied Service
Program
ILE Program Using CRTBNDRPG
Figure 7. ILE Program Using CRTBNDRPG
Effect of ILE
The following deals with the effects of ILE on the way your program handles:
Program callThe 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 proce-
dure calls. Procedures within bound programs call each other by
using static calls. Procedures call ILE and OPM programs by
using dynamic calls.
DataThe 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.
and commitment control) by the system is scoped to the activation
group level. You cannot share files at the data management level
26ILE RPG for AS/400 Programmer's Guide
ILE Application Using CRTRPGMOD
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).
ErrorsWhen you call an ILE RPG program or procedure in the same acti-
vation 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.
Related Information
Converting to RPG IV“Converting Your Source” on page 382
One-step creation processChapter 6, “Creating a Program with the
Activation groups“Managing Activation Groups” on page 109
RCLRSC“Reclaim Resources Command” on
ILE static bindingChapter 10, “Calling Programs and
Exception handling differences“Differences between OPM and ILE RPG
Override and open scope“Overriding and Redirecting File Input and
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.
CRTBNDRPG Command” on page 57
page 112
Procedures” on page 127; also
ILE Con-
cepts
Exception Handling” on page 222
Output” on page 273 and “Sharing an Open
Data Path” on page 277; 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:
¹ A single-language application
¹ A mixed-language application
Chapter 3. Program Creation Strategies27
¹ An advanced application
The effect of ILE is the same as described in “Effect of ILE” on page 26.
ILE Application Using CRTRPGMOD
Method
You may want to read about the basic ILE concepts in
this approach.
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:
¹ 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.
¹ 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.)
¹ 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.
ILE Concepts
before using
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.
28ILE RPG for AS/400 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 mixedlanguage ILE program where one module calls a non-bindable API, QUSCRTUS
(Create User Space).
Chapter 3. Program Creation Strategies29
Job
Y Activation Group
*PGM(Y)
CL *MODULE(Y1)
RPG *MODULE(Y2)
ILE Application Using CRTRPGMOD
C *MODULE(Y3)
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.
Default Activation Group
*PGM(QUSCRTUS)
30ILE RPG for AS/400 Programmer's Guide
A Strategy to Avoid
Job
XYZ Activation Group
*PGM(X)
CL *MODULE(X1)
*SRVPGM(Y)
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 processChapter 7, “Creating a Program with the
RPG *MODULE(X2)
RPG
*SRVPGM(Z)
C *MODULE(Z1)
CL *MODULE(Z2)
CRTRPGMOD and CRTPGM Commands”
on page 73
Activation groups“Managing Activation Groups” on page 109
ILE static bindingChapter 10, “Calling Programs and
Exception HandlingChapter 12, “Handling Exceptions” on
Service programsChapter 8, “Creating a Service Program” on
Updating a Program“Using the UPDPGM Command” on
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.
Procedures” on page 127; also
cepts
page 217; also
page 91; also
ILE Concepts
ILE Concepts
page 87
ILE Con-
Chapter 3. Program Creation Strategies31
Job
Default Activation Group
*PGM(X)
CL
QILE Activation Group
*PGM(Y)
RPG
*SRVPGM(Z)
RPG
A Strategy to Avoid
Figure 11. Scenario to Avoid. An application is split between the OPM default activation
group and a named activation group.
When 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.
32ILE RPG for AS/400 Programmer's Guide
Multiple Procedures Module
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:
¹ Overview of key concepts
¹ Example of module with more than one procedure
¹ 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 proce-dure 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:
¹ Names that are defined within subprocedure are not accessible outside the
subprocedure.
¹ No cycle code is generated for the subprocedure.
¹ The call interface must be prototyped.
¹ Calls to subprocedures must be bound procedure calls.
¹ 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.
Copyright IBM Corp. 1994, 1999 33
Multiple Procedures Module
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.
Figure 12 on page 34 shows what a module might look like with multiple procedures.
*MODULE
Main Procedure
H
Main
Source
Section
specifications
F
specifications
D
specifications - Data items visible
throughout module
I
specifications
C
specifications
O
specifications
Subprocedure 1
P
specification
D
specifications - Data items visible only
to Subprocedure 1
C
specifications - Can access local and
global data items
P
specifications
Local
Scope
Global
Scope
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:
Subprocedure 2
P
specification
D
specifications - Data items visible
only to Subprocedure 2
C
specifications - Can access local and
global data items
P
specifications
Program Data - part of main source section
Local
Scope
¹ Whether the call is bound (procedure) or dynamic (program)
¹ How to find the program or procedure (the external name)
34ILE RPG for AS/400 Programmer's Guide
Multiple Procedures Module
¹ The number and nature of the parameters
¹ Which parameters must be passed, and which are optionally passed
¹ Whether operational descriptors are passed (for a procedure)
¹ 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 FmtCustPR
D Name100A
D Address100A
Figure 13. Prototype for FmtCust Procedure
To produce the formatted output fields, FmtCust calls a procedure NumToChar.
NumToChar has a numeric input parameter that is passed by value, and returns a
character field. Figure 14 shows the prototype for NumToChar.
* Prototype for procedure NumToChar
* The returned value is a character field of length 31.
D NumToCharPR31A
* The input parameter is packed with 30 digits and 0 decimal
* positions, passed by value.
DNUMPARM30P 0VALUE
Figure 14. Prototype for NumToChar 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.
CCALLPFmtCust(RPTNAME : RPTADDR)
Figure 15. Calling the FmtCust Procedure
Using prototyped calls you can call (with the same syntax):
¹ Programs that are on the system at run time
¹ Exported procedures in other modules or service programs that are bound in
the same program or service program
¹ Subprocedures in the same module
Chapter 4. Creating an Application Using Multiple Procedures35
Example of Module with Multiple Procedures
In order to format the name and address properly, FmtCust calls NumToChar to
convert the customer number to a character field. Because FmtCust wants to use
the return value, the call to NumToChar is made in an expression. Figure 16 on
page 36 shows the call.
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 opens up a number of new options for parameter passing.
¹ 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.
¹ 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 'miniapplication' 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.
36ILE RPG for AS/400 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.
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.
C *ISOMOVEDUEDATEDateDue
C CurDateSUBDURDateDueDaysLate:*D
CIFDaysLate > 60 AND
CAMOUNT > 100.00
CRETURN'1'.4/CELSE
CRETURN'0'.4/ .5/CENDIF
P InArrearsE.1/
Figure 18. Source for Subprocedure InArrears
Figure 18 shows the main elements that are common to all subprocedures.
Chapter 4. Creating an Application Using Multiple Procedures37
Example of Module with Multiple Procedures
.1/All subprocedures begin and end with procedure specifications.
.2/After the Begin-Procedure specification (B in position 24 of the proce-
dure 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 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.
One of the formatting tasks requires converting a numeric field to a character field
to match the output field type. This conversion could be coded as part of the subprocedure itself. However, as this is a task that might be required by other reports,
we decided to code the conversion as a separate subprocedure, NumToChar.
NumToChar takes as input a numeric parameter that is passed by value. It converts the number to a character field and returns that field to the caller, in this case
FmtCust.
Note that NumToChar is a prototyped procedure, and so you might expect to see
its prototype inside of FmtCust. You could place the prototype in FmtCust.
However, we placed it in the main source section, so that it would be available to
any subprocedure we might add to ARRSRPT. This is shown later on.
Finally, consider the last subprocedure of this application, NumToChar. Notice that
NumToChar does not appear in the ARRSRPT module, that is shown in Figure 17
on page 37. We decided to place NumToChar inside another module called
CVTPROCS. CVTPROCS 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 CVTPROCS. 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 Procedures39
* NumToChar converts a numeric field to a character field
*
* Parameters: NUMPARM(input)
* Globals:(none)
* Returns:character string
*
* The subprocedure will be called by procedures outside of this
* module, and so the keyword EXPORT is required to indicate this.
*-----------------------------------------------------------------*
P NumToCharBEXPORT
D NumToCharPI31A
DNUMPARM30P 0VALUE
* Local declarations
D POSS5P 0
D SIGNS1A INZ(' ')
D ZONEDSDS
DNUM30S 0
DCHAR30A OVERLAY(NUM)
*
* Body of procedure:
* Handle special case of zero
CIFNUMPARM = 0
CRETURN'0'
CENDIF
* Handle negatives. Set sign to '-' and make positive.
CIFNUMPARM < 0
CEVALNUMPARM = - NUMPARM
CEVALSIGN = '-'
CENDIF
* Get the input number in character form using a data structure
CEVALNUM = NUMPARM
* Left-justify
C
C '0'CHECK CHARPOS
CEVALCHAR = %SUBST(CHAR:POS)
* Return the value adding the sign
CRETURN%TRIML(SIGN + CHAR)
P NumToCharE
Example of Module with Multiple Procedures
Figure 20. Source for module CVTPROCS, containing subprocedure NumToChar
CVTPROCS 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 46.
40ILE RPG for AS/400 Programmer's Guide
Example of Module with Multiple Procedures
The Entire ARRSRPT Program
The ARRSRPT program consists of two modules: ARRSRPT and CVTPROCS.
Figure 21 shows the different pieces of our mini-application.
ARRSRPT *PGM
ARRSRPT *MODULE
Main Procedure
InArrears
FmtCust
CVTPROCS *MODULE
NOMAIN
NumToChar
Figure 21. The ARRSRPT Application
/COPY member
CVTPROCP
CUSTFILE
DDS
CUSTRPT
DDS
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 (NumToChar called by FmtCust)
*=================================================================*
*--------------------------------------------------------------*
* F I L E S
*
* CUSTFILE - contains customer information
* CUSTRPT - printer file (using format ARREARS)
*--------------------------------------------------------------*
FCUSTFILE IPEDISK
FCUSTRPTOEPRINTER
Figure 22 (Part 1 of 3). ILE RPG Complete Source for ARRSRPT Module
Chapter 4. Creating an Application Using Multiple Procedures41
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:
¹ General
¹ Program Creation
¹ Main Procedures
¹ Subprocedures
General Considerations
¹ 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.
¹ 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.
Chapter 4. Creating an Application Using Multiple Procedures45
Program Creation
¹ 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.
¹ 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.
¹ A program that is created to run in the default OPM activation group (by speci-
fying DFTACTGRP(*YES) on the CRTBNDRPG command) cannot contain
bound procedure calls.
Main Procedure Considerations
¹ Because the main procedure is the only procedure with a complete set of spec-
ifications available (except the P specification), it should be used to set up the
environment of all procedures in the module.
Coding Considerations
¹ A main procedure is always exported, which means that other procedures in
the program can call the main procedure by using bound calls.
¹ 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
¹ 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.
¹ You cannot define return values for a main procedure, nor can you specify that
its parameters be passed by value.
Subprocedure Considerations
¹ 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.
¹ The control specification can only be coded in the main source section since it
controls the entire module.
¹ 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.)
46ILE RPG for AS/400 Programmer's Guide
For Further Information
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.
¹ 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
Main Procedure End“Returning from a Main Procedure” on page 152
Subprocedures
Topic See
DefiningChapter on subprocedures, in the
NOMAIN module“Creating a NOMAIN Module” on page 75
page 220
ILE RPG for AS/400
Reference
Exception handling“Exception Handling within Subprocedures” on
page 221
Procedure Specification Chapter on procedure specifications, in the
ILE RPG for
AS/400 Reference
Procedure InterfaceChapter on defining data and prototypes in the
ILE
RPG for AS/400 Reference
Subprocedure End“Returning from a Subprocedure” on page 154
Chapter 4. Creating an Application Using Multiple Procedures47
Prototyped Call
For Further Information
Topic See
Free-form call“Using a Prototyped Call” on page 133
General Information
Passing parameters“Passing Prototyped Parameters” on page 135
PrototypesChapter on defining data and prototypes in the
ILE RPG for AS/400 Reference
RPG for AS/400 Reference
, Chapter 24
ILE
48ILE RPG for AS/400 Programmer's Guide
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:
¹ Enter source statements
¹ Create modules
¹ Read compiler listings
¹ Create programs
¹ Create service programs
¹ Run programs
¹ Pass parameters
¹ Manage the run time
¹ Call other programs or procedures
Many Integrated Language Environment terms and concepts are discussed briefly
in the following pages. These terms and concepts are more fully discussed in
Concepts
.
ILE
Copyright IBM Corp. 1994, 1999 49
50ILE RPG for AS/400 Programmer's Guide
Chapter 5.Entering Source Statements
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:
¹ Interactively using SEU
¹ Interactively using CODE/400
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
RPGcompiler will convert most of the source to uppercase when it compiles
it. It will not convert literals, array data or table data.
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.
128020
Seq#/Date
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.
CodeComments
For more information about creating libraries and source physical files, refer to the
ADTS for AS/400: Source Entry Utility
Development Manager
Copyright IBM Corp. 1994, 1999 51
manual.
manual and the
ADTS/400: Programming
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
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:
¹ Create a library
Using SEU
ADTS for AS/400: Source Entry Utility
¹ Create a source physical file
¹ Start an SEU editing session
¹ 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:
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 on page 53. Note that
the screen is automatically shifted so that position 6 is (for specification type) at
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*
AR EMPREC
AENUM5 0TEXT('EMPLOYEE NUMBER')
AENAME20TEXT('EMPLOYEE NAME')
AENHRS3 1TEXT('EMPLOYEE NORMAL WEEK HOURS')
AK 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 AS/400 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:
¹ Enter your SQL statements on the Calculation specification
¹ Start your SQL statements using the delimiter /EXEC SQL in positions 7-15
(with the / in position 7)
¹ You can start entering your SQL statements on the same line as the starting
delimiter
¹ Use the continuation line delimiter (a + in position 7) to continue your state-
ments on any subsequent lines
¹ Use the ending delimiter /END-EXEC in positions 7-15 (with the slash in posi-
tion 7) to signal the end of your SQL statements.
Note: SQL statements cannot go past position 80 in your program.
Figure 30 on page 56 shows an example of embedded SQL statements.
You must enter a separate command to process the SQL statements. Refer to the
DB2 UDB for AS/400 SQL Programming
Reference
for more information.
manual and the
DB2 UDB for AS/400 SQL
Refer to the
ADTS for AS/400: Source Entry Utility
how SEU handles SQL statement syntax checking.
manual for information about
56ILE RPG for AS/400 Programmer's Guide
Using the CRTBNDRPG Command
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:
¹ Use the CALLB operation in your source
¹ Call a prototyped procedure
¹ 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.
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.
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
Copyright IBM Corp. 1994, 1999 57
command. For more information see Chapter 7, “Creating a Program with
the CRTRPGMOD and CRTPGM Commands” on page 73.
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 5 summarizes the parameters of the CRTBNDRPG command and shows
their default values.
Table 5 (Page 1 of 2). CRTBNDRPG Parameters and Their Default Values Grouped by Function
Program Identification
PGM(*CURLIB/*CTLSPEC)Determines created program name and library
SRCFILE(*LIBL/QRPGLESRC)Identifies source file and library
SRCMBR(*PGM)Identifies file member containing source specifications
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 gener-
|ated 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
*EXPDDS *EXT *NOSHOWSKP
Specifies the contents of compiler listing
|*NOSRCSTMT )
Data Conversion Options
CVTOPT(*NONE)Specifies how various data types from externally described files
are handled
Using the CRTBNDRPG Command
58ILE RPG for AS/400 Programmer's Guide
Using the CRTBNDRPG Command
Table 5 (Page 2 of 2). CRTBNDRPG Parameters and Their Default Values Grouped by Function
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 gener-
|ated 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.
See Appendix C, “The Create Commands” on page 405 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:
¹ *STMT — allows you to display variables and set breakpoints at statement
locations using a compiler listing. No source is displayed with this view.
¹ *SOURCE — creates a view identical to your input source.
¹ *COPY — creates a source view and a view containing the source of any
/COPY members.
¹ *LIST — creates a view similar to the compiler listing.
¹ *ALL — creates all of the above views.
¹ *NONE — no debug data is created.
The source for EMPRPT is shown in Figure 28 on page 54.
Figure 31. Display Module Source display for EMPRPT
Display Module Source
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 11, “Debugging Programs” on
page 163.
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.
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.
60ILE RPG for AS/400 Programmer's Guide
Using the CRTBNDRPG Command
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 62.
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 compat-
ibility. 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:
¹ DSPJOB and then select option 4 (
Display spooled files
)
¹ WRKJOB
¹ WRKOUTQ
queue-name
¹ WRKSPLF
Chapter 6. Creating a Program with the CRTBNDRPG Command61
*------------------------------------------------------------------------*
* DESCRIPTION: This program creates a printed output of employee's pay *
*for the week.*
*------------------------------------------------------------------------*
D Heading1C'NUMBER NAMERATEHD OURS BONUSPAY'
D Heading2C'______ ________________ ______ _D____ _______ __________'
*------------------------------------------------------------------------*
* For each record in the transaction file (TRANSACT), if the employee*
* is found, compute the employees pay and print the details.*
*------------------------------------------------------------------------*
C TRN_NUMBERCHAIN EMP_REC99
C IFNOT *IN99
CEVAL (H) Pay = EMP_RATE * TRN_HOURS + TRN_BONUS
C ENDIF
Using the CRTBNDRPG Command
Figure 32 (Part 1 of 2). A Sample Payroll Calculation Program
*------------------------------------------------------------------------*
* 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 H1P2 3
O35 'PAYROLL REGISTER'
O *DATEY60
O H1P2
O 60 Heading1
O H1P2
O 60 Heading2
O DN1PN992
O TRN_NUMBER5
O EMP_NAME24
O EMP_RATEL33
OTRN_HOURS L 40
OTRN_BONUS L 49
O Pay60 '$0. '
O DN1P 992
O TRN_NUMBER5
O35 '** NOT ON EMPLOYEE FILE **'
O TLR
O33 'END OF LISTING'
Figure 32 (Part 2 of 2). A Sample Payroll Calculation Program
62ILE RPG for AS/400 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:
¹ Fix compilation errors
¹ Fix run-time errors
¹ Provide documentation for maintenance purposes.
See Appendix D, “Compiler Listings” on page 423 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
of the following sections:
¹ Prologue (command option summary)
¹ Source Listing, which includes:
– In-Line diagnostic messages
– Match-field table (if using the RPG cycle with match fields)
¹ Additional diagnostic messages
¹ Field Positions in Output Buffer
¹ /COPY Member Table
¹ Compile Time Data which includes:
– Alternate Collating Sequence records and table or NLSS information and
table
– File translation records
– Array records
– Table records
¹ Message summary
¹ Final summary
minimally
¹ Code generation report (appears only if there are errors)
¹ 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)
Chapter 6. Creating a Program with the CRTBNDRPG Command63
*SHOWSKP
Source lines excluded by conditional compilation directives (appear in
source section of listing)
*EXPDDS
Key field information (separate section)
*XREFList of Cross references (separate section)
*EXTList of External references (separate section)
*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 430 and "*SRCSTMT Source Heading" on page 430.
Using a Compiler Listing
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:
¹ Customize the page heading
¹ Customize the spacing
¹ 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:
¹ Select one of the following date separators: *SYSVAL, *BLANK, slash (/),
hyphen (-) period (.) or comma (,)
¹ Select one of the following date formats: *SYSVAL, *YMD, *MDY, *DMY, or
*JUL
64ILE RPG for AS/400 Programmer's Guide
Using a Compiler Listing
¹ 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.
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
ILE RPG for AS/400 Reference
.
Indenting Structured Operations
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:
¹ Do Num
¹ Last Update
¹ 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 66 shows part of source listing which was produced with indentation. The indentation mark is '| '.
Chapter 6. Creating a Program with the CRTBNDRPG Command65
Line <--------------------- Source Specifications ----------------------------------------------><---- Comments ----> Src Seq
Number ....1....+....2....+<-------- 26 - 35 -------->....4....+....5....+....6....+....7....+....8....+....9....+...10 Id Number
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:
¹ The source section
¹ The Additional Messages section
¹ The /COPY table section
¹ 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 secondlevel 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:
¹ 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.
¹ Output-buffer positions
66ILE RPG for AS/400 Programmer's Guide
Using a Compiler Listing
Lists the start and end positions along with the literal text or field names. Use
this to check for errors in your output specifications.
¹ Compile-time data
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 DateIdNumber
63 CSETOFF_12___003100
======> aabb
======> cccccc
*RNF5051 20 a003100 Resulting-Indicator entry is not valid; defaults to blanks.
*RNF5051 20 b003100 Resulting-Indicator entry is not valid; defaults to blanks.
*RNF5053 30 c003100 Resulting-Indicators entry is blank for specified
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 DateIdNumber
1 D FLD1S+5LIKE(FLD2)000100
2 D FLD2SD000200
*RNF3479 201 000100 A length adjustment is not allowed for a field of the
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).
Chapter 6. Creating a Program with the CRTBNDRPG Command67
Using a Compiler Listing
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
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
Source Entry Utility
.
ADTS for AS/400:
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.
left
|If OPTION(*NOSRCSTMT) is specified, the Line Number on 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
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
|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
|sequence number.
left
side of the compiler listing, and is also the same as the SEU
side of the
right
right
side of the
side
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 432.
68ILE RPG for AS/400 Programmer's Guide
Using a Compiler Listing
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:
¹ If you use the source debugger to debug your program you have a choice of
debug views: *STMT, *SOURCE, *LIST, *COPY, *ALL.
¹ 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
|OPTION(*NOSRCSTMT) is specified, and in the column labeled as the State|ment Number when OPTION(*SRCSTMT) is specified.
¹ 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.
¹ If you specify DBGVIEW(*LIST), the information available to you while debug-
ging 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:
¹ Teaching the program to a new programmer.
¹ 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 parame-
ters on both create commands.
Of particular value for program maintenance is the Prologue section of the listing.
This section tells you:
¹ Who compiled the module/program
¹ What source was used to produce the module/program
¹ 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:
¹ *SHOWCPY and *EXPDDS provide a complete description of the program,
including all specifications from /COPY members, and generated specifications
from externally described files.
Chapter 6. Creating a Program with the CRTBNDRPG Command69
¹ *SHOWSKP allows you to see the statements that are ignored by the compiler
as a result of /IF, /ELSEIF, /ELSE, OR /EOF directives.
¹ *XREF allows you to check the use of files, fields, and indicators within the
module/program.
¹ *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 74) 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.
To access the RETURNCODE data area, specify RETURNCODE in factor 2 of a
*DTAARA DEFINE statement.
The data area RETURNCODE has the following format:
Accessing the RETURNCODE Data Area
ByteContent and Meaning
1For 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.
2Character '1' means that the compilation failed because of compiler
errors.
3Character '1' means that the compilation failed because of source
errors.
4Not set. Always '0'.
5Character '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-10Number of source statements
11-12Severity level from command
13-14Highest severity of diagnostic messages
15-20Number of errors that are found in the module (CRTRPGMOD) or
program (CRTBNDRPG).
21-26 Compile date
27-32 Compile time
33-100Not set. Always blank
101-110Module (CRTRPGMOD) name or program (CRTBNDRPG) name.
111-120Module (CRTRPGMOD) library name or program (CRTBNDRPG) library
name.
121-130Source file name
70ILE RPG for AS/400 Programmer's Guide
Accessing the RETURNCODE Data Area
131-140Source file library name
141-150Source file member name
151-160Compiler listing file name
161-170Compiler listing library name
171-180Compiler listing member name
181-329Not set. Always blank
330-334Total elapsed compile time to the nearest 10th of a second
335Not set. Always blank
336-340Elapsed compile time to the nearest 10th of a second
341-345Elapsed translator time to the nearest 10th of a second
346-379Not set. Always blank
380-384Total compile CPU time to the nearest 10th of a second
385Not set. Always blank
386-390CPU time that is used by compiler to the nearest 10th of a second
391-395CPU time that is used by the translator to the nearest 10th of a second
396-400Not set. Always blank
Chapter 6. Creating a Program with the CRTBNDRPG Command71
Accessing the RETURNCODE Data Area
72ILE RPG for AS/400 Programmer's Guide
Creating a Module Object
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:
¹ Create a module object from RPG IV source
¹ Bind modules into a program using CRTPGM
¹ Read a binder listing
¹ Change a module or program
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:
¹ 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.
¹ 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.
This ability to combine modules allows you to:
Copyright IBM Corp. 1994, 1999 73
Creating a Module Object
¹ Reuse pieces of code. This generally results in smaller programs. Smaller pro-
grams give you better performance and easier debugging capabilities.
¹ Maintain shared code with little chance of introducing errors to other parts of
the overall program.
¹ 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.
¹ 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 6 lists the parameters of the CRTRPGMOD command and their systemsupplied defaults. The syntax diagram of the command and a description of the
parameters are found in Appendix C, “The Create Commands” on page 405.
Table 6 (Page 1 of 2). CRTRPGMOD Parameters and Their Default Values Grouped by Function
Module Identification
MODULE(*CURLIB/*CTLSPEC)Determines created module name and library
SRCFILE(*LIBL/QRPGLESRC)Identifies source file and library
SRCMBR(*MODULE)Identifies file member containing source specifications
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 gener-
|ated 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
ENBPFRCOL(*PEP)Specifies whether performance collection is enabled
74ILE RPG for AS/400 Programmer's Guide
Creating a Module Object
Table 6 (Page 2 of 2). CRTRPGMOD Parameters and Their Default Values Grouped by Function
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 char-
acter for marking it
OPTION(*XREF *NOSECLVL *SHOWCPY
*EXPDDS *EXT *NOSHOWSKP
|*NOSRCSTMT )
Data Conversion Options
CVTOPT(*NONE)Specifies how various data types from externally described files
ALWNULL(*NO)Determines if the module will accept values from null-capable
FIXNBR(*NONE)Determines which decimal data that is not valid is to be fixed by
Run-Time Considerations
SRTSEQ(*HEX)Specifies the sort sequence table to be used
|OPTION(*DEBUGIO)|*DEBUGIO/*NODEBUGIO, determines if breakpoints are gener-
|ated for input and output specifications
LANGID(*JOBRUN)Used with SRTSEQ to specify the language identifier for sort
TRUNCNBR(*YES)Specifies action to take when numeric overflow occurs for
Specifies the contents of compiler listing
are handled
fields
the compiler
sequence
packed-decimal, zoned-decimal, and binary fields in fixed format
operations.
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 63. A sample compiler listing is provided in Appendix D, “Compiler Listings”
on page 423.
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 shown in Figure 36 on page 76. The prototypes for the procedures in TRANSSVC are stored in a /COPY member, as shown in Figure 37 on
page 78.
* 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.