次の図は、事前初期設定された COBOL 環境の仕組みを示しています。 この例では、C プログラムが COBOL 環境を初期設定し、COBOL プログラムを呼び出した後、COBOL 環境を終了します。

次の例は、COBOL 事前初期設定の使用法を示しています。C メインプログラムは、COBOL プログラム XIO を数回呼び出します。XIO の最初の呼び出しでファイルをオープンし、2 回目の呼び出しでレコードを 1 つ書き込みます (以下同様)。そして最後の呼び出しで、ファイルをクローズします。この後、C プログラムは C ストリーム I/O を使用して、このファイルをオープンし、読み取ります。
このプログラムをテストおよび実行するには、コマンド・ウィンドウから次のコマンドを入力します。
cob2 -c xio.cbl
cl testinit.c xio.obj
testinit
結果は次のとおりです。
_iwzCOBOLinit got 0 xio entered with x=0000000000 xio entered with x=0000000001 xio entered with x=0000000002 xio entered with x=0000000003 xio entered with x=0000000004 xio entered with x=0000000099 StopArg=0 _iwzCOBOLTerm expects rc=0 and got rc=0 FILE1 contains ---- 11111 22222 33333 ---- end of FILE1
この例では、実行単位が COBOL の STOP RUN で終了するのではなく、メインプログラムが _iwzCOBOLTerm を呼び出したときに終了している点に注意してください。
次の C プログラムは、ファイル testinit.c に入っています。
#ifdef _AIX
typedef int (*PFN)();
#define LINKAGE
#else
#include <windows.h>
#define LINKAGE _System
#endif
#include <stdio.h>
#include <setjmp.h>
extern void _iwzCOBOLInit(int fcode, PFN StopFun, int *err_code, void *StopArg);
extern void _iwzCOBOLTerm(int fcode, int *err_code);
extern void LINKAGE XIO(long *k);
jmp_buf Jmpbuf;
long StopArg = 0;
int LINKAGE
StopFun(long *stoparg)
{
printf(“inside StopFun\n”);
*stoparg = 123;
longjmp(Jmpbuf,1);
}
main()
{
int rc;
long k;
FILE *s;
int c;
if (setjmp(Jmpbuf) ==0) {
_iwzCOBOLInit(1, StopFun, &rc, &StopArg);
printf( “_iwzCOBOLinit got %d\n”,rc);
for (k=0; k <= 4; k++) XIO(&k);
k = 99; XIO(&k);
}
else printf(“return after STOP RUN\n”);
printf(“StopArg=%d\n”, StopArg);
_iwzCOBOLTerm(1, &rc);
printf(“_iwzCOBOLTerm expects rc=0 and got rc=%d\n”,rc);
printf(“FILE1 contains ---- \n”);
s = fopen(“FILE1”, “r”);
if (s) {
while ( (c = fgetc(s) ) != EOF ) putchar(c);
}
printf(“---- end of FILE1\n”);
}
次の COBOL プログラムは、ファイル xio.cbl に入っています。
IDENTIFICATION DIVISION.
PROGRAM-ID. xio.
******************************************************************
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT file1 ASSIGN TO FILE1
ORGANIZATION IS LINE SEQUENTIAL
FILE STATUS IS file1-status.
. . .
DATA DIVISION.
FILE SECTION.
FD FILE1.
01 file1-id pic x(5).
. . .
WORKING-STORAGE SECTION.
01 file1-status pic xx value is zero.
. . .
LINKAGE SECTION.
*
01 x PIC S9(8) COMP-5.
. . .
PROCEDURE DIVISION using x.
. . .
display “xio entered with x=” x
if x = 0 then
OPEN output FILE1
end-if
if x = 1 then
MOVE ALL “1” to file1-id
WRITE file1-id
end-if
if x = 2 then
MOVE ALL “2” to file1-id
WRITE file1-id
end-if
if x = 3 then
MOVE ALL “3” to file1-id
WRITE file1-id
end-if
if x = 99 then
CLOSE file1
end-if
GOBACK.