Calling C functions

Linking C and COBOL

GnuCOBOL links with C objects directly. Write a small C function, compile it with gcc, and link it with the COBOL program in one step. This is helper.c:

int add_tax(int amount, int rate_percent) { return amount + amount * rate_percent / 100; }

gcc -c helper.c -o helper.o

The CALL sentence

CALL names the C function, USING lists the arguments in order, and RETURNING takes the value. C int arguments map to PIC S9(9) USAGE COMP-5 fields, and BY VALUE passes the number itself rather than a pointer. This is main.cob:

IDENTIFICATION DIVISION. PROGRAM-ID. MAIN. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-AMOUNT PIC S9(9) USAGE COMP-5 VALUE 200. 01 WS-RATE PIC S9(4) USAGE COMP-5 VALUE 13. 01 WS-RESULT PIC S9(9) USAGE COMP-5. PROCEDURE DIVISION. CALL "add_tax" USING BY VALUE WS-AMOUNT WS-RATE RETURNING WS-RESULT. DISPLAY "With tax: " WS-RESULT. STOP RUN.

cobc -x -free -o main main.cob helper.o

./main

With tax: +0000000226

Return values

Keep the C side simple for COBOL callers: pass everything through the USING list, keep one return value, and document whether each argument is BY VALUE or BY REFERENCE in the copybook header. A C pointer maps to a BY REFERENCE item, so the C function can fill a COBOL record in place.

The code on this page was run with GnuCOBOL 3.2.0 and gcc 15.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev