Copybooks: COPY & REPLACE

A copybook is a source fragment included at compile time — the standard way to share record layouts, constants, and common paragraphs.

27.1 COPY

A copybook is a source fragment included at compile time — the standard way to share record layouts, constants, and common paragraphs.

On z/OS, copybooks are members of a PDS concatenated under the SYSLIB DD of the compile step; COPY CUSTREC OF CPYLIB (or IN) selects a library.

* CUSTREC - customer master record layout (100 bytes)
       01  CUSTOMER-RECORD.
           05  CUST-ID              PIC 9(6).
           05  CUST-NAME            PIC X(30).
           05  CUST-CITY            PIC X(20).
           05  CUST-BALANCE         PIC S9(9)V99 COMP-3.
           05  CUST-STATUS          PIC X.
               88  CUST-ACTIVE      VALUE "A".
               88  CUST-CLOSED      VALUE "C".
           05  FILLER               PIC X(37).
FILE SECTION.
       FD  CUST-FILE.
           COPY CUSTREC.
       ...
       WORKING-STORAGE SECTION.
           COPY ERRCODES.
cobc -x -I ./copybooks prog.cob        # search path for copybooks
export COB_COPY_DIR=./copybooks        # alternative

27.2 COPY ... REPLACING

Pseudo-text delimited by == lets you reuse one layout with different prefixes:

This creates BILL-STREET, SHIP-STREET, and so on. You can also replace whole words: REPLACING LEADING ==CUST== BY ==OLD== or REPLACING CUST-ID BY OLD-ID.

05  :PFX:-STREET         PIC X(30).
           05  :PFX:-CITY           PIC X(20).
           05  :PFX:-ZIP            PIC X(10).
01  BILLING-ADDRESS.
           COPY ADDRESS REPLACING ==:PFX:== BY ==BILL==.
       01  SHIPPING-ADDRESS.
           COPY ADDRESS REPLACING ==:PFX:== BY ==SHIP==.

27.3 REPLACE

REPLACE applies text substitution to the following source (until REPLACE OFF. or another REPLACE):

REPLACE ==:MAX-ITEMS:== BY ==500==.
       01  WS-ITEMS   PIC X(10) OCCURS :MAX-ITEMS: TIMES.
       REPLACE OFF.

27.4 Copybook guidelines

One copybook per record layout; the copybook name matches the record or file.

Never edit a shared copybook without recompiling every program that uses it (impact analysis tools and build systems like IBM DBB track these dependencies).

Keep copybooks free of PROCEDURE DIVISION logic unless it is a deliberate shared routine (e.g., standard error handling paragraphs). Include a header comment with length, owner, and change history.