IBM R.P.G. Programming – Source /COPY RPG Copybooks

IBM i

Oct 10

What are RPG COPYBOOKS anyway?

Copybooks are a very simple way of reproducing the same code into many programs: a copybook is a source member containing a section of code that can be inserted/copied into any other source member at compilation time. The main idea behind RPG Copybooks is re-usability.

Think of a copybook as a source member that contains a common re-usable code component that that you dont want to compile but want to include in the actual programs that use it at compile time.

Copybooks were frequently used back in the day as a fast alternative to having a common program that every other program called. A classic example may be definition for a system wide *LDA structure. Just think, all your programs in a given application will be defining certain parts of the *LDA, or program status data structure, or *PSSR routine or just about anything – all with the same field names, in every program written within that application.

COPYBOOKS make it simple to write a bit of code in a source member and then have all the other programs referencing it and sucking in that code at compile time.

For example – Here is a copybook of a PSDS

0001.00  * sample copysrc member called QGPL/COPY(PSDS) - program status data structure 
0002.00 D SDS 
0003.00 DSx4PROG 1 10 Program Name 
0004.00 DSx4STAT  11 15 status code 
0005.00 DSx4SEQ#  21 28 rpg stat number 
0006.00 DSx4RTN 29 36 rpg routine 
0007.00 DSx4PARM  37 39 number of params 
0008.00 DSx4CERR  40 46 cpf/mch error cod 
0009.00 DSx4PLIB  81 90 program library 

So this little code snippet is defining some areas of the program status data structure which could in turn be used by every other program on the system. Rather than reproduce this code everywhere it’s simply coded into its own unique source member (generally called something like COPYBOOK for no other reason that to differentiate it from the normal QRPGSRC, QRPGLESRC, etc.. etc..) and can then be referenced from any RPG program on the system by inserting a line in the code that looks like this:

0094.00 *  Fetch external description of PSDS
0095.00 /COPY QGPL/COPY,PSDS
0098.00 * --------------------------------------------------- 

Simple huh?

When the program is compiled the compiler will suck the copybook source code into that point in the program and compile it as if you had typed it in yourself.

If you make a change to your copybook – you simply recompile all programs using it to update them.

Follow

About the Author

IBM i Software Developer, Digital Dad, AS400 Anarchist, RPG Modernizer, Alpha Nerd and Passionate Eater of Cheese and Biscuits. Nick Litten Dot Com is a mixture of blog posts that can be sometimes serious, frequently playful and probably down-right pointless all in the space of a day. Enjoy your stay, feel free to comment and in the words of the most interesting man in the world: Stay thirsty my friend.