COBOLMainframe

COBOL Copybooks: COPY, REPLACING, and Shared Data Definitions

TT
TopicTrick
COBOL Copybooks: COPY, REPLACING, and Shared Data Definitions

Copybooks are COBOL's mechanism for code reuse. Rather than redefining the same customer record layout in 50 programs, you define it once in a copybook and COPY it wherever needed. Changes to the layout require recompiling programs that include the copybook, but the definition itself lives in one place. On large z/OS mainframe systems with thousands of programs, copybook discipline is the difference between maintainable code and an unmaintainable mess.

The COPY Statement

COPY includes a copybook member into the program's source at the point where the COPY statement appears:

cobol
DATA DIVISION.
WORKING-STORAGE SECTION.

    COPY CUSTMAST.

    COPY SQLCA.

    COPY DFHAID.

The compiler replaces each COPY statement with the full text of the named member from the SYSLIB DD library. The compiled program sees a single, expanded source as if you had typed everything in manually.

COPY can appear in any division and any section. Common locations:

  • DATA DIVISION — record layouts, SQL host variables, condition code tables
  • PROCEDURE DIVISION — common error handling routines, initialization paragraphs
  • WORKING-STORAGE SECTION — flags, constants, date work areas

Copybook Source Format

A copybook looks like a partial COBOL program — it has no IDENTIFICATION DIVISION header, it just contains whatever code it contributes:

CUSTMAST.cpy:

cobol
      *=============================================================*
      * CUSTOMER MASTER RECORD LAYOUT                               *
      * DATASET: PROD.CUSTOMER.VSAM.KSDS                           *
      * RECORD LENGTH: 200 BYTES                                    *
      * UPDATED: 2026-01-20                                         *
      *=============================================================*
       01 CUSTOMER-MASTER-RECORD.
          05 CMR-CUSTOMER-ID      PIC X(10).
          05 CMR-LAST-NAME        PIC X(25).
          05 CMR-FIRST-NAME       PIC X(15).
          05 CMR-MIDDLE-INITIAL   PIC X(1).
          05 CMR-DATE-OF-BIRTH    PIC 9(8).
          05 CMR-SSN              PIC X(11).
          05 CMR-ACCOUNT-INFO.
             10 CMR-ACCOUNT-ID   PIC X(10).
             10 CMR-OPEN-DATE    PIC 9(8).
             10 CMR-STATUS       PIC X(2).
                88 CMR-ACTIVE             VALUE 'AC'.
                88 CMR-CLOSED             VALUE 'CL'.
                88 CMR-SUSPENDED          VALUE 'SU'.
          05 CMR-BALANCE          PIC S9(11)V99 COMP-3.
          05 CMR-CREDIT-LIMIT     PIC S9(9)V99 COMP-3.
          05 FILLER               PIC X(81).

The indentation starts in column 7 (Area A/B alignment). Copybooks must follow the same column rules as the programs that include them unless the FORMAT FREE option is used.

COPY REPLACING

REPLACING performs text substitution during the COPY — every occurrence of the search text is replaced with the replacement text:

cobol
COPY CUSTMAST REPLACING ==CMR== BY ==INPUT-CMR==.
COPY CUSTMAST REPLACING ==CMR== BY ==OUTPUT-CMR==.

This includes the same copybook twice with different field name prefixes. The first inclusion creates fields like INPUT-CMR-CUSTOMER-ID, INPUT-CMR-BALANCE, etc. The second creates OUTPUT-CMR-CUSTOMER-ID, OUTPUT-CMR-BALANCE, etc.

Pseudo-text Delimiters

The == delimiters mark the boundary of the replacement text. This syntax allows replacement of any string, including partial words, reserved words, or multi-word phrases:

cobol
*> Replace a prefix placeholder:
COPY TRANRECORD REPLACING ==:TRN:== BY ==PAYMENT==.

*> Replace a level number:
COPY FIELDGROUP REPLACING ==05== BY ==10==.

*> Replace multiple strings:
COPY BASERECORD
    REPLACING ==:DATE-FIELD:== BY ==WS-PROCESS-DATE==
              ==:AMOUNT-FIELD:== BY ==WS-TRANSACTION-AMT==
              ==:STATUS-FIELD:== BY ==WS-PROC-STATUS==.

Parameterized Copybook Pattern

Large shops use placeholder tokens (often enclosed in colons) for parameterized copybooks:

ACCREC.cpy:

cobol
       01 :PREFIX:-ACCOUNT-RECORD.
          05 :PREFIX:-ACCOUNT-ID   PIC X(10).
          05 :PREFIX:-BALANCE      PIC S9(11)V99 COMP-3.
          05 :PREFIX:-STATUS       PIC X(2).
             88 :PREFIX:-ACTIVE           VALUE 'AC'.
             88 :PREFIX:-CLOSED           VALUE 'CL'.

Usage in a program that needs both input and output account records:

cobol
WORKING-STORAGE SECTION.
    COPY ACCREC REPLACING ==:PREFIX:== BY ==INPUT==.
    COPY ACCREC REPLACING ==:PREFIX:== BY ==OUTPUT==.

This generates INPUT-ACCOUNT-RECORD with INPUT-ACCOUNT-ID, INPUT-BALANCE, etc., and separately OUTPUT-ACCOUNT-RECORD with its own fields — all from one copybook.

Essential IBM-Supplied Copybooks

SQLCA — SQL Communication Area

Every program using embedded SQL must include SQLCA:

cobol
WORKING-STORAGE SECTION.
    EXEC SQL INCLUDE SQLCA END-EXEC.

The preprocessor expands this to include the SQLCA copybook, which provides:

  • SQLCODE — 0 success, +100 not found, negative = error
  • SQLERRM — error message text (variable-length)
  • SQLERRD — array of 6 integers with diagnostic info
  • SQLWARN — warning flags array
cobol
*> After every SQL statement:
EVALUATE TRUE
    WHEN SQLCODE = 0
        PERFORM PROCESS-SUCCESS
    WHEN SQLCODE = 100
        SET WS-NOT-FOUND TO TRUE
    WHEN OTHER
        MOVE SQLCODE TO WS-SQLCODE-DISPLAY
        PERFORM LOG-SQL-ERROR
END-EVALUATE.

DFHAID — CICS Attention Identifier Values

CICS programs need DFHAID to test which key the terminal user pressed:

cobol
WORKING-STORAGE SECTION.
    COPY DFHAID.

DFHAID defines constants for every AID (attention identifier) key:

cobol
*> Some values from DFHAID:
*> DFHENTER  PIC X VALUE X'7D'   (ENTER key)
*> DFHPF1    PIC X VALUE X'F1'   (PF1)
*> DFHPF2    PIC X VALUE X'F2'   (PF2)
*> DFHPF3    PIC X VALUE X'F3'   (PF3)
*> DFHPF12   PIC X VALUE X'FC'   (PF12)
*> DFHCLEAR  PIC X VALUE X'6D'   (CLEAR)
*> DFHPA1    PIC X VALUE X'6C'   (PA1)

Usage in CICS program logic:

cobol
EVALUATE EIBAID
    WHEN DFHENTER
        PERFORM PROCESS-ENTER-KEY
    WHEN DFHPF3
        PERFORM EXIT-PROGRAM-LOGIC
    WHEN DFHPF12
        PERFORM CANCEL-TRANSACTION
    WHEN DFHCLEAR
        PERFORM CLEAR-SCREEN-FIELDS
    WHEN OTHER
        PERFORM DISPLAY-INVALID-KEY-MSG
END-EVALUATE.

DFHBMSCA — BMS Color and Attribute Constants

For CICS BMS map programs:

cobol
COPY DFHBMSCA.

*> Set field attribute to protected, bright:
MOVE DFHBMPRO TO MAP-ACCOUNT-ID-A.

*> Set field to unprotected, dark (password):
MOVE DFHBMDAR TO MAP-PASSWORD-A.

*> Set field color to red for error:
MOVE DFHRED TO MAP-ERROR-MSG-A.

DCLGEN Output — DB2 Table Declarations

DCLGEN generates a copybook from a DB2 table:

