21
Sat, Dec
3 New Articles

Breaking Apart Your Source

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
For years, I've been teaching RPG and RPG IV to programmers, and one question I always ask is, "Are you using /COPY?" Well, the answer will probably be no surprise to you, but few (virtually none) are, and this is not good.

The /COPY directive in RPG III and RPG IV allows you to selectively include source code from outside the current source member. This means you can store commonly used code--such as procedure prototypes, global field declarations, and perhaps even compiler options--in separately maintained source members. How cool is that!

When I've asked my students why they don't use /COPY, two answers represent 99% of their responses: 1) They can't see the source when they edit the main source member, and 2) they simply never started using it.

I think the first response pinpoints what, to me, is the biggest flaw in the way AS/400 RPG programmers write code; they use SEU (edit source). This is perhaps the most significant practice that is keeping RPG programmers a generation behind their PC, Linux, and UNIX counterparts. Stop using SEU!

The second response is more understandable. After all, there are many features in RPG that the general programming community does not use. But /COPY or the ability to include separate source members at compile time has become a fundamental programming practice--so much so that IBM recently enhanced RPG with a second include feature, the /INCLUDE directive.

/COPY and /INCLUDE allow the included source member to contain any regular RPG source code, including another /COPY or /INCLUDE statement. This is known as nested /COPY. /COPY differs from /INCLUDE in that the current SQL preprocessor doesn't know about /INCLUDE, so it lets /INCLUDE pass through the compiler's SQL preprocessor without being processed. That is, unlike /COPY, /INCLUDE statements are not expanded by the SQL preprocessor; rather, they are expanded when the actual RPG compiler is evoked.

Why the difference? The SQL preprocessor, it appears, is aging. It does not recognize contemporary compiler features such as compiler directives and nested /COPY statements. In fact, it fails if a source member being included by /COPY contains a /COPY statement itself. Since the SQL preprocessor doesn't know about /INCLUDE, it allows /INCLUDE to pass through the preprocessor phase with being processed. This allows the RPG compiler itself to process the /INCLUDE member and any of its statements, similar to what happens with the regular /COPY when not using embedded SQL. Aside from the SQL preprocessor issue, the two directives are identical.

Prototypes and /COPYs

One of the biggest advantages of using the /COPY statement is that it allows you to import prototypes for procedures. Since most new code written in RPG IV will probably take advantage of procedures and every procedure requires a prototype, the benefit of /COPY and /INCLUDE should become obvious.

Let's assume we have several procedures that we've created for an application. Most of those procedures are written in RPG IV, and some are written in another language, such as C. It turns out that we want to use some of these procedures in multiple applications. For example, we have several "date and time" procedures and perhaps some CGI procedures.

In order to use these procedures, the prototype for the procedure needs to be included in each source member that refers to the procedure--that is, in source members where the procedure is called and in the source member that defines the procedure itself.
So if we have three source members that contain the procedure definitions for several procedures, and those source members are named DATERTN, STRRTN, and SYSTOOLS, we would have something like the following:

Member: DATERTN
Member: STRRTN
Member: SYSTOOLS
GetDay()
GetDayAsString()
GetEndOfMonth()
ToUpper()
ToLower()
FindReplace()
RtvMbrD()
RunCmd()
RtvFldList()


When these source members are compiled, an individual *MODULE object is created that contains the compiled code for the procedure. We can then bind by copy (physically bind or copy these modules into our application) or bind by reference (create a service program containing these modules).

In order to call and then bind to any of these procedures, we need to include their prototypes in the source member that contains the call to the procedure. So we create a second set of source members that contains only the prototypes for the procedures, and we end up with something like the following:

Member: DATES
Member: STRING
Member: TOOLS
GetDay()
GetDayAsString()
GetEndOfMonth()
ToUpper()
ToLower()
FindReplace()
RtvMbrD()
RunCmd()
RtvFldList()


These source members will be /COPYed into the source member that contains the call to the procedure. For example, if we need to call the GetEndOfMonth() procedure, we need to include the prototype for that procedure. We can physically code the prototype (bad idea!), or we can simply include the DATES source member by using a /COPY or /INCLUDE directive.

