GnuCOBOL Functions

I am adding this post to provide some insights into the coding structures required for defining and calling custom functions with GnuCOBOL.


000001 IDENTIFICATION DIVISION.
000002 PROGRAM-ID. TEST.
000003* Purpose of this program is demonstrate the use of functions by
000004* defining a simple function to increment a number.
000005 ENVIRONMENT DIVISION.
000006 CONFIGURATION SECTION.
000007 REPOSITORY.
000008 FUNCTION INCREMENT AS "FUNCTION-INCREMENT"
000009 FUNCTION ALL INTRINSIC.
000010 DATA DIVISION.
000011 WORKING-STORAGE SECTION.
000012 77 WS-Test-Data PIC 99.
000013 PROCEDURE DIVISION.
000014 A000-Main SECTION.
000015 MOVE 1 TO WS-Test-Data
000016 DISPLAY "PARAMETER EQUALS " WS-Test-Data
000017 DISPLAY "INCREMENTED BY 1 " INCREMENT(WS-Test-Data)
000018 STOP RUN.
000019 END PROGRAM TEST.
000020*
000021 IDENTIFICATION DIVISION.
000022 FUNCTION-ID. FUNCTION-INCREMENT.
000023* The increment function increments the passed parameter.
000024 DATA DIVISION.
000025* The linkage section receives a parameter for incrementing to a
000026* returned value.
000027 LINKAGE SECTION.
000028 77 LK-Parameter PIC 99.
000029 77 LK-Return-Value PIC 99.
000030 PROCEDURE DIVISION USING LK-Parameter RETURNING LK-Return-Value.
000031* Increment and return the passed parameter.
000032 A000-Main SECTION.
000033 ADD 1 TO LK-Parameter GIVING LK-Return-Value
000034 GOBACK.
000035 END FUNCTION FUNCTION-INCREMENT.

The INCREMENT function is defined in the main TEST program within a repository in the CONFIGURATION SECTION (line 8) using an alias from the AS keyword of “FUNCTION-INCREMENT” which matches the FUNCTION-ID (line 22). I have found that this line is crucial to avoid issues with the function not being found at runtime.

As functions are defined as intrinsic (line 9), the keyword FUNCTION can be omitted when calling a function. The INCREMENT function is called using a parameter of WS-Test-Data on line 17 with the statement INCREMENT(WS-Test-Data).

The function itself is defined from lines 21 onward with its LINKAGE section containing the passed parameter and returned value.

To compile and execute this test code, use the following;

$ cobc -x ./Test.cbl
$ ./Test
PARAMETER EQUALS 01
INCREMENTED BY 1 02

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s