cobol
*> Generated by DCLGEN from DB2 table ACCOUNT:
      * DCLGEN TABLE(PRODDB.ACCOUNT)
      * LIBRARY(PROD.COPYLIB(DCLACCT))
       EXEC SQL DECLARE PRODDB.ACCOUNT TABLE
         ( ACCOUNT_ID    CHAR(10)          NOT NULL,
           CUSTOMER_ID   CHAR(10)          NOT NULL,
           BALANCE       DECIMAL(13,2)     NOT NULL,
           STATUS_CD     CHAR(2)           NOT NULL,
           OPEN_DATE     DATE              NOT NULL
         ) END-EXEC.

       01 DCLACCOUNT.
          10 ACCOUNT-ID    PIC X(10).
          10 CUSTOMER-ID   PIC X(10).
          10 BALANCE       PIC S9(11)V99 COMP-3.
          10 STATUS-CD     PIC X(2).
          10 OPEN-DATE     PIC X(10).

Always use DCLGEN output rather than manually writing host variable definitions — it guarantees alignment with the actual table schema.

Copybook Library Organization

A well-organized z/OS shop maintains multiple copy libraries by category:

LibraryContents
PROD.COPYLIB.RECORDSBusiness record layouts (CUSTMAST, ACCTRECORD, TRANSREC)
PROD.COPYLIB.DB2DCLGEN output and SQLCA
PROD.COPYLIB.CICSDFHAID, DFHBMSCA, commarea layouts
PROD.COPYLIB.COMMONShared constants, date fields, error handling paragraphs
PROD.COPYLIB.VENDORThird-party and IBM-supplied copybooks

The compilation JCL SYSLIB DD concatenates these libraries:

jcl
//SYSLIB   DD DSN=PROD.COPYLIB.RECORDS,DISP=SHR
//         DD DSN=PROD.COPYLIB.DB2,DISP=SHR
//         DD DSN=PROD.COPYLIB.CICS,DISP=SHR
//         DD DSN=PROD.COPYLIB.COMMON,DISP=SHR
//         DD DSN=SYS1.MACLIB,DISP=SHR

When the compiler encounters COPY CUSTMAST, it searches each library in order until it finds a member named CUSTMAST.

Version Control for Copybooks

When a copybook changes, every program that includes it must be recompiled. This is the central management challenge of copybook-based sharing. Standard practices:

Impact analysis before change: Use grep or a source management tool (Endevor, CA-LIBRARIAN) to find all programs that COPY the changed member before modifying it.

Backward compatibility: Add new fields at the end of existing records. Never change the position or length of existing fields — doing so creates binary incompatibility with any compiled program not yet recompiled.

Version suffix: For breaking changes, create a new copybook member (CUSTMASV2) rather than modifying the original. Migrate programs incrementally.

COPY level tracking: Some shops include a copybook version constant in the copybook itself:

cobol
       05 FILLER PIC X(8) VALUE 'CSTMSTV3'.   *> copybook version

This appears in memory dumps and can be checked at runtime.

Common Copybook Patterns

Shared Error Handling Paragraphs

cobol
      *=============================================================*
      * ERRHNDLR.cpy — Standard error handling routine              *
      *=============================================================*
       STANDARD-ERROR-HANDLER.
           MOVE WS-RETURN-CODE TO WS-DISPLAY-CODE
           STRING 'PROGRAM ' DELIMITED BY SIZE
                  WS-PROGRAM-ID DELIMITED BY SPACE
                  ' ERROR CODE: ' DELIMITED BY SIZE
                  WS-DISPLAY-CODE DELIMITED BY SIZE
                  INTO WS-ERROR-MESSAGE
           END-STRING
           PERFORM WRITE-ERROR-LOG
           IF WS-FATAL-ERROR
               PERFORM ABEND-CLEANUP
               STOP RUN
           END-IF.

Include in PROCEDURE DIVISION:

cobol
PROCEDURE DIVISION.
    COPY ERRHNDLR.

Next Steps

Copybooks complete the modular programming toolkit. The next topic is JCL — the Job Control Language that compiles, links, and runs COBOL programs on z/OS. See COBOL JCL: Compile, Link, and Run, or return to the COBOL Mastery course.