COBOL copy books

Edouard Tavinor
2 min readMar 6, 2022

Hi everybody!

Here’s a short post about copy books in COBOL and why you may want to use them.

Here’s the important stuff:

this is big_program.cob

identification division.
program-id. big_program.
environment division.
data division.
working-storage section.
copy 'person_dd.cob' replacing ==:block:== by alice.
copy 'person_dd.cob' replacing ==:block:== by bob.
procedure division.100-start.
move 32 to age in alice
move 'alice' to name in alice
move 27 to age in bob
move 'bob' to name in bob
perform display-alice
perform display-bob
goback.copy 'person_pd.cob' replacing ==:block:== by alice.
copy 'person_pd.cob' replacing ==:block:== by bob.

and here you can see person_dd.cob`

01 :block:.
05 age PIC 9(3).
05 name PIC X(10).

and then there’s person_pd.cob`

display-:block:.
display 'name ' name in :block:
display 'age ' age in :block:
.

running the whole thing:

$ cobc -x big_program.cob && ./big_program
name alice
age 032
name bob
age 027

Please note that I’ve only tried this using gnu-cobol. It’s possible that other cobol implementations will complain.

Now comes the question as to why you would want to do this.

Consider what the program would look like without copy books:

$ cobc -E big_program.cob -o big_program.p && cat big_program.p
#line 1 "big_program.cob"
identification division.
program-id. big_program.
environment division.
data division.
working-storage section.

#line 1 "person_dd.cob"
01 alice.
05 age PIC 9(3).
05 name PIC X(10).
#line 6 "big_program.cob"
#line 1 "person_dd.cob"
01 bob.
05 age PIC 9(3).
05 name PIC X(10).
#line 7 "big_program.cob"
procedure division.
100-start.
move 32 to age in alice
move 'alice' to name in alice
move 27 to age in bob
move 'bob' to name in bob
perform display-alice
perform display-bob
goback.
#line 1 "person_pd.cob"
display-alice.
display 'name ' name in alice
display 'age ' age in alice
.
#line 18 "big_program.cob"
#line 1 "person_pd.cob"
display-bob.
display 'name ' name in bob
display 'age ' age in bob
.
#line 19 "big_program.cob"

Here we are repeating code in the source file. Similar procedures and structures are defined twice. By exporting the code to a copy book we need only maintain one copy of it :) With some clever usage of names you might even be able to get close to object-oriented programming :) You just need one file for each division you want to put the extracted code in (a file for the environment division, for the data division and the procedure division).

Notes

The copy ... replacing statement in Cobol has a special way of specifying quotes: ==word== . However, if the word in the copy book is surrounded by parenthesis this won’t work (important for array indeces for example). To get around this problem, you can surround the word with colons in the copy book and the main program. I do this in the example above.

--

--