I've been playing with OpenCOBOL today. In particular, I wanted to figure out two things: 1) how to access environment variables, and 2) how to call an external C function and pass parameters. Here is an example. First, the COBOL code (Updated 2019/07/20, to work with GNU Cobol 1.1.0):
IDENTIFICATION DIVISION.
PROGRAM-ID. CALLENV.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 ENVVAR.
05 PIC X(1024).
05 PIC X X"00".
01 RETVAL PIC 9(9).
01 RETVALZ PIC Z(08)9.
01 TIMESVAL USAGE BINARY-LONG VALUE 111.
PROCEDURE DIVISION.
ACCEPT ENVVAR FROM ENVIRONMENT "COBENV".
CALL "print" USING ENVVAR, BY VALUE TIMESVAL RETURNING RETVAL.
MOVE RETVAL TO RETVALZ.
DISPLAY 'Return value is ' FUNCTION TRIM(RETVALZ,LEADING) '.'.
STOP RUN RETURNING 0.
Next, the external C function:
#include <stdio.h>
#include <string.h>
extern int print(char *what, int times)
{
while (strlen(what) > 0 && what[strlen(what) - 1] == ' ')
what[strlen(what) - 1] = 0;
printf("%s, %d times.\n", what, times);
return 123;
}
The two can be compiled and linked together (and tested) as in the following make file:
callenv: callenv.cob cobprint.c
cc -c cobprint.c
cobc -x -o callenv callenv.cob cobprint.o
rm cobprint.o
COBENV="THIS IS A TEST" callenv
I am impressed by OpenCOBOL 1.0. Version 1.1 will be even nicer, I expect.
Incidentally, OpenCOBOL also has an awesome reference manual.
