Example: COBOL program calling C functions
The following example shows a COBOL program that calls
C functions by using the CALL
statement.
The example illustrates the following concepts:
- The
CALL
statement does not indicate whether the called program is written in COBOL or C. - COBOL supports calling programs that have mixed-case names.
- You can pass
arguments to C programs in various ways (for example,
BY REFERENCE
orBY VALUE
). - You must
declare a function return value on a
CALL
statement that calls a non-void C function. - You must map COBOL data types to appropriate C data types.
CBL PGMNAME(MIXED)
* This compiler option allows for case-sensitive names for called programs.
*
IDENTIFICATION DIVISION.
PROGRAM-ID. "COBCALLC".
*
DATA DIVISION.
WORKING-STORAGE SECTION.
01 N4 PIC 9(4) COMP-5.
01 NS4 PIC S9(4) COMP-5.
01 N9 PIC 9(9) COMP-5.
01 NS9 PIC S9(9) COMP-5.
01 NS18 USAGE COMP-2.
01 D1 USAGE COMP-2.
01 D2 USAGE COMP-2.
01 R1.
02 NR1 PIC 9(8) COMP-5.
02 NR2 PIC 9(8) COMP-5.
02 NR3 PIC 9(8) COMP-5.
PROCEDURE DIVISION.
MOVE 123 TO N4
MOVE -567 TO NS4
MOVE 98765432 TO N9
MOVE -13579456 TO NS9
MOVE 222.22 TO NS18
DISPLAY "Call MyFun with n4=" N4 " ns4=" NS4 " N9=" n9
DISPLAY " ns9=" NS9" ns18=" NS18
* The following CALL illustrates several ways to pass arguments.
*
CALL "MyFun" USING N4 BY VALUE NS4 BY REFERENCE N9 NS9 NS18
MOVE 1024 TO N4
* The following CALL returns the C function return value.
*
CALL "MyFunR" USING BY VALUE N4 RETURNING NS9
DISPLAY "n4=" N4 " and ns9= n4 times n4= " NS9
MOVE -357925680.25 TO D1
CALL "MyFunD" USING BY VALUE D1 RETURNING D2
DISPLAY "d1=" D1 " and d2= 2.0 times d2= " D2
MOVE 11111 TO NR1
MOVE 22222 TO NR2
MOVE 33333 TO NR3
CALL "MyFunV" USING R1
STOP RUN.