Let's use the GetEndOfMonth procedure as an example. Figure 1 shows the source for the GetEndOfMonth procedure:

......Name+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++
0001 P GetEndOfMonth   B                   Export
0002 D GetEndOfMonth   PI              D   DatFmt(*ISO)
0003 D  in_Date                        D   Const DatFmt(*ISO)
      
     ** Local variables begin here
0004 D NextMth         S               D   DatFmt(*ISO)
0005 D nDay            S              5I 0
0006 D EndOfMth        S               D   DatFmt(*ISO)
 
     **  To calculate the end of the month, use the following: 
     **  Next Month = (Date + 1 month) 
     **  End-Of-Month = Next Month - Day of next month
0007 C                   TEST(E)                 in_Date
0008 C                   if        %ERROR
0009 C                   return    D'0001-01-01'
0010 C                   endif
    
.....CSRn01Factor1+++++++OpCode(ex)Factor2+++++++Result++++++++
0011 C     in_Date       AddDur    1:*Months     NextMth
0012 C                   Extrct    NextMth:*Days nDay
0013 C     NextMth       SubDur    nDay:*Days    EndOfMth
0014 C                   return    EndOfMth
0015 P GetEndOfMonth   E

Figure 1: This is the source for the GetEndOfMonth procedure example.

Lines 2 and 3 of the GetEndOfMonth procedure contain the procedure interface (the parameter list) for the procedure. The prototype for this procedure would be as shown in Figure 2:

.....DName+++++++++++EUDS.......Length+TDc.Functions++++++++++++++++
0001 D GetEndOfMonth   PR              D   DatFmt(*ISO)
0002 D  in_Date                        D   Const DatFmt(*ISO)

Figure 2: This is the prototype for the GetEndOfMonth procedure example.

The difference between the procedure interface (lines 2 and 3 of Figure 1) and the prototype (line 1 of Figure 2) is that the letters "PI" appear in the procedure definition in positions 24 and 25 of line 2 in Figure 1, whereas the letters "PR" appear in the prototype in the same positions of line 1 in Figure 2. The letters "PR" indicate that the source is a prototype.

A prototype can be included even if its procedure is not called by the source in which it is included. Essentially, prototypes simply help the compiler syntax check the call to the procedure. If the procedure isn't called, its prototype isn't used, so there's no wasted overhead associated with including procedure prototypes you don't use.

You could simply hard code the prototype in the same source member that the procedure is defined in, but then when you need to call the GetEndOfMonth procedure, you'd have to physically copy the prototype into each source member that needed it, and what fun is that?

Using the /COPY or /INCLUDE statements, however, you can simply store the prototype and other related prototypes in a separate source member and then /COPY it into the source that needs it.

For example, suppose an application needs to read a Customer master file and, using a payment due date, calculate a new due date based on a grace period that extends through the end of the month. Then, a report needs to be printed with the customer number and the revised due date.

Figure 3 shows the source for this example application.

0001 H 
.....FFileName++IFEASFRlen+LKeylnKFDevice+.Functions+++++++++++++++++++
0002 FCustomer  IF   E           K DISK
0003 FQPRINT    O    F  132        PRINTER OFLIND(*INOV)
      
0004  /COPY TOOLSLIB/QRPGLESRC,DATES
     
.....DName+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++
0005 D EndMonth        S               L   DATFMT(*ISO)
     
.....C*Rn01..............OpCode(ex)Extended-factor2++++++++++++++++++++
0006 C                   Read      CustRec
0007 C                   Dow       NOT %EOF
0008 C                   Eval      EndMonth = GetEndOfMonth(DueDate)
0009 C                   Except    Payments
0010 C                   Read      CustRec
0011 C                   enddo
0012 C                   Eval      *INLR = *ON
.....OFormat++++DAddn01n02n03Except++++SpbSpaSkbSka...................
0013 OQPRINT    E            Payments    1
0014 O                                        +   0 'CustNo:'
0015 O                       CustNo        Z  +   1
0016 O                                        +   0 'Due Date:'
0017 O                       EndMonth         +   1

Figure 3: Here's an example of where to use the /COPY statement.

The /COPY statement on line 4 of Figure 3 illustrates the ease of including another source member. That's all there is to it. Nothing else needs to be done. When the compiler processes the /COPY statement, the source in Figure 5 is produced.

0001 H 
.....F*ileName++IFEASFRlen+LKeylnKFDevice+.Functions+++++++++++++++++++
0002 FCustomer  IF   E           K DISK
0003 FQPRINT    O    F  132        PRINTER OFLIND(*INOV)
      
0004  *COPY TOOLSLIB/QRPGLESRC,DATES
    +D GetEndOfMonth   PR              D   DatFmt(*ISO)
    +D  in_Date                        D   Const DatFmt(*ISO)
     
.....D*ame+++++++++++EUDS.......Length+TDc.Functions+++++++++++++++++++
0005 D EndMonth        S               L   DATFMT(*ISO)
     
.....C*Rn01..............OpCode(ex)Extended-factor2++++++++++++++++++++
0006 C                   Read      CustRec
0007 C                   Dow       NOT %EOF
0008 C                   Eval      EndMonth = GetEndOfMonth(DueDate)
0009 C                   Except    Payments
0010 C                   Read      CustRec
0011 C                   enddo
0012 C                   Eval      *INLR = *ON
.....O*ormat++++DAddn01n02n03Except++++SpbSpaSkbSka...................
0013 OQPRINT    E            Payments    1
0014 O                                        +   0 'CustNo:'
0015 O                       CustNo        Z  +   1
0016 O                                        +   0 'Due Date:'
0017 O                       EndMonth         +   1

Figure 5: Here, the /COPY source is expanded.

Note that the prototype (actually, all the source from the included member) is copied into the main source member exactly where the /COPY statement was specified.

Syntax of /COPY and /INCLUDE

The syntax is the same for both /COPY and /INCLUDE, and they can include either regular OS/400 source file members or text files stored in the Integrated File System (IFS). The syntax to include regular OS/400 source members is as follows:

/COPY  {{ library/ } source-file, } member


The library name and source file name are optional, but the member name is required. In addition, the /COPY and /INCLUDE statement must have one and only one space between the directive itself and the member name. Here are a few examples:

/COPY payroll/qrpglesrc,dates
/COPY qrpglesrc,dates
/COPY dates


All three of these /COPY statements are effectively the same. If the library name is not specified, the library list is searched. If the source file name appears in a library name that is high on the library list and it does not contain the member name, the search continues to the next source file on the library list and then the next until the member name is located. The library name (if specified) must be qualified to the source file name, using the forward slash, as in the traditional libname/srcf syntax. If the source file name is not specified, QRPGLESRC is used as the default name, and the library name may not be specified. Any name is valid as long as it is a valid source file object. If the source file name is specified, it is qualified to the member name using a comma, as in the srcf,mbrnam syntax. The member name is always required. The syntax to include source from the IFS is as follows:

/COPY "/cozzi/rpg source/dates.rpg"
/COPY "/cozzi/rpgsrc/dates"
/COPY /cozzi/rpgsrc/dates
/COPY /qsys.lib/payroll.lib/qrpglesrc.file/dates.mbr


When using the IFS file system naming, both the IFS and the so-called QSYS file system can be included. That is, in addition to text files stored on the IFS, regular OS/400 source file members may be included using the IFS naming convention.

The first /COPY includes the text file named DATES.RPG located in the "/cozzi/rpg source" folder of the IFS. Note the embedded blank. When the directory includes an embedded blank, the entire directory and file name must be enclosed in quotes (single or double). When no blanks are embedded, quotes are optional.

The second /COPY statement also includes the dates.rpg file, but it avoids specifying the suffix. If no suffix is specified, the compiler looks for the file without the suffix, and if it does not find it, it looks for the file with a suffix of .rpg. If it cannot find that, it looks for the file with a .rpginc suffix.

The third /COPY statement is the same as the second example, except the quotes are not specified.

The fourth /COPY statement illustrates how the IFS syntax can be used to include regular OS/400 source file members. By starting the IFS directory name with /QSYS.LIB, the so-called "QSYS File system" is searched for the file name.

Start using /COPY or /INCLUDE today! Your code will be happier, and it will create less maintenance issues than you currently have by allowing you to modify prototypes, algorithms, or data variables in one place and then simply recompile.



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: