Copybooks and COPY
The COPY statement
COPY inserts the text of another file at compile time, like include in C. Copybooks usually hold shared data layouts so every program sees the same record. This is EMPLOYEE-REC.cpy:
01 EMPLOYEE-REC.
05 EMP-NAME PIC X(30).
05 EMP-SALARY PIC 9(7)V99.
The program then pulls the record in with COPY:
DATA DIVISION.
WORKING-STORAGE SECTION.
COPY EMPLOYEE-REC.
REPLACING
REPLACING renames whole words as the copybook is included, so one copybook can serve several records: here every EMP- name becomes a CUST- name, and the group gets a new name too:
COPY EMPLOYEE-REC REPLACING
==EMPLOYEE-REC== BY ==CUSTOMER-REC==
==EMP-NAME== BY ==CUST-NAME==
==EMP-SALARY== BY ==CUST-SALARY==.
Copybook hygiene
Keep copybooks small and free of procedure code: data layouts only, with a clear prefix on every field name. A copybook that changes one program should be recompiled into all of its users before the next release.
The code on this page was run with GnuCOBOL 3.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev