29
Fri, Nov
0 New Articles

Let's Write a Procedure

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Exporting procedure names is a bit confusing. By default, RPG IV procedure names are exported with the name specified in positions 7 to 21 of the Procedure specification (a.k.a. P specification or P-spec). But you can export a procedure name as any name you want, effectively creating an alias for the procedure name itself.

RPG IV is a case-insensitive language. Whether you write in uppercase, lowercase, or mixed case, it is all converted to uppercase by the compiler. For example, CustNo, custno, or CUSTNO would be converted to CUSTNO.

While this example is for field names, the same holds true for procedure names. However, the language does provide a way for you to export and call a procedure that is not in uppercase. Why is there a specific feature for non-uppercase procedure names? Consider this: RPG converts all procedure names, like it does for field names, to uppercase. But there are other languages that are case-sensitive. The C language, for example is case-sensitive. So procedures written in C are not converted to uppercase. Consequently, in order for RPG IV to be able to call a procedure written in C, it must have a mechanism to call non-uppercase procedure names.

A procedure in RPG IV consists of four parts:

  • Beginning and ending P specifications--The beginning and ending P specifications outline the body of the procedure implementation as well as the procedure interface.
  • Procedure interface--The procedure interface is the "entry plist" of the procedure. It must immediately follow the beginning P specification.
  • Procedure implementation--The procedure implementation includes the Definition and Calculation specifications of the procedure that holds the variables, and it does the work of the procedure.
  • Prototype--The prototype is a separate set of code that the compiler uses to make sure the parameters you pass to the procedure match those that are defined on the procedure interface. It is the prototype that also allows you to identify the name used to export (make available) the procedure name. That is, the prototype can be used to export the procedure name in uppercase, lowercase, or mixed case.

To illustrate these components, let's look at a simple example of a procedure. First, we have the P specifications. Our example procedure will calculate the cube root of a given value. The cube root will be returned to the caller.

The P specifications for the CUBEROOT procedure are as follows:

     P CubeRoot        B                   EXPORT
      **  Procedure implementation code goes here.
     P CubeRoot        E

By default, the RPG compiler converts this procedure name from "CubeRoot" as specified above to "CUBEROOT."

Next, we need to add the procedure interface. This is the parameter list for the procedure as well as the return value. The procedure interface is inserted after the beginning P specification as follows:

     P CubeRoot        B                   EXPORT

     D CubeRoot        PI            30P10
     D  nValue                       30P10 Const

      **  Procedure implementation code goes here.

     P CubeRoot        E

Note that the name of the procedure is repeated on the procedure interface. While this is optional, I strongly recommend that you always specify the procedure name with your procedure interface.

The P specifications and the procedure interface are the three locations where the procedure name is specified when creating the implementation of the procedure.

In addition to the procedure interface, there is the prototype. As mentioned, the prototype is used by the compiler to syntax check the parameters passed to the procedure. It does this by testing the data types as well as checking whether or not they are constant (i.e., literal) values.

The easiest way to create a prototype is to copy the entire procedure interface and change the "PI" on the first line to "PR."

So this:

     D CubeRoot        PI            30P10
     D  nValue                       30P10 Const

Becomes this:

     D CubeRoot        PR            30P10
     D  nValue                       30P10 Const

The subtle difference is in columns 24 and 25: "PI" for the procedure interface and "PR" for the prototype.

It is a great programming practice to store the prototypes for your procedures in a secondary source member. For example, if the procedure is in a source member named MYSTUFF in QRPGLESRC, you might store the prototypes for the procedures you've created in MYSTUFF in a source member named MYSTUFF in the QCPYSRC source file. Don't have a QCPYSRC file? Create it as follows:

  CRTSRCPF  QCPYSRC RCDLEN(112)

Upper/Lowercase Procedure Names

So how do you export a procedure name in upper/lowercase? In the procedure interface and prototype, the procedure name is specified on regular RPG IV source lines. Therefore, the procedure name is always converted to uppercase. So "CubeRoot" becomes "CUBEROOT" when compiled.

Procedure names are case-sensitive. If you attempt to call the CUBEROOT procedure in mixed case, the compile will fail. For example:

     C                   callb    'CubeRoot'

This will not compile because the procedure name is quoted on the CALLB opcode and the compiler does not convert quoted text strings to uppercase. The procedure name is CUBEROOT, not CubeRoot, so the compile will fail.

