Example: COBOL program calling C++ function

The following example shows a COBOL program that calls a C++ function by using a CALL statement that passes arguments BY REFERENCE.

The example illustrates the following concepts:
  • The CALL statement does not indicate whether the called program is written in COBOL or C++.
  • You must declare a function return value on a CALL statement that calls a non-void C++ function.
  • The COBOL data types must be mapped to appropriate C++ data types.
  • The C++ function must be declared extern "C".
  • The COBOL arguments are passed BY REFERENCE. The C++ function receives them by using reference parameters.

COBOL program driver:

cbl pgmname(mixed)
Identification Division.
Program-Id. "driver".
Data division.
Working-storage section.
01 A pic 9(8) binary value 11111.
01 B pic 9(8) binary value 22222.
01 R pic 9(8) binary.
Procedure Division.
    Display "Hello World, from COBOL!"
    Call "sub" using by reference A B
      returning R
    Display R
    Stop Run.

C++ function sub:

#include <iostream.h>
extern "C" long sub(long& A, long& B) {
  cout << "Hello from C++" << endl;
  return A + B;
}

Output:

Hello World, from COBOL!
Hello from C++
00033333

related references  
CALL statement (COBOL for AIX Language Reference)