COBOL by Example: Copybooks
Reusing code across programs with COPY statement, including external copybook files during compilation, maintaining consistent data structures, and managing shared record layouts centrally.
Code
IDENTIFICATION DIVISION.
PROGRAM-ID. COPY-DEMO.
DATA DIVISION.
WORKING-STORAGE SECTION.
*> This line pulls in code from an external file
COPY 'CUSTOMER-REC.CPY'.
PROCEDURE DIVISION.
MOVE 1001 TO CUST-ID.
MOVE "Acme Corp" TO CUST-NAME.
DISPLAY "Customer: " CUST-NAME.
STOP RUN.Explanation
One of COBOL's earliest forms of modularity is the Copybook. A copybook is a separate file containing a chunk of code—usually Data Division definitions—that can be included in multiple programs. This ensures that if a record layout changes, you only need to update one file and recompile all programs that use it.
The COPY statement acts like a preprocessor directive (similar to #include in C). During compilation, the compiler replaces the COPY line with the actual contents of the referenced file. This happens before the code is actually compiled into machine language.
Copybooks are not limited to variable definitions; they can also contain Procedure Division code, although this is less common. They are the standard way to enforce consistency across an organization's codebase, ensuring everyone uses the same field names and data types for shared data structures.