To cause a procedure name to be created with an upper/lowercase name, you must add the EXTPROC keyword to the prototype. Normally, this keyword is not needed, but when the procedure name you want to call is either different from the prototype name or not in uppercase, then you need to specify the EXTPROC keyword, as follows:

EXTPROC('CubeRoot')

The EXTPROC keyword identifies the name of the procedure that the compile is going to reference when you do a call to the prototype. That's right: The call is still made to the name you specify on the prototype in columns 7 to 21 and is case-insensitive. But the compiler actually evokes the procedure name identified on the EXTPROC keyword. The complete CUBEROOT prototype follows:

     D CubeRoot        PR            30P10 ExtProc('CubeRoot')
     D  nValue                       30P10 Const

When this is compiled, the name "CubeRoot" in columns 7 to 21 is folded to uppercase by the compiler and becomes "CUBEROOT." However, the actual procedure 'CubeRoot' specified on the EXTPROC keyword is not translated since it is quoted.

To call the 'CubeRoot' procedure, you still specify the prototype name (columns 7 to 21). The way it is specified (uppercase, lowercase, mixed case) is irrelevant. For example:

     C                   eval      nRoot = CubeRoot(1234)

     C                   eval      nRoot = CUBEROOT(1234)

     C                   eval      nRoot = cuberoot(1234)

All three of the previous statements refer to the prototype name. Since they are not quoted character strings, RPG IV converts all three to uppercase, as follows:

     C                   EVAL      NROOT = CUBEROOT(1234)

     C                   EVAL      NROOT = CUBEROOT(1234)

     C                   EVAL      NROOT = CUBEROOT(1234)

The compiler also converts the prototype to uppercase, as follows:

     D CUBEROOT        PR            30P10 EXTPROC('CubeRoot')
     D  NVALUE                       30P10 CONST

Note that since the EXTPROC keyword includes 'CubeRoot' (in quotes), the compiler avoids converting that string to uppercase. Consequently, the name 'CubeRoot' is used as the procedure name.

The prototype must be included in the same source member as that of the procedure implementation. The compiler uses the prototype to make sure it matches the parameters of the procedure interface and to identify the name used to export the procedure.

Exporting a Procedure Name

The EXPORT keyword allows a procedure to be called from another module (e.g., from another source member). The syntax to allow this is as follows:

     P CubeRoot        B                   EXPORT

The EXPORT keyword is specified on the beginning P specification. Without this keyword, you will not be able to call the procedure from outside the source member that contains its implementation.

As a rule of thumb, you should always specify EXPORT, avoiding it only when you are certain you will not need to call it from outside the source member. If you make it a habit, as I have, you can avoid those cryptic "Reference to undefined symbol..." messages.

Here's the entire CubeRoot procedure defined in a source member, along with a dummy example of how to call it. This source member should compile on all versions of OS/400 and i5/OS.

The Prototype Source Member

      **  Source Mbr:  MYMATH
     D CubeRoot        PR            30P10 ExtProc('CubeRoot')
     D  nValue                       30P10 Const

The Sample Procedure and Usage

      **  Source Mbr: TESTCUBE
     H OPTION(*NODEBUGIO : *SRCSTMT)
      /IF DEFINED(*CRTBNDRPG)
     H DFTACTGRP(*NO) ACTGRP(*NEW)
      /ENDIF

      /COPY QCPYSRC,MYMATH

     D nRoot           S             20P10

     C                   eval      *INLR = *ON

     C                   eval      nRoot = CubeRoot(1234)

     P CubeRoot        B                   EXPORT
     D CubeRoot        PI            30P10
     D  nValue                       30P10 Const
       
     C                   return    nValue ** (1/3)
     P CubeRoot        E

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.

BOB COZZI

Bob Cozzi is a programmer/consultant, writer/author, and software developer. His popular RPG xTools add-on subprocedure library for RPG IV is fast becoming a standard with RPG developers. His book The Modern RPG Language has been the most widely used RPG programming book for more than a decade. He, along with others, speaks at and produces the highly popular RPG World conference for RPG programmers.


MC Press books written by Robert Cozzi available now on the MC Press Bookstore.

RPG TnT RPG TnT
Get this jam-packed resource of quick, easy-to-implement RPG tips!
List Price $65.00

Now On Sale

The Modern RPG IV Language The Modern RPG IV Language
Cozzi on everything RPG! What more could you want?
List Price $99.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: