Compile

This chapter describes how to compile COBOL programs using GnuCOBOL.

Compiler options

The compiler cobc accepts the options described in this section. The compiler arguments follow the general syntax cobc <options> <file> [<file> ...]. A complete list of options can be displayed by using the option --help.

Help options

The following switches display information about the compiler:

  • --help, -h

    Display help screen ( Appendix A). No further actions will be taken.

  • --version, -V

    Display compiler version, author package date and executable build date. No further actions will be taken.

  • -dumpversion

    Display internal compiler version (plain string of numbers). No further actions will be taken.

  • --info

    Display build information along with the default and current compiler configurations. No further actions will be taken except for further display options.

  • --verbose, -v

    Verbosely display the programs invoked during compilation and additional diagnostics. Use multiple times to increase the verbosity.

  • --list-reserved

    Display reserved words ( Appendix B). A Yes/No output shows if the word is supported 1 , context sensitive and its aliases. The given options for reserved words specified for example by option -std=<dialect> will be taken into account. No further actions will be taken except for further display options.

  • --list-intrinsics

    Display intrinsic functions ( Appendix C). A Y/N field shows if the function is implemented. No further actions will be taken except for further display options.

  • --list-system

    Display system routines ( Appendix D). No further actions will be taken except for further display options.

  • --list-mnemonics

    Display mnemonic names ( Appendix E). No further actions will be taken except for further display options.

  • --list-exceptions

    Display exception names ( Appendix F). No further actions will be taken except for further display options.

Build target

The compiler cobc treats files like *.cob, *.cbl as COBOL source code, *.c as C source code, *.o as object code, *.i as preprocessed code and *.so as dynamic modules and knows how to handle such files in the generation, compilation, and linking steps.

The special input name - takes input from stdin which is assumed to be COBOL source, and uses a default output name of a.out (or a.so/c/o/i, selected as appropriate) for the build type.

You may also use - as output name for the listing file or the preprocessor result, for example with cobc -t - prog.cob / cobc -P- prog.cob.

By default, the compiler builds a dynamically loadable module.

The following options specify the target type produced by the compiler:

  • -E

    Preprocess only: compiler directives are executed, comment lines are removed and COPY statements are expanded. The output is sent to stdout, allowing you to directly use it as input for another process. You can manually set an output file using -o.

  • -C

    Translation only. COBOL source files are translated into C files. The output is saved in file *.c.

  • --save-temps

    Normal compilation with additional storing the preprocessed files as *.i and the translated C files as file *.c.

  • -S

    Compile only. Translated C files are compiled by the C compiler to assembler code. The output is saved in file *.s.

  • -c

    Compile and assemble. This is equivalent to cc -c. The output is saved in file *.o.

  • -m

    Compile, assemble, and build a dynamically loadable module (i.e., a shared library). The output is saved in file *.so. 2 This is the default behaviour.

  • -b

    Compile, assemble, and combine all input files into a single dynamically loadable module. Unless -o is also used, the output is saved using the first filename as *.so.

  • -x

    Include the main function in the output, creating an executable image. The main entry point being the first program in the file.

    This option takes effect at the translation stage. If you give this option with -C, you will see the main function at the end of the generated C file.

  • -j, -job, -j=<args>, -job=<args>

    Run job after compilation. Either from executable with -x, or with cobcrun when compiling a module. Optional arguments <args>, if given, are passed to the program or module command line.

  • -I <directory>

    Add <directory> to copy/include search path.

  • -L <directory>

    Add <directory> to library search path.

  • -l <lib>

    Link the library <lib>.

  • -D <define>

    Pass <define> to the COBOL compiler.

  • -o <file>

    Place the output into <file>.

Source format

GnuCOBOL supports fixed, free, Micro Focus’ Variable, X/Open Free-form, ICOBOL xCard and Free-form, ACUCOBOL-GT Terminal, and COBOLX source formats. By default, the compiler tries to autodetect the format using the indicator on the first line, using the fixed format for correct indicators and the free format for incorrect ones. This can be overridden either by the >>SOURCE [FORMAT] [IS] {FIXED|FREE|COBOL85|VARIABLE|XOPEN|XCARD|CRT|TERMINAL|COBOLX|AUTO}directive, or by one of the following options:

  • -free, -F, -fformat=free

    Free format. The program-text area starts in column 1 and continues till the end of line (effectively 255 characters in GnuCOBOL).

  • -fixed, -fformat=fixed

    Fixed format. Source code is divided into: columns 1-6, the sequence number area; column 7, the indicator area; columns 8-72, the program-text area; and columns 72-80 as the reference area. 3

  • -fformat=cobol85

    Fixed format with enforcements on the use of Area A.

  • -fformat=variable

    Micro Focus’ Variable format. Identical to the fixed format above except for the program-text area which extends up to column 250 instead of 72.

  • -fformat=xcard

    ICOBOL xCard format. Variable format with right margin set at column 255 instead of 250.

  • -fformat=xopen

    X/Open Free-form format. The program-text area may start in column 1 unless an indicator is present, and lines may contain up to 255 characters. Indicator for debugging lines is ‘D‘ (D followed by a space) instead of ‘D‘ or ‘d‘.

  • -fformat=crt

    ICOBOL Free-form format (CRT). Similar to the X/Open format above, with lines containing up to 320 characters and single-character debugging line indicators (’D‘ or ‘d‘).

  • -fformat=terminal

    ACUCOBOL-GT Terminal format. Similar to the CRT format above, with indicator for debugging lines being ‘\D‘ instead of ‘D‘ or ‘d‘. This format is mostly compatible with VAX COBOL terminal source format.

  • -fformat=cobolx

    COBOLX format. This format is similar to the CRT format above, except that the indicator area is always present in column 1; the program-text area starts in column 2 and extends up to the end of the record. Lines may contain up to 255 characters.

  • -fformat=auto

    Autodetection of format. The compiler will use the first line of the file to detect whether the file is in fixed format (with a correct indicator at position 7), or in free format.

Note that with source formats XOPEN, CRT, TERMINAL, and COBOLX, missing spaces are not inserted within continued alphanumeric literals that are truncated before the right margin.

Area A denotes the source code that spans between margin A and margin B, and Area B spans from the latter to the end of the record. Area A enforcement checks the contents of Area A, and reports any item that does not belong to the correct Area: this feature helps in developping COBOL programs that are portable to actual mainframe environments.

In general, division, section, and paragraph names must start in Area A. In the DATA DIVISION, level numbers ‘01‘ and ‘77‘, must also start in Area A. In the PROCEDURE DIVISIONs, statements and separator periods must fit within Area B. Every source format listed above may be subject to Area A enforcement, except FIXED, FREE, and XOPEN.

Note that Area A enforcement enables recovery from missing periods between paragraphs and sections.

Warning options

Warnings are diagnostic messages that report constructions that are not inherently erroneous but that are risky or suggest there may have been an error.

The following options do not enable specific warnings but control the kinds of diagnostics produced by cobc.

  • -fsyntax-only

    Check Check the code for syntax errors, but don’t do anything beyond that.

  • -fmax-errors=<n>

    Limits the maximum number of error messages to <n>, at which point cobc bails out rather than attempting to continue processing the source code. If <n> is 0, there is no limit on the number of error messages produced. If -Wfatal-errors is also specified, then -Wfatal-errors takes precedence over this option.

  • -w

    Inhibit all warning messages.

  • -Werror

    Make all warnings into errors.

  • -Werror=<warning>

    Make the specified <warning> into an error. The specifier for a warning is appended; for example -Werror=obsolete turns the warnings controlled by -Wobsolete into errors. This switch takes a negative form, to be used to negate -Werror for specific warnings; for example -Wno-error=obsolete makes -Wobsolete warnings not be errors, even when -Werror is in effect.

    The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (Printing of the option in the warning message can be disabled using the -fno-diagnostics-show-option flag.)

    Note that specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything.

  • -Wfatal-errors

    This option causes the compiler to abort compilation on the first error occurred rather than trying to keep going and printing further error messages.

You can request many specific warnings with options beginning with ‘-W‘, for example -Wimplicit-define to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning ‘-Wno‘ to turn off warnings; for example, -Wno-implicit-define. This manual lists only one of the two forms, whichever is not the default.

Some options, such as -Wall and -Wextra, turn on other options, such as -Wtruncate. The combined effect of positive and negative forms is that more specific options have priority over less specific ones, independently of their position in the command-line. For options of the same specificity, the last one takes effect.

  • -Wall

    Enable all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning). The list of warning flags turned on by this option is shown in --help.

  • -Wextra, -W

    Enable every possible warning that is not dialect specific. This includes more information than -Wall would normally provide. (This option used to be called -W. The older name is still supported, but the newer name is more descriptive.)

  • -W<warning>

    Enable single warning <warning>.

  • -Wno-<warning>

    Disable single warning <warning>.

  • -Warchaic

    Warn if archaic features are used, such as continuation lines or the NEXT SENTENCE statement.

  • -Wcall-params

    Warn if non-01/77-level items are used as arguments in a CALL statement. This is not set with -Wall.

  • -Wcolumn-overflow

    Warn if text after column 72 in FIXED format. This is not set with -Wall.

  • -Wconstant

    Warn inconsistent constant

  • -Wimplicit-define

    Warn if implicitly defined data items are used.

  • -Wlinkage

    Warn dangling LINKAGE items. This is not set with -Wall.

  • -Wobsolete

    Warn if obsolete features are used.

  • -Wparentheses

    Warn about any lack of parentheses around AND within OR.

  • -Wredefinition

    Warn about incompatible redefinitions of data items.

  • -Wstrict-typing

    Warn about type mismatch strictly.

  • -Wterminator

    Warn about the lack of scope terminator END-XXX. This is not set with -Wall.

  • -Wtruncate

    Warn on possible field truncation. This is not set with -Wall.

  • -Wconstant-expression

  • -Wconstant-numlit-expression

    Warn about expressions that always resolve to true/false and therefore lead to unreachable code.

  • -Wunreachable

    Warn if statements are likely unreachable. This is not set with -Wall.

  • -Wadditional

    Enable warnings that don’t have an own warning flag.

Configuration options

The compiler uses many dialect specific options. These may be set via a defined dialect by -std=, a configuration file by -conf= or by using the single dialect flags directly.

Appendix G, and config/*.conf.

Note concerning the defined dialects: The GnuCOBOL compiler tries to limit both the feature-set and reserved words to the specified compiler when the “strict” dialects are used. COBOL sources compiled with these dialects are therefore likely to compile with the specified compiler and vice versa: sources that were compiled on the specified compiler should compile without any issues with GnuCOBOL. With the “non-strict” dialects GnuCOBOL will activate the complete feature-set where it doesn’t directly conflict with the specified dialect, including reserved words. COBOL sources compiled with these dialects therefore may work only with GnuCOBOL. COBOL sources may need a change because of reserved words in GnuCOBOL, otherwise offending words <word-1> and <word-2> may be removed by -fno-reserved=<word-1>,<word-1>.

The dialects COBOL-85, X/Open COBOL, and are always “strict”.

  • -std=<dialect>

    Compiler uses the given <dialect> to determine certain compiler features and warnings.

  • -std=default

    GnuCOBOL dialect, supporting many of the and features, many extensions found in other dialects and its own feature-set

  • -std=cobol85

    COBOL-85 without any extensions other than the amendment Intrinsic Function Module (1989), source compiled with this dialect is likely to compile with most COBOL compilers

  • -std=xopen

    X/Open COBOL (based on COBOL-85) without any vendor extensions, source compiled with this dialect is likely to compile with most COBOL compilers; will warn items that “should not be used in a conforming source program”

  • -std=cobol2002, -std=cobol2014

    / without any vendor extensions, use -Warchaicand -Wobsolete if archaic/obsolete features should be flagged

  • -std=ibm-strict, -std=ibm

    IBM compatible

  • -std=mvs-strict, -std=mvs

    MVS compatible

  • -std=mf-strict, -std=mf

    Micro Focus compatible

  • -std=bs2000-strict, -std=bs2000

    BS2000 compatible

  • -std=acu-strict, -std=acu

    ACUCOBOL-GT compatible

  • -std=rm-strict, -std=rm

    RM/COBOL compatible

  • -std=realia-strict, -std=realia

    CA Realia II compatible

  • -std=gcos-strict, -std=gcos

    GCOS compatible

  • -freserved-words=<dialect>

    Compiler uses the given <dialect> to determine the reserved words.

  • -conf=<file>

    User-defined dialect configuration.

  • -febcdic-table=<cconv-table>/<file>

    EBCDIC/ASCII translation table to use; either read from <file>, or one of the existing <cconv-table> from the configuration directory (see cobc --info) which have a .ttbl extension, for example -febcdic-table=alternate. See the default.ttbl file for detailed information about the format.

You can override each single configuration entry by using compiler configuration options on the command line.

Examples:

  • -frelax-syntax-checks

  • -frenames-uncommon-levels=warning

  • -fnot-reserved=CHAIN,SCREEN

  • -ftab-width=4

Appendix A.

Listing options

  • -t=<file>

    Generate and place the standard print listing into <file>.

  • -T=<file>

    Generate and place a wide print listing into *<file>.

  • --tlines=<lines>

    Specify lines per page in print listing, default = 55. Set to zero for no additional page breaks.

  • -ftsymbols

    Generate symbol table in listing.

  • -fno-theader

    Suppress all headers from listing while keeping page breaks.

  • -fno-tmessages

    Suppress warning and error summary from listing.

  • -fno-tsource

    Suppress actual source from listing (for example to only produce the cross-reference).

  • -P, -P<directory>, -P=<file>

    Generate and place a preprocessed listing (old format) into <filename>.lst, <directory>/<filename>.lst, <file>.

  • -Xref

  • -X

    Generate cross reference in the listing.

Here is an example program listing with the options -t -ftsymbols:

GnuCOBOL 3.0.0   test.cbl                   Mon May 14 10:23:45 2018  Page 0001

LINE    PG/LN  A...B...........................................................

000001         IDENTIFICATION   DIVISION.
000002         PROGRAM-ID.      prog.
000003         ENVIRONMENT DIVISION.
000004         CONFIGURATION SECTION.
000005         DATA             DIVISION.
000006         WORKING-STORAGE  SECTION.
000007         COPY 'values.cpy'.
000001C        78  I   VALUE 20.
000002C        78  J   VALUE 5000.
000003C        78  M   VALUE 5.
000008         01  SETUP-REC.
000009             05  FL1       PIC X(04).
000010             05  FL2       PIC ZZZZZ.
000011             05  FL3       PIC 9(04).
000012             05  FL4       PIC 9(08) COMP.
000013             05  FL5       PIC 9(04) COMP-4.
000014             05  FL6       PIC Z,ZZZ.99.
000015             05  FL7       PIC S9(05) SIGN LEADING SEPARATE.
000016             05  FL8       PIC X(04).
000017             05  FL9 REDEFINES FL8 PIC 9(04).
000018             05  FLA.
000019                 10  FLB OCCURS I TIMES.
000020                     15  FLC PIC X(02).
000021                 10  FLD   PIC X(20).
000022             05  FLD1      PIC X(100).
000023             05  FLD2 OCCURS M TO J TIMES DEPENDING ON FL5.
000024                 10  FILLER PIC X(01).
000025             05  FLD3      PIC X(3).
000026             05  FLD4      PIC X(4).
000027         PROCEDURE        DIVISION.
000028             STOP RUN.

The first part of the listing lists the program text. If the program text is a COPY the line number reflects the COPY line number and is appended with a ‘C‘.

When the wide list option -T is specified, the SEQUENCEcolumns (for fixed-form reference-format) are included in the listing.

The second part of the listing file is the listing of the Symbol Table:

GnuCOBOL 3.0.0   test.cbl                   Mon May 14 10:23:45 2018  Page 0002

SIZE TYPE           LVL  NAME                           PICTURE

5204 GROUP          01   SETUP-REC
0004 ALPHANUMERIC   05     FL1                          X(04)
0005 ALPHANUMERIC   05     FL2                          ZZZZZ
0004 ALPHANUMERIC   05     FL3                          9(04)
0004 NUMERIC        05     FL4                          9(08) COMP
0002 NUMERIC        05     FL5                          9(04) COMP
0008 ALPHANUMERIC   05     FL6                          Z,ZZZ.99
0006 ALPHANUMERIC   05     FL7                          S9(05)
0004 ALPHANUMERIC   05     FL8                          X(04)
0004 ALPHANUMERIC-R 05     FL9                          9(04)
0060 ALPHANUMERIC   05     FLA
0040 ALPHANUMERIC   10       FLB                        OCCURS 20
0002 ALPHANUMERIC   15         FLC                      X(02)
0020 ALPHANUMERIC   10       FLD                        X(20)
0100 ALPHANUMERIC   05     FLD1                         X(100)
5000 ALPHANUMERIC   05     FLD2                         OCCURS 5 TO 5000
0001 ALPHANUMERIC   10       FILLER                     X(01)
0003 ALPHANUMERIC   05     FLD3                         X(3)
0004 ALPHANUMERIC   05     FLD4                         X(4)

If the symbol redefines another variable the TYPE is marked with ‘R‘. If the symbol is an array the OCCURS phrase is in the PICTURE field.

The last part of the listing file is the summary of warnings an error in the compilation group:

0 warnings in compilation group
2 errors in compilation group

Debug switches

  • -g

    Produce C debugging information in the output.

  • --debug, -d

    Enable all run-time error checks.

  • -fmemory-check=scope

    Enable checking of internal storage during CALL (implied by --debug.

  • -fec=exception-name, -fno=ec=exception-name

    Enable/disable specified exception checks, Appendix F; --debug implies -fec=ALL.

  • -fsource-location

    Generate source location code (implied by --debug, -fdump and -fec).

  • -fstack-check

    Enable PERFORM stack checking (implied by --debug or -g).

  • -ftrace

    Generate trace code (log executed procedures, if tracing is enabled).

  • -ftraceall

    Generate trace code (log executed procedures and statements, if tracing is enabled).

  • -fdebugging-line

    Enable debugging lines (’D‘ in indicator column; ‘>>D‘ directive).

  • -O

    Enable optimization of code size and execution speed. See your C compiler documentation, for example man gcc for details.

  • -O2

    Optimize even more.

  • -Os

    Optimize for size. Optimizer will favour code size over execution speed.

  • -fnotrunc

    Do not truncate binary fields according to PICTURE.

Miscellaneous

  • -ext <extension>

    Add default file extension.

  • -fintrinsics=[ALL|intrinsic function name(,name,...)]

    Allow use of all or specific intrinsic functions without FUNCTIONkeyword.

    Note: defining this within your source with CONFIGURATION SECTION. REPOSITORY. is preferred.

  • -ffold-copy=LOWER

    Fold COPY subject to lower case (default no transformation).

  • -ffold-copy=UPPER

    Fold COPY subject to upper case (default no transformation).

  • -save-temps(=<dir>)

    Save intermediate files (by default, in current directory).

  • -fimplicit-init

    Do automatic initialization of the COBOL runtime system.

Multiple sources

This section describes how to compile a program from multiple source files.

This section also describes how to build a shared library that can be used by any COBOL program and how to use external libraries in COBOL programs.

Static linking

The easiest way of combining multiple files is to compile them into a single executable.

One way is to compile all the files in one command:

$ cobc -x -o prog main.cob subr1.cob subr2.cob

Another way is to compile each file with the option -c, and link them at the end. The top-level program must be compiled with the option -x.

$ cobc -c subr1.cob
$ cobc -c subr2.cob
$ cobc -c -x main.cob
$ cobc -x -o prog main.o subr1.o subr2.o

You can link C routines as well using either method:

$ cobc -o prog main.cob subrs.c

or

$ cobc -c subrs.c $ cobc -c -x main.cob $ cobc -x -o prog main.o subrs.o

Any number of functions can be contained in a single C file.

The linked programs will be called dynamically; that is, the symbol will be resolved at run time. For example, the following COBOL statement

CALL "subr" USING X.

will be converted into equivalent C code like this:

int (*func)() = cob_resolve("subr");
if (func != NULL)
  func (X);

With the compiler option -fstatic-call, more efficient code will be generated:

subr(X);

Please notice that this option only takes effect when the called program name is in a literal (like CALL "subr"). With a data name (like CALL SUBR), the program is still called dynamically.

Dynamic linking

There are two methods to achieve this: a driver program, or compiling the main program and subprograms separately.

Compile all programs with the option -m:

$ cobc -m main.cob subr.cob

This creates the shared object files main.so and subr.so. 4

Before running the main program, install the module files in your library directory:

$ cp subr.so /your/cobol/lib

Set the runtime variable COB_LIBRARY_PATHto your library directory, and run the main program:

$ export COB_LIBRARY_PATH=/your/cobol/lib

(Please notice: You may set the variable via a runtime configuration file, Appendix I. You may also set the variable to directly point to the directory where you compiled the sources.)

Now execute your program:

$ cobcrun main

The main program is compiled as usual:

$ cobc -x -o main main.cob

Subprograms are compiled with the option -m:

$ cobc -m subr.cob

This creates a module file subr.so 5 .

Before running the main program, install the module files in your library directory:

$ cp subr.so /your/cobol/lib

Now, set the environment variable COB_LIBRARY_PATHto your library directory, and run the main program:

$ export COB_LIBRARY_PATH=/your/cobol/lib
$ ./main

Building library

You can build a shared library by combining multiple COBOL programs and even C routines:

$ cobc -c subr1.cob
$ cobc -c subr2.cob
$ cc -c subr3.c
$ cc -shared -o libsubrs.so subr1.o subr2.o subr3.o

Using library

You can use a shared library by linking it with your main program.

Before linking the library, install it in your system library directory:

$ cp libsubrs.so /usr/lib

or install it somewhere else and set LD_LIBRARY_PATH:

$ cp libsubrs.so /your/cobol/lib
$ export LD_LIBRARY_PATH=/your/cobol/lib

Then, compile the main program, linking the library as follows:

$ cobc -x main.cob -L/your/cobol/lib -lsubrs

C interface

This chapter describes how to combine C programs with COBOL programs.

Writing Main Program in C

Include libcob.h in your C program and call cob_init before using any COBOL module. Do a cleanup afterwards, either by calling cob_stop_run (if your program should terminate) or by calling cob_tidy (if your program should execute further on without any more COBOL calls). Calling cob_init, one or several GnuCOBOL modules and then cob_tidyin this sequence can be done multiple times).

#include <libcob.h>

int
main (int argc, char **argv)
{
  /* initialize your program */
  ...

  /* initialize the COBOL run-time library */
  cob_init (argc, argv);

  /* rest of your program */
  ...

  /* Clean up and terminate - This does not return */
  cob_stop_run (return_status);
}

You can write cobc_init(0, NULL); if you do not want to pass command line arguments to COBOL.

The easiest option to compile and/or link your C program is by passing the work to cobc as follows:

cobc -x main.c

possibly running in verbose mode to see what cobc does:

cobc -x --verbose main.c   # using -x -v or -xv would be also possible

or with several steps:

cobc -c main.c
cobc -x main.o

As an alternative you can use the cob-config tool to get the necessary options to be passed to the C compiler / linker.

cc -c `cob-config --cflags` main.c    # compile only
cc -o main main.o `cob-config --libs` # link only

Static linking with COBOL programs

Let’s call the following COBOL module from a C program:

---- say.cob ---------------------------
       IDENTIFICATION DIVISION.
       PROGRAM-ID. say.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       LINKAGE SECTION.
       01 hello PIC X(7).
       01 world PIC X(6).
       PROCEDURE DIVISION USING hello world.
           DISPLAY hello world.
           GOBACK.
----------------------------------------

This program accepts two arguments, displays them, and exits.

From the viewpoint of C, this is equivalent to a function having the following prototype:

extern int say(char *hello, char *world);

So, your main program will look like as follows:

---- hello.c ---------------------------
#include <libcob.h>

extern int say(char *hello, char *world);

int
main()
{
  int ret;
  char hello[8] = "Hello, ";
  char world[7] = "world!";

  /* initialize the COBOL run-time library */
  cob_init(0, NULL);

  /* call the static module and store its return code */
  ret = say(hello, world);

  /* shutdown the COBOL run-time library, keep program running */
  (void)cob_tidy();

  return ret;
}
----------------------------------------

Compile and run these programs as follows:

$ cobc -x hello.c say.cob
$ ./hello
Hello, world!

or, more split and directly using the C compiler:

$ cc -c `cob-config --cflags` hello.c
$ cobc -c -static say.cob
$ cobc -x -o hello hello.o say.o
$ ./hello
Hello, world!

Note: The biggest benefits of static linking are that all programs are verified to be available in the resulting binary. Furthermore there is a slightly performance benefit in this type of CALL (not visible for “normal” programs).

Dynamic linking with COBOL programs

You can find a COBOL module having a specific name by using the C function cob_resolve, which takes the module name as a string and returns a pointer to the module function.

cob_resolve returns NULL if there is no module. In this case, the function cob_resolve_error returns the error message.

Let’s see an example:

---- hello-dynamic.c -------------------
#include <libcob.h>

static int (*say)(char *hello, char *world);

int main()
{
  int ret;
  char hello[8] = "Hello, ";
  char world[7] = "world!";

  /* initialize the COBOL run-time library */
  cob_init(0, NULL);

  /* Find the module with PROGRAM-ID "say". */
  say = cob_resolve("say");

  /* If there is no such module, show error and exit. */
  if(say == NULL) {
    fprintf(stderr, "%s\n", cob_resolve_error());
    exit(1);
  }

  /* Call the module found ... */
  ret = say(hello, world);

  /* ...and exit with the return code. */
  cob_stop_run(ret);
}
----------------------------------------

Compile and run these programs as follows:

$ cobc -x -o hello hello-dynamic.c
$ cobc -m say.cob
$ export COB_LIBRARY_PATH=.
$ ./hello
Hello, world!

The check of the module load as written above can be directly done in libcob as follows:

---- hello-dynamic2.c ------------------
#include <libcob.h>

int main()
{
  int ret;
  char hello[8] = "Hello, ";
  char world[7] = "world!";

  void *cob_argv[2];
  cob_argv[0] = hello;
  cob_argv[1] = world;

  /* initialize the COBOL run-time library */
  cob_init(0, NULL);

  /* do a CALL, expecting the module to exist,
     otherwise exiting with an error. */
  ret = cob_call ("say", 2, cob_argv);

  /* ...and exit with the return code. */
  cob_stop_run(ret);
}
----------------------------------------

In any case be aware that all errors that happen within COBOL will exit your program, as same as a STOP RUN will do.

Depending on the application you possibly want to register C signal handlers; error and/or exit handlers in C and/or COBOL to do cleanups, logging or anything else.

There is one way to handle all these scenarios with a call, too, using cob_call_with_exception_check instead of cob_call as follows:

---- hello-dynamic3.c ------------------
#include <libcob.h>

int main()
{
  int ret;
  char hello[8] = "Hello, ";
  char world[7] = "world!";

  void *cob_argv[2];
  cob_argv[0] = hello;
  cob_argv[1] = world;

  /* initialize the COBOL run-time library */
  cob_init(0, NULL);

  /* do a CALL, catching all possible results, */
  ret = cob_call_with_exception_check ("say", 2, cob_argv);

  switch (ret) {
  case 0:  /* program coming back */

    /* Clean up and terminate runtime */
    cob_runtime_hint("program exited with return code %d",
       cob_last_exit_code ());
    cob_tidy ();
    break;

  case 1:  /* normal exit */
    cob_runtime_hint("STOP RUN with return code %d",
       cob_last_exit_code ());
    break;

  case -1:  /* error exit */
    cob_runtime_hint("error exit with return code %d and error \"%s\"",
       cob_last_exit_code (), cob_last_runtime_error ());
    break;

  case -2:  /* hard error exit */
    cob_runtime_hint("hard error exit with return code %d and error \"%s\"",
       cob_last_exit_code (), cob_last_runtime_error ());
    break;

  case -3:  /* signal handler  exit */
    cob_runtime_hint("signal handler exit with signal %d and error \"%s\"",
       cob_last_exit_code (), cob_last_runtime_error ());
    break;

  default:
    cob_runtime_hint("unexpected return from cob_call_with_exception_check,"
       " last exit code %d, last error \"%s\"",
       cob_last_exit_code (), cob_last_runtime_error ());
    break;
  }

  /* ...and exit with zero if no error happened */
  exit(ret != 0 && ret != 1);
}
----------------------------------------

Static linking with C programs

Let’s call the following C function from COBOL:

---- say.c -----------------------------
int say(char *hello, char *world)
{
  int i;
  for(i = 0; i < 7; i++)
    putchar(hello[i]);
  for(i = 0; i < 6; i++)
    putchar(world[i]);
  putchar('\n');
  return 0;
}
----------------------------------------

This program is equivalent to the program in say.cob above.

Note that, unlike C, the arguments passed from COBOL programs are not terminated by the null character (i.e., ‘\0‘).

You can call this function in the same way you call COBOL programs:

---- hello.cob -------------------------
       IDENTIFICATION DIVISION.
       PROGRAM-ID. hello.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 hello PIC X(7) VALUE "Hello, ".
       01 world PIC X(6) VALUE "world!".
       PROCEDURE DIVISION.
       CALL "say" USING hello world.
       STOP RUN.
----------------------------------------

Compile these programs as follows:

$ cobc -x -o hello -static hello.cob say.c
$ ./hello
Hello, world!

or separate:

$ cc -c say.c
$ cobc -c -static -x hello.cob
$ cobc -x -o hello hello.o say.o
$ ./hello
Hello, world!

Dynamic linking with C programs

You can create a dynamically-linked module from a C program by compiling it with cobc …

$ cobc -m say.c
$ cobc -x hello.cob
$ export COB_LIBRARY_PATH=.
$ ./hello
Hello, world!

or with most C compilers by passing option -shared to the C compiler:

$ cc -shared -o say.so say.c
$ cobc -x hello.cob
$ export COB_LIBRARY_PATH=.
$ ./hello
Hello, world!

Mind that for COBOL to be able to load the module via CALL the name of the binary must either be identical to the CALL name or the binary containing the entry-point must have been loaded before (by a previous call or COB_PRE_LOAD).

Redirecting output to a (FILE *)

From a module written in C you can call cob_set_runtime_optionto set the exact (FILE *) which is used to write trace data to. In common.h is the following:

enum cob_runtime_option_switch {
   COB_SET_RUNTIME_TRACE_FILE              /* 'p' is  FILE *  */
   COB_SET_RUNTIME_DISPLAY_PRINTER_FILE    /* 'p' is  FILE *  */
   COB_SET_RUNTIME_RESCAN_ENV              /* rescan environment variables */
   COB_SET_RUNTIME_DISPLAY_PUNCH_FILE      /* 'p' is  FILE *  */
};
COB_EXPIMP  void  cob_set_runtime_option   (enum cob_runtime_option_switch opt, void *p);

So from you C code you can tell the GnuCOBOL runtime to redirect TRACE output by:

cob_set_runtime_option (COB_SET_RUNTIME_TRACE_FILE,
                        (void*)((FILE*)myfd));

You could also redirect all DISPLAY UPON PRINTER output to a file by:

cob_set_runtime_option (COB_SET_RUNTIME_DISPLAY_PRINTER_FILE,
                        (void*)((FILE*)myfd));

You could also redirect all DISPLAY UPON SYSPUNCH output to a file by:

cob_set_runtime_option (COB_SET_RUNTIME_DISPLAY_PUNCH_FILE,
                         (void*)((FILE*)myfd));

Another routine can be used to return the current value of the option.

COB_EXPIMP  void *
cob_get_runtime_option (enum cob_runtime_option_switch opt);

Loading EBCDIC/ASCII translation tables (collating sequences)

When an EBCDIC/ASCII translation table is needed (for instance when calling sort functions), you can can call the cob_load_collation function to retrieve such tables:

COB_EXPIMP int
cob_load_collation (const char *col_name,
                    cob_u8_t *ebcdic_to_ascii,
                    cob_u8_t *ascii_to_ebcdic)
1

Support may be partial or complete.

2

The extension varies depending on your host.

3

Historically, fixed

format was based on 80-character punch cards.

4

The extension used depends on your operating system.

5

The extension

used depends on your operating system.