10 Interfacing With The OS

10.1 Compiling Programs

Program source files should have by convention, extensions of .cob or .cbl.

Program file names should match exactly the specification of PROGRAM-ID (including case).

Spaces cannot be included in primary entry-point names and therefore must not be included in program file names.

The GnuCOBOL compiler will translate your COBOL program into C source code, compile that C source code into executable binary form using the C compiler specified when GnuCOBOL was built and link that executable binary into:

  • Directly executable form

    This is an executable file directly-executable from the command-line. On Windows computers, this would be an .exe file. On Unix systems, this will be a file with no specific extension, but with execute permissions. This file will include the main program as well as any static-linked subprograms.

  • Static-linkable form

    This is a single subprogram compiled into object-code form, ready to be linked in with a main program to form a directly-executable program. On windows computers, these generally are .o (object-code) files.

  • Dynamically-loadable executable form

    These are dynamically-loadable object code files ready to be invoked from other programs at execution time. On Windows systems, these would be .dll files, while on Unix systems they are typically .so files (OSX uses .dylib).

10.1.1 cobc - The GnuCOBOL Compiler

The GnuCOBOL compiler is named cobc ( cobc.exe on a Windows system).

The following describes the syntax and option switches of the cobc command. This information may be displayed by entering the command cobc --help or cobc -h.

GnuCOBOL compiler for most COBOL dialects with lots of extensions

Sorted within groups

Usage: cobc [options]... file...

Options:
  -h, --help             display this help and exit

  -du(mpversion)         display compiler version and exit
  -i, --info             display compiler information (build/environment)
                         and exit
  -q, --brief            reduced displays, commands invoked not shown
  -v, --verbose          verbose mode, display additional information;
                         multiple -v options increase the verbosity,
                         the maximum is 3 as follows:
                         (1) display compiler version and the commands
                         invoked by the compiler,
                         (2) pass verbose option to assembler/compiler
                         (3) pass verbose option to linker
  -V, --version          display compiler version information and exit
  -###                   like -v but commands not executed

  -A <options>           add <options> to the C compile phase
  -b                     combine all input files into a single
                         dynamically loadable module
  -c                     compile and assemble, but do not link
  --conf=<file>          user-defined dialect configuration; see -std
  -C                     translation only; convert COBOL to C
  -d, --debug            enable all run-time error checking,
                         equal to -fstack-check -fec=EC-ALL
  -D <define>            define <define> for COBOL compilation
  -ext <extension>       add file extension for resolving COPY
  -E                     preprocess only; do not compile or link
  -F, --free             use free source format (alias for -fformat=free)
  --fixed                use fixed source format (default; alias for
                         -fformat=fixed)
  -fec=<exception-name>        enable code generation for <exception-name>,
                         see --list-exceptions for the possible values,
                         sets -fsource-location
  -fno-ec=<exception-name>
                         disable code generation for <exception-name>
  -g                     enable C compiler debug and stack check
  -I <directory>         add <directory> to copy/include search path
  -j [<args>], --job[=<args>]
                         run program after build, passing <args>
  -K <entry>             generate CALL to <entry> as static
  -l <lib>               link the library <lib>
  -L <directory>         add <directory> to library search path
  --list-exceptions      display exception names
  --list-intrinsics      display intrinsic functions
  --list-mnemonics       display mnemonic names
  --list-reserved        display reserved words
  --list-system          display system routines
  -m                     build a dynamically loadable module (default)
  -o <file>              place the output into <file>
  -O, -O2, -O3, -Os      enable optimization
  -O0                    disable optimization
  -P[=<dir or file>]     generate preprocessed program listing (.lst)
  -Q <options>           add <options> to the C link phase
  -std=<dialect>         warnings/features for a specific dialect
                         <dialect> can be one of:
                         default, cobol2014, cobol2002, cobol85, xopen,
                         ibm-strict, ibm, mvs-strict, mvs,
                         mf-strict, mf, bs2000-strict, bs2000,
                         acu-strict, acu, rm-strict, rm, gcos-strict,
                         gcos;
                         see configuration files in directory config
  -S                     compile only; output assembly file
  --save-temps[=<dir>]   save intermediate files
                         * default: current directory
  -t <file>              generate and place a program listing into <file>
  --tlines=<lines>       specify lines per page in listing, default = 55
  -T <file>              generate and place a wide program listing into <file>
  -x                     build an executable program
  -X, --Xref             generate internal cross reference


Warning options:
  -w                     disable all warnings
  -Wall                  enable most warnings (all except as noted below)
  -Wadditional           additional warnings only raised with -Wall
  -Warchaic              warn if archaic features are used
  -Warithmetic-osvs      warn if arithmetic expression precision has changed
  -Wcall-params          warn about non 01/77 items for CALL parameters
                         * NOT set with -Wall
  -Wcolumn-overflow      warn about text after program-text area, FIXED format
                         * NOT set with -Wall
  -Wconstant-expression  warn about expressions that always resolve to true/false
  -Wconstant-numlit-expression
                         warn about numeric expressions that always resolve to
                         true/false
  -Wdangling-text        warn about source text after program-area
                         * NOT set with -Wall
  -Werror                treat all warnings as errors
  -Werror=<warning>      treat specified <warning> as error
  -Wextra                like -Wall but enable some extra warning flags
  -Wimplicit-define      warn whenever data items are implicitly defined
                         * NOT set with -Wall
  -Winitial-value        warn if initial VALUE clause is ignored
  -Wlarger-01-redefines  warn about larger redefines allowed by COBOL standards
  -Wlinkage              warn about dangling LINKAGE items
                         * NOT set with -Wall
  -Wobsolete             warn if obsolete features are used
  -Woverlap              warn about overlapping MOVE of items
  -Wno-corresponding     do not warn about CORRESPONDING with no matching items
                         * ALWAYS active
  -Wno-dialect           do not warn about dialect specific issues
                         * ALWAYS active
  -Wgoto-different-section
                         warn about GO TO a praragraph defined in a different section
  -Wno-error             don't treat warnings as errors
  -Wno-error=<warning>   don't treat specified <warning> as error
  -Wno-goto-section      do not warn about GO TO section-name
                         * ALWAYS active
  -Wno-ignored-error     do not warn about errors in code parts which are
                         unreachable and so normally ignored
                         * ALWAYS active
  -Wno-missing-newline   do not warn about missing newlines
                         * ALWAYS active
  -Wno-others            do not warn about different issues
                         * ALWAYS active
  -Wno-pending           do not warn if pending features are used
                         * ALWAYS active
  -Wno-repository-checks
                         do not warn/check for program/function/external signature
                         mismatch
                         * ALWAYS active
  -Wno-unfinished        do not warn if unfinished features are used
                         * ALWAYS active
  -Wno-unsupported       do not warn if runtime does not support a feature used
  -Wno-<warning>         disable warning enabled by default, -Wall or -Wextra
  -Wparentheses          warn if parentheses are omitted around AND within OR
  -Wpossible-overlap     warn about MOVE of items that may overlap depending on
                         variables
                         * NOT set with -Wall
  -Wpossible-truncate    warn about possible field truncation
                         * NOT set with -Wall
  -Wprototypes           warn about missing FUNCTION prototypes/definitions
  -Wredefinition         warn about non-referenced ambiguous data items
  -Wstrict-typing        warn strictly about type mismatch
  -Wsuspicious-perform-thru
                         warn if PERFORM THRU references procedures not in ascending
                         order or multiple sections
                         * ALWAYS active
  -Wterminator           warn about lack of scope terminator END-XXX
                         * NOT set with -Wall
  -Wtruncate             warn about field truncation from constant assignments
  -Wunreachable          warn about likely unreachable statements
                         * NOT set with -Wall


Compiler options:
  -fsign=[ASCII|EBCDIC]        define display sign representation
                         * default: machine native
  -ffold-copy=[UPPER|LOWER]
                         fold COPY subject to value
                         * default: no transformation
  -ffold-call=[UPPER|LOWER]
                         fold PROGRAM-ID, CALL, CANCEL subject to value
                         * default: no transformation
  -fmax-errors=<number>        maximum number of errors to report before
                         compilation is aborted
                         * default: 128
  -fintrinsics=[ALL|intrinsic
                         function name(,name,...)]
                         intrinsics to be used without FUNCTION keyword
  -fdump=<scope>         dump data fields on abort, <scope> may be
                         a combination of: ALL, WS, LS, RD, FD, SC, LO
  -fcallfh=<name>        specifies <name> to be used for I/O
                         as external provided EXTFH interface module
  -febcdic-table=[DEFAULT|RESTRICTED-GC|IBM|GCOS]
                         define EBCDIC translation table:
                         * default: translation to extended ASCII as per MF
                         * restricted-gc: translation from restricted ASCII only
                         * ibm: translation to restricted ASCII as per IBM
                         * gcos: translation to extended ASCII as per GCOS7
  -fdefault-colseq=[ASCII|EBCDIC|NATIVE]
                         define default collating sequence
                         * default: NATIVE
  -fstack-extended       store origin of entrypoints and PERFORM
                         * turned on by -debug/-dump
  -fno-remove-unreachable
                         disable remove of unreachable code
                         * turned off by -g
  -ftrace                generate trace code
                         * scope: executed SECTION/PARAGRAPH
  -ftraceall             generate trace code
                         * scope: executed SECTION/PARAGRAPH/STATEMENTS
  -fsyntax-only          syntax error checking only; don't emit any output
  -fdebugging-line       enable debugging lines
                         * 'D' in indicator column or floating >>D
  -fsource-location      generate source location code
                         * turned on by -debug/-ftraceall/-fec/-dump
  -fimplicit-init        automatic initialization of the COBOL runtime system
  -fno-recursive-check   disable check of recursive program call;
                         effectively compiling as RECURSIVE program
  -fstack-check          PERFORM stack checking
                         * turned on by -debug/-g
  -fsection-exit-check   check that code execution does not leave the scope of
                         SECTIONs
  -fimplicit-goback-check
                         check that code execution does not end implicit at end of
                         PROCEDURE DIVISION
  -fwrite-after          use AFTER 1 for WRITE of LINE SEQUENTIAL
                         * default: BEFORE 1
  -fmfcomment            '*' in column 1 treated as comment with listing suppression
                         * FIXED/COBOL85/VARIABLE format only
  -facucomment           '$' in indicator area treated as '*',
                         '|' treated as floating comment
  -fno-trunc             allow numeric field overflow
                         * non-ANSI behaviour
  -fsingle-quote         use a single quote (apostrophe) for QUOTE
                         * default: double quote
  -foptional-file        treat all files as OPTIONAL
                         * unless NOT OPTIONAL specified
  -fstatic-call          output static function calls for the CALL statement
  -fno-gen-c-decl-static-call
                         disable generation of C function declarations
                         for subroutines with static CALL
  -fgen-c-line-directives
                         generate source location directives in C code;
                         * turned on by -g
  -fgen-c-labels         generate extra labels in C sources;
                         * turned on by -g
  -fno-theaders          suppress all headers and output of compilation
                         options from listing while keeping page breaks
  -fno-tsource           suppress source from listing
  -fno-tmessages         suppress warning and error summary from listing
  -ftsymbols             specify symbols in listing
  -fno-diagnostics-show-option
                         suppress output of option that directly
                         controls the diagnostic


Compiler dialect configuration options:
  -freserved-words=<value>
                         use of complete/fixed reserved words
  -ftab-width=1..12      number of spaces that are assumed for tabs
  -ftext-column=72..255  right margin column number for fixed-form reference format
  -fpic-length=<number>  maximum number of characters allowed in the PICTURE
                         character-string
  -fword-length=1..63    maximum word-length for COBOL (= programmer defined) words
  -fliteral-length=<number>
                         maximum literal size in general
  -fnumeric-literal-length=1..38
                         maximum numeric literal size
  -fdefaultbyte=<value>  default initialization for fields without VALUE, may be
                         one of
                         * character in quotes
                         * decimal 0..255 representing a character
                         * "init" to initialize to PICTURE/USAGE
                         * "none" to do no explicit initialization
                         * default: "init"
  -fformat=<value>       default reference-format, may be one of: FIXED, FREE,
                         COBOL85, VARIABLE, XOPEN, XCARD, CRT, TERMINAL, COBOLX
  -fbinary-size=<value>  binary byte size - defines the allocated bytes according to
                         PIC, may be one of: 2-4-8, 1-2-4-8, 1--8
  -fbinary-byteorder=<value>
                         binary byte order, may be one of: native, big-endian
  -fassign-clause=<value>
                         how to interpret 'ASSIGN word': as 'ASSIGN EXTERNAL word' or
                         'ASSIGN DYNAMIC word', may be one of: dynamic, external,
                         ibm (= external), mf (= dynamic)
  -fscreen-section-rules=<value>
                         which compiler's rules to apply to SCREEN SECTION item
                         clauses, may be one of: acu, gc, mf, rm, std, xopen
  -fdpc-in-data=<value>  whether DECIMAL-POINT IS COMMA has effect in XML/JSON
                         GENERATE, may be one of: none, xml, json, all
  -ffilename-mapping     resolve file names at run time using environment variables
  -fpretty-display       alternate formatting of numeric fields
  -fbinary-truncate      numeric truncation according to ANSI
  -fcomplex-odo          allow complex OCCURS DEPENDING ON
  -fodoslide             adjust items following OCCURS DEPENDING (implies complex-odo)
  -findirect-redefines   allow REDEFINES to other than last equal level number
  -frelax-syntax-checks  allow certain syntax variations (e.g. REDEFINES position)
  -fref-mod-zero-length  allow zero length reference-modification (only changed with
                         EC-BOUND-REF-MOD active)
  -frelax-level-hierarchy
                         allow non-matching level numbers
  -fselect-working       require ASSIGN USING items to be in WORKING-STORAGE
  -flocal-implies-recursive
                         LOCAL-STORAGE SECTION implies RECURSIVE attribute
  -fsticky-linkage       LINKAGE SECTION items remain allocated between invocations
  -fmove-ibm             MOVE operates as on IBM (left to right, byte by byte)
  -fperform-osvs         exit point of any currently executing perform is recognized
                         if reached
  -farithmetic-osvs      limit precision in intermediate results to precision of final
                         result (less accurate)
  -fconstant-folding     evaluate constant expressions at compile time
  -fhostsign             allow hexadecimal value 'F' for NUMERIC test of signed
                         PACKED DECIMAL field
  -fprogram-name-redefinition
                         program names don't lead to a reserved identifier
  -faccept-update        set WITH UPDATE clause as default for ACCEPT dest-item,
                         instead of WITH NO UPDATE
  -faccept-auto          set WITH AUTO clause as default for ACCEPT dest-item,
                         instead of WITH TAB
  -fconsole-is-crt       assume CONSOLE IS CRT if not set otherwise
  -fno-echo-means-secure      NO-ECHO
                         hides input with asterisks like SECURE
  -fline-col-zero-default
                         assume a field DISPLAY starts at LINE 0 COL 0 (i.e. at the
                         cursor), not LINE 1 COL 1
  -fdisplay-special-fig-consts
                         special behaviour of DISPLAY SPACE/ALL X'01'/ALL X'02'/ALL
                         X'07'
  -fbinary-comp-1        COMP-1 is a 16-bit signed integer
  -fnumeric-pointer      POINTER is a 64-bit unsigned integer
  -fmove-non-numeric-lit-to-numeric-is-zero
                         imply zero in move of non-numeric literal to numeric items
  -fimplicit-assign-dynamic-var
                         implicitly define a variable if an ASSIGN DYNAMIC does not
                         match any data item
  -fdevice-mnemonics     specifying device by mnemonic
  -fxml-parse-xmlss      XML PARSE XMLSS
  -fareacheck            check contents of Area A (when reference format supports
                         Area A enforcement),
                         enabled checks include:
                         * division, section, paragraph names, level indicators (FD,
                         SD, RD, and CD),
                           and toplevel numbers (01 and 77) must start in Area A;
                         * statements must not start in Area A; and
                         * separator periods must not be within Area A
  -fcomment-paragraphs=<support>
                         comment paragraphs in IDENTIFICATION DIVISION (AUTHOR,
                         DATE-WRITTEN, ...)
  -fcontrol-division=<support>
                         CONTROL DIVISION
  -fpartial-replace-when-literal-src=<support>
                         apply partial replacing with literal source operand even
                         when it replaces with spaces only;
                         * "skip" prevents such replacements
  -fmemory-size-clause=<support>
                         MEMORY-SIZE clause
  -fmultiple-file-tape-clause=<support>
                         MULTIPLE-FILE-TAPE clause
  -flabel-records-clause=<support>
                         LABEL-RECORDS clause
  -fvalue-of-clause=<support>
                         VALUE-OF clause
  -fdata-records-clause=<support>
                         DATA-RECORDS clause
  -ftop-level-occurs-clause=<support>
                         OCCURS clause on top-level
  -fsame-as-clause=<support>
                         SAME AS clause
  -ftype-to-clause=<support>
                         TYPE TO clause
  -fusage-type=<support>      USAGE type-name
  -fsynchronized-clause=<support>
                         SYNCHRONIZED clause
  -fsync-left-right=<support>
                         LEFT/RIGHT phrases in SYNCHRONIZED clause
  -fspecial-names-clause=<support>
                         SPECIAL-NAMES clause
  -fgoto-statement-without-name=<support>
                         GOTO statement without name
  -fstop-literal-statement=<support>
                         STOP-literal statement
  -fstop-identifier-statement=<support>
                         STOP-identifier statement
  -fstop-error-statement=<support>
                         STOP ERROR statement
  -fdebugging-mode=<support>
                         DEBUGGING MODE and debugging indicator
  -fuse-for-debugging=<support>
                         USE FOR DEBUGGING
  -fpadding-character-clause=<support>
                         PADDING CHARACTER clause
  -fnext-sentence-phrase=<support>
                         NEXT SENTENCE phrase
  -flisting-statements=<support>
                         listing-directive statements EJECT, SKIP1, SKIP2, SKIP3
  -ftitle-statement=<support>
                         listing-directive statement TITLE
  -fentry-statement=<support>
                         ENTRY statement
  -fmove-noninteger-to-alphanumeric=<support>
                         move noninteger to alphanumeric
  -fmove-figurative-constant-to-numeric=<support>
                         move figurative constants to numeric
  -fmove-figurative-space-to-numeric=<support>
                         move figurative constant SPACE to numeric
  -fmove-figurative-quote-to-numeric=<support>
                         move figurative constant QUOTE to numeric
  -fodo-without-to=<support>
                         OCCURS DEPENDING ON without to
  -fsection-segments=<support>
                         section segments
  -falter-statement=<support>
                         ALTER statement
  -fcall-overflow=<support>
                         OVERFLOW clause for CALL
  -fnumeric-boolean=<support>
                         boolean literals (B'1010')
  -fhexadecimal-boolean=<support>
                         hexadecimal-boolean literals (BX'A')
  -fnational-literals=<support>
                         national literals (N'UTF-16 string')
  -fhexadecimal-national-literals=<support>
                         hexadecimal-national literals (NX'265E')
  -fnational-character-literals=<support>
                         non-standard national literals (NC'UTF-16 string')
  -fhp-octal-literals=<support>
                         HP COBOL octal literals (%377)
  -facu-literals=<support>
                         ACUCOBOL-GT literals (#B #O #H #X)
  -fword-continuation=<support>
                         continuation of COBOL words
  -fnot-exception-before-exception=<support>
                         NOT ON EXCEPTION before ON EXCEPTION
  -faccept-display-extensions=<support>
                         extensions to ACCEPT and DISPLAY
  -frenames-uncommon-levels=<support>
                         RENAMES of 01-, 66- and 77-level items
  -flarger-redefines=<support>
                         allow larger REDEFINES items
  -fsymbolic-constant=<support>
                         constants defined in SPECIAL-NAMES
  -fconstant-78=<support>
                         constant with level 78 item (note: has left to right
                         precedence in expressions)
  -fconstant-01=<support>
                         constant with level 01 CONSTANT AS/FROM item
  -fperform-varying-without-by=<support>
                         PERFORM VARYING without BY phrase (implies BY 1)
  -freference-out-of-declaratives=<support>
                         references to sections not in DECLARATIVES from within
                         DECLARATIVES
  -fprogram-prototypes=<support>
                         CALL/CANCEL with program-prototype-name
  -fcall-convention-mnemonic=<support>
                         specifying call-convention by mnemonic
  -fcall-convention-linkage=<support>
                         specifying call-convention by WITH ... LINKAGE
  -fnumeric-value-for-edited-item=<support>
                         numeric literals in VALUE clause of numeric-edited items
  -fincorrect-conf-sec-order=<support>
                         incorrect order of CONFIGURATION SECTION paragraphs
  -fdefine-constant-directive=<support>
                         allow >> DEFINE CONSTANT var AS literal
  -ffree-redefines-position=<support>
                         REDEFINES clause not following entry-name in definition
  -frecords-mismatch-record-clause=<support>
                         record sizes does not match RECORD clause
  -frecord-delimiter=<support>
                         RECORD DELIMITER clause
  -fsequential-delimiters=<support>
                         BINARY-SEQUENTIAL and LINE-SEQUENTIAL phrases in
                         RECORD DELIMITER
  -frecord-delim-with-fixed-recs=<support>
                         RECORD DELIMITER clause on file with fixed-length records
  -fmissing-statement=<support>
                         missing statement (e.g. empty IF / PERFORM)
  -fmissing-period=<support>
                         missing period in PROCEDURE DIVISION (when reference format
                         supports Area A enforcement)
  -fzero-length-literals=<support>
                         zero-length literals, e.g. '' and ""
  -fxml-generate-extra-phrases=<support>
                         XML GENERATE's phrases other than COUNT IN
  -fcontinue-after=<support>
                         AFTER phrase in CONTINUE statement
  -fgoto-entry=<support>      ENTRY FOR GOTO and GOTO ENTRY statements
  -fassign-variable=<support>
                         ASSIGN [TO] variable in SELECT
  -fassign-using-variable=<support>
                         ASSIGN USING/VARYING variable in SELECT
  -fassign-ext-dyn=<support>
                         ASSIGN EXTERNAL/DYNAMIC in SELECT
  -fassign-disk-from=<support>
                         ASSIGN DISK FROM variable in SELECT
  -fvsam-status=<support>
                         VSAM status in FILE STATUS
  -fself-call-recursive=<support>
                         CALL to own PROGRAM-ID implies RECURSIVE attribute
  -frecord-contains-depending-clause=<support>
                         DEPENDING clause in RECORD CONTAINS
  -fpicture-l=<support>  PICTURE string with 'L' character
      where <support> is one of the following:
      'ok', 'warning', 'archaic', 'obsolete', 'skip', 'ignore', 'error',
      'unconformable'

      -fnot-reserved=<word>   word to be taken out of the reserved words list
 -freserved=<word>       word to be added to reserved words list
 -freserved=<word>:<alias>
                         word to be added to reserved words list as alias
 -fnot-register=<word>   special register to disable
 -fregister=<word> or <word>:<definition>
                         special register to enable

Each file specified on the cobc command constitutes a Compilation Unit. A compilation unit may be a single GnuCOBOL program — with or without nested subprograms( 11.2 Independent vs Contained vs Nested Subprograms) — or multiple GnuCOBOL programs, separated by END PROGRAM or END FUNCTION marker lines, as appropriate. 11.2 Independent vs Contained vs Nested Subprograms, for some examples of these marker lines.

A compilation unit may also be a C-language source program, recognized as such by having a file extension of .c or an assembly-language program, recognized by its file extension of .s. In such a case, COBOL compilation of that file will be bypassed by the cobc command; instead, the file will be passed directly to the C compiler or assembler (executed automatically by cobc).

A compilation unit may also be an object-code module (output from the C compiler), recognized as such by having a file extension of .o. In these situations, all compilation will be bypassed, and the object code will be “bound” into the generated executable by the linker (an ld command executed internally by the cobc command).

Pre-compiled object-code subprograms may be automatically located by the GnuCOBOL compiler and the loader by using the LD_LIBRARY_PATH compilation-time environment variable ( 10.1.4 Compilation Time Environment Variables). If they are locatable through that environment variable, they need not be named on the cobc command.

The collection of compilation units supplied on a single cobc execution constitute a Compilation Group. All executable code produced from a single compilation group will be collected together into a single executable file, whose filename will be the same as that of the first compilation unit specified on the cobc command.

The simplest mode of compilation is to generate a single executable file from one or more GnuCOBOL source files:

cobc -x mainprog.cbl sub1.cbl sub2.cbl

The main program must be the first program found in the first compilation unit ( mainprog.cbl). The remainder of that compilation unit as well as the rest of the files in the compilation group ( sub1.cbl and sub2.cbl) must be independent and/or contained subprograms ( 11.2 Independent vs Contained vs Nested Subprograms).

This command assumes that all source files are in the directory from which the cobc command was executed. You are, of course, free to include full pathnames with any filename, if necessary.

With the -x switch on the compiler command, a single directly-executable executable file (UNIX, Windows/Cygwin, OSX) or “exe” file (Windows, Windows/MinGW) will be generated. This executable file has the compiled code for all COBOL programs contained within the compilation group specified on the cobc command included in the file.

Any subroutines or user-defined functions that weren’t included in any of the source files comprising the compilation group will be treated as dynamically loadable subprograms ( 11.4 Dynamic vs Static Subprograms).

Optionally, the -o switch may be used in addition to -x to specify the name of the generated executable file. If -o switch is not specified, the filename of the 1st compilation unit will be used as the name of the executable file. The appropriate extension for the generated file ( .exe, on a Windows computer, for example) will be added to the filename that is explicitly specified or implicitly assumed for the output file.

Compilations may be performed to generate dynamically-loadable modules (or dynamically-loadable libraries, as they are frequently called). These compilations are performed by using the -m switch instead of -x switch:

cobc -m mainprog.cbl sub1.cbl sub2.cbl

When the -m switch is used, an operating-system-specific dynamically-loadable module is generated for each individual compilation unit, using the filename of each compilation unit as its module filename and either an extension of .so (UNIX, Windows/Cygwin), .dylib (OSX) or .dll (Windows, Windows/MinGW).

You may compile GnuCOBOL subprograms into assembler source code which can then be assembled and linked with a main program when that main program is compiled. To create such an assembler source file, compile the subprogram(s) as follows:

cobc -S sprog1.cbl

The above generates an assembler source file named sprog1.s. If you have multiple subprograms to compile this way, just string their file names out on the command. Each will be translated to its own assembler source file.

Later, when you wish to compile a calling program and combine any needed assembly language subroutines in (as static subroutines — 11.4 Dynamic vs Static Subprograms), use a command such as this:

cobc -x mainprog.cbl sprog1.s

10.1.2 cobc option -Xref an example

The following shows the output from using -Xref.

   Using the internal -Xref as extra options -X -t prog.list :

GnuCOBOL 3.1.2.0        prog.cbl             Thu Nov 25 15:31:52 2021  Page 0001

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

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

GnuCOBOL 3.1.2.0 prog.cbl Thu Nov 25 15:31:52 2021 Page 0002

NAME DEFINED REFERENCES

SETUP-REC 8 referenced by child FL1 9 not referenced FL2 10 not referenced FL3 11 not referenced FL4 12 not referenced FL5 13 25 x1 FL6 14 not referenced FL7 15 not referenced FL8 16 not referenced FL9 17 not referenced FLA 18 not referenced FLB 19 not referenced FLC 20 not referenced FLD 21 not referenced FLD1 22 not referenced FLD3 23 not referenced FLD4 24 not referenced FLD2 25 not referenced

GnuCOBOL 3.1.2.0 prog.cbl Thu Nov 25 15:31:52 2021 Page 0003

LABEL DEFINED REFERENCES

E prog 27

0 warnings in compilation group 0 errors in compilation group

10.1.3 Cross Reference listing using cobxref

This program is found in the contrib area or by itself in Sourceforge under its own name (cobxref).

The following shows the output from using cobxref with the same program example.

Note that cobxref also reports the COPY depth which can be up to 9 and includes the program being compiled as depth 1.

Using cobxref with command cobxref prog.cbl :

ACS Cobol Xref v2.02.03          Dictionary File for PROG    25/11/2021  15:22:00:04
                                  Page    1

     1  000001 IDENTIFICATION   DIVISION.
     2  000002 PROGRAM-ID.      prog.
     3  000003 ENVIRONMENT DIVISION.
     4  000004 CONFIGURATION SECTION.
     5  000005 DATA             DIVISION.
     6  000006 WORKING-STORAGE  SECTION.
     7  000007*COPY 'values.cpy'.
     8  000001 78  I   VALUE 20.
     9  000002 78  J   VALUE 5000.
    10  000003 78  M   VALUE 5.
    11  000008 01  SETUP-REC.
    12  000009     05  FL1       PIC X(04).
    13  000010     05  FL2       PIC ZZZZZ.
    14  000011     05  FL3       PIC 9(04).
    15  000012     05  FL4       PIC 9(08) COMP.
    16  000013     05  FL5       PIC 9(04) COMP-4.
    17  000014     05  FL6       PIC Z,ZZZ.99.
    18  000015     05  FL7       PIC S9(05) SIGN LEADING SEPARATE.
    19  000016     05  FL8       PIC X(04).
    20  000017     05  FL9 REDEFINES FL8 PIC 9(04).
    21  000018     05  FLA.
    22  000019         10  FLB OCCURS I TIMES.
    23  000020             15  FLC PIC X(02).
    24  000021         10  FLD   PIC X(20).
    25  000022     05  FLD1      PIC X(100).
    26  000025     05  FLD3      PIC X(3).
    27  000026     05  FLD4      PIC X(4).
    28  000023     05  FLD2 OCCURS M TO J TIMES DEPENDING ON FL5.
    29  000024         10  FILLER PIC X(01).
    30  000027 PROCEDURE        DIVISION.
    31  000028     STOP RUN.
    32        *>>>Info: Total Copy Depth Used = 02

ACS Cobol Xref v2.02.03 Dictionary File for PROG 25/11/2021 15:22:00:04

Page 2

Data Section (WORKING-STORAGE) Defn Locations ——————————-+—————————————————————

FL1 000012W FL2 000013W FL3 000014W FL4 000015W FL5 000016W 000028 FL6 000017W FL7 000018W FL8 000019W 000020 FL9 000020W FLA 000021W FLB 000022W FLC 000023W FLD 000024W FLD1 000025W FLD2 000028W FLD3 000026W FLD4 000027W I 000008W 000022 J 000009W 000028 M 000010W 000028 SETUP-REC 000011W

ACS Cobol Xref v2.02.03 Dictionary File for PROG 25/11/2021 15:22:00:04

Page 3

Procedure Defn Locations ——————————-+—————————————————————

None

10.1.4 Compilation Time Environment Variables

The following are the various environment variables that can play a role in the compilation of GnuCOBOL programs.

  • COB_CC *

    Set to the name of the C compiler you wish GnuCOBOL to use.

    Use this feature at your own risk – you should always use the c compiler your gnucobol build was generated for.

  • COB_CFLAGS *

    Set to any switches that you’d like to pass on to the C compiler from the cobc compiler (in addition to any that cobc will specify).

  • COB_CONFIG_DIR *

    Set to the path to the folder where GnuCOBOL config files are kept.

  • COB_COPY_DIR *

    If copybooks your program needs are not stored in the same directory as your program, set this environment variable to the folder in which the copybooks may be found (IBM mainframe programmers will recognize this as SYSLIB).

  • COB_LDADD

    Set to any additional linker switches ( ld) that can specify where standard libraries that must be linked with the program can be found. The default is “” (empty).

  • COB_LDFLAGS

    Set to any linker ( ld) switches that you’d like to pass on to the C compiler from the cobc compiler (in addition to any that cobc will specify).

  • COB_LIBS *

    Set to any linker switches ( ld) that specify where standard libraries that must be linked with the program can be found.

  • COBCPY

    This environment variable provides an additional means of specifying where copybooks may be found by the compiler (see also COB_COPY_DIR, above).

  • LD_LIBRARY_PATH

    If you are planning on using static-linked subroutine libraries, set this variable to the path of the directory containing your libraries.

  • TMPDIR

  • TMP

    Set to a directory/folder appropriate to create temporary files in. The intermediate working files created by the compiler will be created here (and deleted once they’re no longer needed).

    The variable TMPDIR is checked for a valid path first; if that isn’t set, then TMP is checked.

    On a Windows system, the TMP environment variable is normally set for you when you logon. If you wish to use a different temporary folder, you may set TMPDIR yourself and have no fear of disrupting other Windows software that relies on TMP.

  • *

    The starred environment variables above have default values, established when the version of GnuCOBOL you are using was built. To see these default values, as well as other build-specific information, execute the command:

    cobc -i
    

10.1.5 Predefined Compilation Variables

GnuCOBOL defines compilation variables when certain conditions are true.

If the condition associated with a variable is false, the variable is not defined during compilations.

  • DEBUG

    The -d debug flag is specified.

  • EXECUTABLE

    The module being compiled contains the main program.

  • GCCOMP

    The size of a COMP item is determined according to the GnuCOBOL scheme, where for a PICTURE of length:

    • 1-2

      item has 1 byte

    • 3-4

      item has 2 bytes

    • 5-9

      item has 4 bytes

    • 10-18

      item has 8 bytes.

  • GNUCOBOL

    GnuCOBOL is compiling the source unit.

  • HOSTSIGNS

    A signed packed-decimal item’s value may be considered NUMERIC if the sign has value X"F".

  • IBMCOMP

    The size of a COMP item is determined according to the IBM scheme, where for a PICTURE of length:

    • 1-4

      item has 2 bytes

    • 5-9

      item has 4 bytes

    • 10-18

      item has 8 bytes.

  • MODULE

    The module being compiled does not contain the main program.

  • NOHOSTSIGNS

    A signed packed-decimal item’s value may not be considered

  • NUMERIC

    if the sign has value X"F".

  • NOIBMCOMP

    The size of a COMP item is not determined according to the IBM scheme.

  • NOSTICKYLINKAGE

    Sticky-linkage (linkage-section items remaining allocated between invocations) is not enabled.

  • NOTRUNC

    Numeric data items are truncated according to their internal representation.

  • P64

    Pointers are greater than 32 bits long

  • STICKY-LINKAGE

    Sticky-linkage (linkage-section items remaining allocated between invocations) is enabled.

  • TRUNC

    Numeric data items are truncated according to their PICTURE clauses.

    While still supported, this may well be removed in the future and should not be used. See GCCOMP and GNUCOBOL instead:

  • OCCOMP

    The size of a COMP <item> is determined according to the GnuCOBOL scheme, where for a PICTURE of length:

    • 1 - 2

      <item> = 1 byte

    • 3 - 4

      <item> = 2 bytes

    • 5 - 9

      <item> = 4 bytes

    • 10 - 18

      <item> = 8 bytes

  • OPENCOBOL

    GnuCOBOL is compiling the source unit.

10.1.6 Locating Copybooks

The GnuCOBOL compiler will attempt to locate copybooks by searching for them in the following folders. The search will occur in the sequence shown below, and will terminate once a copybook is found.

  1. The folder named as the <library-name-1> on the COPY statement ( 3.2 COPY).

  2. The folder in which the program being compiled resides.

  3. The folder named on the -I switch.

  4. Each of the folders named on the COB_CPY_DIR compilation-time environment variable ( 10.1.4 Compilation Time Environment Variables) in order of presentation.

  5. Each of the folders named on the COBCPY compilation-time environment variable ( 10.1.4 Compilation Time Environment Variables) in order of presentation.

    A single folder may be named or multiple folders may be specified, separated by a system-appropriate delimiter character. When multiple folders are specified, they will be searched in the order they are named on the environment variable.

    If the GnuCOBOL compiler you are using was built to utilize a native Windows environment, use a semicolon (’;‘) as the delimiter character.

    If, however, the GnuCOBOL compiler was built for a Unix, OSX or Linux environment, or was built for a Windows environment utilizing either the Cygwin or MinGW Unix emulators, use a colon character (’:‘) as the delimiter.

  6. For v1.1 only, the single folder specified on the COB_COPY_DIR environment variable. (If not defined, for order see results of ‘cobc –info’).

As each of the above folders is searched for a copybook — COPY <XXXXXXXX>., for example — the GnuCOBOL compiler will attempt to locate the copybook file by any of the following names, in the sequence shown:

  • <XXXXXXXX>.CPY

  • <XXXXXXXX>.CBL

  • <XXXXXXXX>.COB

  • <XXXXXXXX>.cpy

  • <XXXXXXXX>.cbl

  • <XXXXXXXX>.cob

  • <XXXXXXXX>

The COPY statement is case-sensitive on UNIX systems; COPY copybookname and COPY COPYBOOKNAME will both fail to locate the CopyBookName copybook on a UNIX system.

Windows implementations of GnuCOBOL may, or may not, be similarly case sensitive with regard to copybook names, depending upon the Windows version and GnuCOBOL build options — it is safest to simply treat the COPY command as case-sensitive in all environments.

It is possible, however, to automatically cause all COPY statements to “fold” the names of all copybooks to upper-case by specifying the -ffold-copy switch with the upper option (i.e. --fold-copy=upper) to the GnuCOBOL compiler. Similarly, names could be folded to lower-case by using the lower option (i.e. --fold-copy=lower. If copybook libraries are maintained entirely using upper- or lower-case file names and extensions, either of these options will allow copybooks to be found regardless of how the programmer entered their names on COPY statements.

Case-folding may also be turned on and off within the program source code using the CDF >>SET statement ( 3.6 >>SET).

10.1.7 Compiler Configuration Files

GnuCOBOL uses compiler configuration files to define various options that will control the compilation process. These configuration files are specified using the -conf switch compilation switch and are found in the folder defined by the COB_CONFIG_DIR compilation-time environment variable ( 10.1.4 Compilation Time Environment Variables).

If this is not defined under *nix it will default to /usr/local/share/gnucobol/config.

The following is a verbatim listing of the default configuration file (the one used if you don’t specify the -conf switch), just to show you the types of settings that may appear and taken from v3.1.2 :

# GnuCOBOL compiler configuration
#
# Copyright (C) 2001-2012, 2014-2020 Free Software Foundation, Inc.
# Written by Keisuke Nishida, Roger While, Simon Sobisch, Edward Hart,
# Ron Norman
#
# This file is part of GnuCOBOL.
#
# The GnuCOBOL compiler is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# GnuCOBOL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GnuCOBOL.  If not, see <https://www.gnu.org/licenses/>.


# Value: any string
name: "GnuCOBOL"

# Value: enum
standard-define                       0
#        CB_STD_GC = 0,
#        CB_STD_MF,
#        CB_STD_IBM,
#        CB_STD_MVS,
#        CB_STD_BS2000,
#        CB_STD_ACU,
#        CB_STD_85,
#        CB_STD_2002,
#        CB_STD_2014

# Value: int
tab-width:                    8
text-column:                  72
# Maximum word-length for COBOL words / Programmer defined words
# Be aware that GC checks the word length against COB_MAX_WORDLEN
# first (currently 63)
word-length:                  63

# Maximum literal size in general
literal-length:                       8191

# Maximum numeric literal size (absolute maximum: 38)
numeric-literal-length:               38

# Maximum number of characters allowed in the character-string (max. 255)
pic-length:                   255

# Default assign type
# Value: 'dynamic', 'external'
assign-clause:                        dynamic

# If yes, file names are resolved at run time using
# environment variables.
# For example, given ASSIGN TO "DATAFILE", the file name will be
#  1. the value of environment variable 'DD_DATAFILE' or
#  2. the value of environment variable 'dd_DATAFILE' or
#  3. the value of environment variable 'DATAFILE' or
#  4. the literal "DATAFILE"
# If no, the value of the assign clause is the file name.
#
filename-mapping:             yes

# Alternate formatting of numeric fields
pretty-display:                       yes

# Allow complex OCCURS DEPENDING ON
complex-odo:                  no

# Allow REDEFINES to other than last equal level number
indirect-redefines:           no

# Binary byte size - defines the allocated bytes according to PIC
# Value:         signed  unsigned  bytes
#                ------  --------  -----
# '2-4-8'        1 -  4    same        2
#                5 -  9    same        4
#               10 - 18    same        8
#
# '1-2-4-8'      1 -  2    same        1
#                3 -  4    same        2
#                5 -  9    same        4
#               10 - 18    same        8
#
# '1--8'         1 -  2    1 -  2      1
#                3 -  4    3 -  4      2
#                5 -  6    5 -  7      3
#                7 -  9    8 -  9      4
#               10 - 11   10 - 12      5
#               12 - 14   13 - 14      6
#               15 - 16   15 - 16      7
#               17 - 18   17 - 18      8
#
binary-size:                  1-2-4-8

# Numeric truncation according to ANSI
binary-truncate:              yes

# Binary byte order
# Value: 'native', 'big-endian'
binary-byteorder:             big-endian

# Allow larger REDEFINES items
larger-redefines-ok:          no

# Allow certain syntax variations (eg. REDEFINES position)
relax-syntax-checks:          no

# Allow zero length reference-modification
# (only checked with active EC-BOUND-REF-MOD)
ref-mod-zero-length:          yes

# Perform type OSVS - If yes, the exit point of any currently
# executing perform is recognized if reached.
perform-osvs:                 no

# Compute intermediate decimal results like IBM OSVS
arithmetic-osvs:              no

# MOVE like IBM (mvc); left to right, byte by byte
move-ibm:                     no

# SELECT RELATIVE KEY and ASSIGN fields must be in WORKING-STORAGE
select-working:               no

# LOCAL-STORAGE SECTION implies RECURSIVE attribute
local-implies-recursive:              no

# If yes, LINKAGE SECTION items remain allocated
# between invocations.
sticky-linkage:                       no

# If yes, allow non-matching level numbers
relax-level-hierarchy:                no

# If yes, evaluate constant expressions at compile time
constant-folding:             yes

# Allow Hex 'F' for NUMERIC test of signed PACKED DECIMAL field
hostsign:                     no

# If yes, set WITH UPDATE clause as default for ACCEPT dest-item,
# except if WITH NO UPDATE clause is used
accept-update:                        no

# If yes, set WITH AUTO clause as default for ACCEPT dest-item,
# except if WITH TAB clause is used
accept-auto:                  no

# If yes, DISPLAYs and ACCEPTs are, by default, done on the CRT (i.e., using
# curses).
console-is-crt:                       no

# If yes, allow redefinition of the current program's name. This prevents its
# use in a prototype-format CALL/CANCEL statement.
program-name-redefinition:    yes

# If yes, NO ECHO/NO-ECHO/OFF is the same as SECURE (hiding input with
# asterisks, not spaces).
no-echo-means-secure:         no

# If yes, the first item in a field screen ACCEPT/DISPLAY (e.g. DISPLAY x UPON
# CRT) is located after the previous ACCEPT/DISPLAY (as though LINE 0 COL 0 had
# been specified).
line-col-zero-default:                yes

# If yes, DISPLAY SPACES acts as ERASE EOS, DISPLAY X"01" acts as ERASE EOL,
# DISPLAY X"02" acts as BLANK SCREEEN and DISPLAY X"07" acts as BELL. Note
# DISPLAY LOW-VALUE is excluded from this; it will always just position the
# cursor.
display-special-fig-consts:   no

# If yes, COMP-1 is a signed 16-bit integer and any PICTURE clause is ignored.
binary-comp-1:                        no

# If yes, POINTER is handled as BINARY-DOUBLE UNSIGNED instead of its own class
numeric-pointer:              no

# auto-adjust to zero like MicroFocus does
move-non-numeric-lit-to-numeric-is-zero: no

# If yes, implicitly define a variable for an ASSIGN DYNAMIC which does not
# match an existing data item.
implicit-assign-dynamic-var:  yes

# What rules to apply to SCREEN SECTION items clauses
screen-section-rules:         gc

# Whether DECIMAL-POINT IS COMMA has effect in XML/JSON GENERATE
dpc-in-data:                  xml

# Dialect features
# Value: 'ok', 'warning', 'archaic', 'obsolete', 'skip', 'ignore', 'error',
#        'unconformable'

alter-statement:                      obsolete
comment-paragraphs:                   obsolete
call-overflow:                                archaic
data-records-clause:                  obsolete
debugging-mode:                               ok
use-for-debugging:                    ok
listing-statements:                   skip    # may be a user-defined word
title-statement:                      skip    # may be a user-defined word
entry-statement:                      ok
goto-statement-without-name:          obsolete
label-records-clause:                 obsolete
memory-size-clause:                   obsolete
move-noninteger-to-alphanumeric:      error
move-figurative-constant-to-numeric:  archaic
move-figurative-space-to-numeric:     error
move-figurative-quote-to-numeric:     obsolete
multiple-file-tape-clause:            obsolete
next-sentence-phrase:                 archaic
odo-without-to:                               warning
padding-character-clause:             obsolete
section-segments:                     ignore
stop-literal-statement:                       obsolete
stop-identifier-statement:            obsolete
same-as-clause:                               ok
type-to-clause:                               ok
usage-type:                                   ok
synchronized-clause:                  ok
special-names-clause:                 ok
top-level-occurs-clause:              ok
value-of-clause:                      obsolete
numeric-boolean:                      ok
hexadecimal-boolean:                  ok
national-literals:                    ok
hexadecimal-national-literals:                ok
national-character-literals:          warning
# TO-DO: Add separate config option for H"..." to be unsupported,numeric,non-numeric(acu)
acu-literals:                         unconformable
hp-octal-literals:                    unconformable
word-continuation:                    warning
not-exception-before-exception:               ok
accept-display-extensions:            ok
renames-uncommon-levels:              ok
symbolic-constant:                    ok
constant-78:                          ok
constant-01:                          ok
perform-varying-without-by:           ok
reference-out-of-declaratives:                warning
program-prototypes:                   ok
call-convention-mnemonic:             ok
call-convention-linkage:              ok
numeric-value-for-edited-item:                ok
incorrect-conf-sec-order:             ok
define-constant-directive:            archaic
free-redefines-position:              warning
records-mismatch-record-clause        warning
record-delimiter:                     ok
sequential-delimiters:                        ok
record-delim-with-fixed-recs:         ok
missing-statement:                    warning
zero-length-literals:                 ok
xml-generate-extra-phrases:           ok
continue-after:                               ok
goto-entry:                           warning
assign-variable:                      ok
assign-using-variable:                        ok
assign-ext-dyn:                               ok
assign-disk-from:                     ok
vsam-status:                          ignore

# use complete word list; synonyms and exceptions are specified below
reserved-words:               default

# not-reserved:
# Value: Word to be taken out of the reserved words list
not-reserved: TERMINAL
# reserved:
#   Entries of the form word-1=word-2 define word-1 as an alias for default
# reserved word word-2. No spaces are allowed around the equal sign.
reserved:     AUTO-SKIP=AUTO
reserved:     AUTOTERMINATE=AUTO
reserved:     BACKGROUND-COLOUR=BACKGROUND-COLOR
reserved:     BEEP=BELL
reserved:     BINARY-INT=BINARY-LONG
reserved:     BINARY-LONG-LONG=BINARY-DOUBLE
reserved:     CELLS=CELL
reserved:     COLOURS=COLORS
reserved:     EMPTY-CHECK=REQUIRED
reserved:     EQUALS=EQUAL
reserved:     FOREGROUND-COLOUR=FOREGROUND-COLOR
reserved:     HIGH-VALUES=HIGH-VALUE
reserved:     INITIALISE=INITIALIZE
reserved:     INITIALISED=INITIALIZED
reserved:     LENGTH-CHECK=FULL
reserved:     LOW-VALUES=LOW-VALUE
reserved:     ORGANISATION=ORGANIZATION
reserved:     PIXELS=PIXEL
reserved:     SYNCHRONISED=SYNCHRONIZED
reserved:     TIMEOUT=TIME-OUT
reserved:     VALUES=VALUE
reserved:     ZEROES=ZERO
reserved:     ZEROS=ZERO

10.2 Running Programs

Once GnuCOBOL programs have been compiled into either directly-executable programs (created via the -x switch) or dynamically-loadable libraries (created via the -m switch), those programs may be executed from any shell environment. The exact manner in which the two are executed will differ, as described in the upcoming sections.

10.2.1 Direct Execution

GnuCOBOL programs compiled with the -x switch will be generated as directly-executable programs. For example, a native Windows or Windows/MinGW build of GnuCOBOL will generate an .exe file when the -x switch switch is specified to the compiler.

On Unix, OSX, or Windows/Cygwin builds, the -x switch switch will generate an executable binary file, usually with no particular extension unless one is explicitly requested of the compiler via the -o switch.

On a UNIX system this means the programs may be executed from a command shell such as bash, csh, ksh and so forth. When a GnuCOBOL program runs on a Windows system, it runs within a console window (i.e. cmd.exe). OSX versions of GnuCOBOL programs run within a terminal.app window.

Interactions between the program and the user will take place using the standard input, standard output and standard error streams. Any screen section I/O performed by the program will take place within the terminal window.

Direct program execution syntax is [<path>]<program> [<arguments>].

For example:

/usr/local/printaccount ACCT=6625378

or

C:\\Users\\Me\\Documents\\Programs\\printaccount.exe ACCT=6625378

10.2.2 Executing Dynamically-Loadable Libraries

As discussed previously, dynamically-loadable libraries are created via the compiler’s -m switch. Once so created, the program(s) in these libraries are executed from the command line (via the GnuCOBOL cobcrun utility), or as dynamically-loadable subprograms.

10.2.2.1 cobcrun - Command-line Execution

It is possible to generate executable modules for all GnuCOBOL programs, not just subprograms, by choosing to use the -m switch option to specify the loader output format, even for main programs.

Some may prefer to compile their GnuCOBOL main programs into these dynamically-loadable modules in the interests of using the same general compilation command for all programs without having to think “Is it a main program or a subprogram?”.

Main programs compiled in this manner should be executed as follows:

[\ *path*\ ]cobcrun \ *program*\  [\ *arguments*\ ]

Do not specify the .so or .dll extension on the program name. The program value must exactly match the primary entry-point name of the main program (including upper- and lower-case letters), unless you are planning on using Call Folding ( 10.2.2.2 Dynamically Loaded Subprograms).

The general usage and syntax of cobcrun is as follows as issued by running cobcrun -h (or –help) :

GnuCOBOL module loader

Usage: cobcrun [options] PROGRAM [parameter ...]
  or:  cobcrun options

Options:
  -h, -help                      display this help and exit
  -V, -version                   display cobcrun and runtime version and exit
  -i, -info                      display runtime information (build/environment)
  -v, -verbose                   display extended output with --info
  -c <file>, -config=<file>      set runtime configuration from <file>
  -r, -runtime-config            display current runtime configuration
                                 (value and origin for all settings)
  -M <module>, -module=<module>  set entry point module name and/or load path
                                 where -M module prepends any directory to the
                                 dynamic link loader library search path
                                 and any basename to the module preload list
                                 (COB_LIBRARY_PATH and/or COB_PRELOAD)

Here are two examples of using cobcrun. First, on a Unix, OSX or Windows/Cygwin system:
cd /usr/local
cobcrun printaccount acct=6625378

Or, on a Native Windows or Windows/MinGW system:
cd C:\Users\Me\Documents\Programs
cobcrun printaccount.exe acct=6625378

Note how the cobcrun command does not allow a path to be specified with the program name — the directory in which the programs dynamically loadable module exists must either be the current directory or must be defined in the current PATH.

10.2.2.2 Dynamically Loaded Subprograms

Dynamically-loaded subprograms are executed (from a COBOL syntax point of view) just like any other subprograms. What makes them unique, however, is that they are loaded into memory only when they are actually used the first time during the execution of a program.

When a dynamically-loadable module needs to be loaded (because it is not already in memory from a previous subprogram execution), the dynamically-loadable library will be sought by libcob in each directory named in the library specified by the run-time environment variable will be searched and if not found then. Finally, if it still cannot be located, execution will be terminated with an error message (libcob: Cannot find module ‘xxxxxxxx’). For speed performance purposes all such should therefore be stored within the directories pointed to by the environment variable run-time environment variable.

The process of locating dynamically-loadable modules is case sensitive on UNIX systems; CALL "dynsub" and CALL "DYNSUB" will both fail to locate the DynSub.so library on a UNIX system.

Windows implementations of GnuCOBOL may, or may not, be similarly case sensitive with regard to library names, depending upon the Windows version and GnuCOBOL build options — it is safest to simply treat library names as case sensitive in all environments.

It is possible, however, to automatically cause all library names to ‘fold’ to upper-case by specifying the -ffold-call switch with the “upper” option (i.e. --fold-call=upper) to the GnuCOBOL compiler. Similarly, library names could be folded to lower-case by using the “lower” option (i.e. --fold-call=lower. If libraries are maintained entirely using upper- or lower-case file names, either of these options will allow libraries to be found regardless of how the programmer entered their names on CALL statements.

11 Sub-Programming, for a complete discussion of sub-programming.

10.2.3 Run Time Environment Variables

The following is a list of the various environment variables that can play a role in the execution of GnuCOBOL programs.

  • COB_DISPLAY_WARNINGS

    If set to a value of ‘Y‘, any run-time warnings (such as noting the implicit closing of open files when a GOBACK statement ( 7.8.21 GOBACK) or STOP statement ( 7.8.44 STOP) with the RUN option is executed) will be displayed. Any other value for this environment variable (including not setting the variable at all) will suppress such messages.

  • COB_LIBRARY_PATH

    At runtime, GnuCOBOL will attempt to locate and load any application dynamically loadable libraries used this variable that points to the directories specified, if it wasn’t found there, using the PATH environment variable.

  • COB_LOAD_CASE

    If set to either UPPER or LOWER, this environment variable will internally convert referenced entry point names to either upper- or lower-case before initiating searches for dynamically loadable modules. The UPPER and LOWER values of the environment variable are actually case insensitive.

  • COB_PHYSICAL_CANCEL

    If set to ‘Y‘, ‘y‘ or ‘1‘, a CANCEL statement ( 7.8.6 CANCEL) will physically unload a subprogram dynamically loadable module. If set to anything else, a CANCEL statement ( 7.8.6 CANCEL) logically unloads a module so that subsequent use will re-initialize the module as if it had actually been reloaded, but the overhead of actually reloading the module will be avoided.

  • COB_PRE_LOAD

    If set to any non-null value, this variable will cause all dynamically loadable libraries to be loaded when the program begins execution (rather than searching for and loading the module upon first use).

  • COB_SET_DEBUG

    If a USE FOR DEBUGGING ( 7.5 DECLARATIVES) section exists, the code within it will be disabled unless this environment variable is set to a value of ‘Y‘, ‘y‘ or ‘1‘.

  • COB_SET_TRACE

    If the -ftrace switch (trace procedures) or -ftraceall switch (trace procedures and statements) was used when the program was compiled, setting this environment variable to a value of ‘Y‘ will activate the trace at the point the program begins execution. Setting this environment variable to any other value (or never setting it to ANY value) will disable tracing. Tracing, if configured by one of the two switches described above, can also be controlled via the the READY TRACE statement ( 7.8.33 READY TRACE) and RESET TRACE statement ( 7.8.35 RESET TRACE). If COB_SET_TRACE is set to Y, then tracing will always occur regardless of the presence of READY TRACE or RESET TRACE so in effect they will have no action on program execution.

  • COB_SCREEN_ESC

    If set to any non-blank value, this variable allows a ACCEPT data-item statement ( 7.8.1.4 ACCEPT data-item) to detect the Esc key.

  • COB_SCREEN_EXCEPTIONS

    Setting this variable to any non-blank value will allow the ACCEPT data-item statement ( 7.8.1.4 ACCEPT data-item) to detect the pressing of the Esc, PgUp and PgDn keys.

  • COB_SORT_MEMORY

    The value of this variable (an integer) will be used to define how much memory will be allocated for use in sorting. If the value is 1048576 or greater, that value will be used “as is” as the amount of memory (in bytes) to allocate. If the value is less than 1048576, the value will specify how many MB of memory will be allocated. The default sort memory amount is 128 MB.

  • COB_SWITCH_n

    (n=0 to 15); These environment variables correspond to SWITCH-0 through SWITCH-15, defined in the SPECIAL-NAMES ( 5.1.3 SPECIAL-NAMES) paragraph. Setting them to ON will activate them; any other value turns them off.

  • COB_SYNC

    If set to a value of upper- or lower-case ‘p‘, this variable will force a file commit every time a file is written to (ensuring that data is immediately written to the file rather than retained in memory until a future commit occurs). This will slow-down update access to files, but will provide for better integrity in the event of a program failure.

  • COB_TRACE_FILE

    If set to any non-null value, this environment variable specifies the file to which all -ftrace switch and -ftraceall switch output will be written. If this is NOT set to a value, all -ftrace switch and -ftraceall switch output will be written to STDERR, where it may be piped via a “2> filename” on the command that executes the program.

  • DB_HOME

    If your GnuCOBOL build uses the Berkeley Database (BDB) package, use this environment variable to specify the folder in which the lock management files to be associated with all non-SORT files opened by the program will be stored. ORGANIZATION INDEXED ( 5.2.1.4 ORGANIZATION INDEXED) files will also have their data file allocated in the folder pointed to by this environment variable, if it exists.. Having this variable defined will activate record locking features on the READ statement ( 7.8.32 READ), REWRITE statement ( 7.8.37 REWRITE) and WRITE statement ( 7.8.52 WRITE). Even with DB_HOME, locking will not work with ORGANIZATION SEQUENTIAL ( 5.2.1.1 ORGANIZATION SEQUENTIAL), ORGANIZATION LINE SEQUENTIAL ( 5.2.1.2 ORGANIZATION LINE SEQUENTIAL) or ORGANIZATION RELATIVE files with GnuCOBOL builds created for Windows/MinGW. ORGANIZATION INDEXED locks will work with Windows/MinGW + BDB and all locks will work for all file organizations with UNIX GnuCOBOL builds.

  • PATH

    The GnuCOBOL “bin” directory should be defined in the PATH.

  • TMPDIR

  • TMP

  • TEMP

    One of these environment variables must be set to a directory/folder appropriate to create temporary files in. They will be checked in the order shown. This will be used by the SORT statement ( 7.8.42 SORT) and MERGE statement ( 7.8.27 MERGE) to create temporary work files. You may also use this folder for any temporary files your application may require.

Also used during execution of programs is runtime.cfg also found in /usr/local/share/gnucobol/configfor *nix and this file can also be changed to match your environment if needed. When viewing, note the Default settings.

10.2.3.1 General instructions

The initial runtime.cfg file is found in the  $COB_CONFIG_DIR/config
(  COB_CONFIG_DIR  defaults to  installdir/gnucobol  ).
The environment variable  COB_RUNTIME_CONFIG  may define a different runtime
configuration file to read.

If settings are included in the runtime environment file multiple times
then the last setting value is used, no warning occurs.

Settings via environment variables always take precedence over settings
that are given in runtime configuration files. And the environment is
checked after completing processing of the runtime configuration file(s)

All values set to string variables or environment variables are checked
for  ${envvar}  and replacement is done at the time of the setting.

Any environment variable may be set with the directive  setenv  .
Example:  setenv COB_LIBRARY_PATH ${LD_LIBRARY_PATH}

Any environment variable may be unset with the directive  unsetenv
(one var per line).
Example:  unsetenv COB_LIBRARY_PATH

Runtime configuration files can include other files with the directive
include.
Example:  include my-runtime-configuration-file

To include another configuration file only if it is present use the directive
includeif.
You can also use  ${envvar}  inside this.
Example:  includeif ${HOME}/mygc.cfg

If you want to reset a parameter to its default value use:
   reset parametername

Most runtime variables have boolean values, some are switches, some have
string values, integer values and some are size values.
The boolean values will be evaluated as following:
      to true:          1, Y, ON, YES, TRUE  (no matter of case)
      to false:         0, N, OFF
A 'size' value is an integer optionally followed by K, M, or G for kilo, mega
or giga.

For convenience a parameter in the runtime.cfg file may be defined by using
either the environment variable name or the parameter name.
In most cases the environment variable name is the parameter name (in upper
case) with the prefix  COB_  .

Note: If you want to *slightly* speed up a program's startup time, remove all
      of the comments from the actual real configuration file that is processed

10.2.3.2 General Environment

 Environment name:  COB_DISABLE_WARNINGS
   Parameter name:  disable_warnings
          Purpose:  turn off runtime warning messages
             Type:  boolean
          Default:  false
          Example:  DISABLE_WARNINGS  TRUE

 Environment name:  COB_ENV_MANGLE
   Parameter name:  env_mangle
          Purpose:  names checked in the environment would get non alphanumeric
                    change to '_'
             Type:  boolean
          Default:  false
          Example:  ENV_MANGLE  TRUE

 Environment name:  COB_SET_DEBUG
   Parameter name:  debugging_mode
          Purpose:  to enable USE ON DEBUGGING procedures that were active
                    during compile-time because of WITH DEBUGGING MODE,
                    otherwise the code generated will be skipped
             Type:  boolean
          Default:  false
          Example:  COB_SET_DEBUG  1

 Environment name:  COB_SET_TRACE
   Parameter name:  set_trace
          Purpose:  to enable COBOL trace feature
             Type:  boolean
          Default:  false
          Example:  SET_TRACE  TRUE

 Environment name:  COB_TRACE_FILE
   Parameter name:  trace_file
          Purpose:  to define where COBOL trace output should go
             Type:  string
          Default:  stderr
          Example:  TRACE_FILE  ${HOME}/mytrace.log

 Environment name:  COB_TRACE_FORMAT
   Parameter name:  trace_format
          Purpose:  to define format of COBOL trace output
             Type:  string
          Default:  "%P %S Line: %L"
                    %P is replaced by Program-Id/Function-Id minimal length 29
                       with prefix
                    %I is replaced by Program-Id/Function-Id variable length,
                       without prefix
                    %L is replaced by Line number, right justified, length 6
                    %S is replaced by statement type and name
                    %F is replaced by source file name
          Example:  TRACE_FORMAT  "Line: %L %S"
             Note:  format of GC2.2 and older:
                    "PROGRAM-ID: %I    Line: %L        %S"

For v4.0+
 Environment name:  COB_TRACE_IO
  Parameter name:  trace_io
         Purpose:  define if I/O details should be added to trace
            Type:  boolean
         Default:  false
         Example:  TRACE_IO true

 Environment name:  COB_DUMP_FILE
   Parameter name:  dump_file
          Purpose:  to define where COBOL dump output should go
             Note:  The -fdump=all compile option prepares for dump
             Type:  string       : $$ is replaced by process id
          Default:  stderr
          Example:  DUMP_FILE  ${HOME}/mytrace.log

 Environment name:  COB_DUMP_WIDTH
   Parameter name:  dump_width
          Purpose:  to define COBOL dump line length
             Type:  integer
          Default:  100
          Example:  dump_width 120

For v4.0+
 Environment name:  COB_STATS_RECORD
  Parameter name:  stats_record
         Purpose:  define if I/O statistics should be written
            Type:  boolean
         Default:  false
         Example:  STATS_RECORD true

For v4.0+
 Environment name:  COB_STATS_FILE
  Parameter name:  stats_file
         Purpose:  to define where COBOL I/O statistics should be written
                   The file is appended to
            Type:  string
         Default:  stderr
         Example:  STATS_FILE  ${HOME}/mystats.txt

 Environment name:  COB_CURRENT_DATE
   Parameter name:  current_date
          Purpose:  specify an alternate Date/Time to be returned to ACCEPT
                    clauses this is used for testing purposes or to tweak
                    a missing offset partial setting is allowed
             Type:  numeric string in format YYYYDDMMHH24MISS or date string
          Default:  the operating system date is used
          Example:  COB_CURRENT_DATE "2016/03/16 16:40:52"
                    current_date YYYYMMDDHHMMSS+01:00

10.2.3.3 Call Environment

Environment name:  COB_LIBRARY_PATH
  Parameter name:  library_path
         Purpose:  paths for dynamically-loadable modules
            Type:  string
            Note:  the default paths .:/installpath/extras are always
                   added to the given paths
         Example:  LIBRARY_PATH    /opt/myapp/test:/opt/myapp/production

Environment name:  COB_PRE_LOAD
  Parameter name:  pre_load
         Purpose:  modules that are loaded during startup, can be used
                   to CALL COBOL programs or C functions that are part
                   of a module library
            Type:  string
            Note:  the modules listed should NOT include extensions, the
                   runtime will use the right ones on the various platforms,
                   COB_LIBRARY_PATH is used to locate the modules
         Example:  PRE_LOAD      COBOL_function_library:external_c_library

Environment name:  COB_LOAD_CASE
  Parameter name:  load_case
         Purpose:  resolve ALL called program names to UPPER or LOWER case
            Type:  Only use  UPPER  or  LOWER
         Default:  if not set program names in CALL are case sensitive
         Example:  LOAD_CASE  UPPER

Environment name:  COB_PHYSICAL_CANCEL
  Parameter name:  physical_cancel
         Purpose:  physically unload a dynamically-loadable module on CANCEL,
                   this frees some RAM and allows the change of modules during
                   run-time but needs more time to resolve CALLs (both to
                   active and not-active programs)
           Alias:  default_cancel_mode, LOGICAL_CANCELS (0 = yes)
            Type:  boolean (evaluated for true only)
         Default:  false
         Example:  PHYSICAL_CANCEL  TRUE

10.2.3.4 File I/O

 Environment name:  COB_VARSEQ_FORMAT
   Parameter name:  varseq_format
          Purpose:  declare format used for variable length sequential files
                    - different types and lengths precede each record
                    - 'length' is the data length, does not include the prefix
             Type:  0   means 2 byte record length (big-endian) + 2 NULs
                    1   means 4 byte record length (big-endian)
                    2   means 4 byte record length (local machine int)
                    3   means 2 byte record length (big-endian)
          Default:  0
          Example:  VARSEQ_FORMAT 1

For v4.0+
 Environment name: COB_VARREL_FORMAT
  Parameter name: varrel_format
         Purpose: declare format to be used for variable length relative files
            Type: gc  means 'size_t' record length (local machine) precedes
                            maxiumum length data record
                  mf  means file is in Micro Focus format
                 b32  means Big-Endian 32-bit 'int' record length precedes data
                 b64  means Big-Endian 64-bit 'int' record length precedes data
                 l32  means Little-Endian 32-bit 'int' record length precedes data
                 l64  means Little-Endian 64-bit 'int' record length precedes data
         Default: gc
            NOTE: 'gc' results in files which cannot be used if copied between
                       machines of different hardware archeticture
         Example: VARREL_FORMAT mf

For v4.0+
 Environment name:  COB_FIXREL_FORMAT
  Parameter name:  fixrel_format
         Purpose:  declare format to be used for fixed length relative
                   files (different types and lengths preceding each record)
            Type:  b32 means 4 byte record length (big-endian)
                   l32 means 4 byte record length (little-endian)
                   b64 means 8 byte record length (big-endian)
                   l64 means 8 byte record length (little-endian)
                   mf  means Micro Focus default
                   gc  means GnuCOBOL default (local 'size_t')
         Default:  gc  fixed size with no record length prefix
         Example:  FIXREL_FORMAT B32

For v4.0+
 Environment name: COB_VARFIX_FORMAT
  Parameter name: varfix_format
         Purpose: declare format to be used for fixed length relative files
            Type: gc  means 'size_t' record length (local machine) precedes
                            fixed length data record
                  mf  means file is in Micro Focus format
                 b32  means Big-Endian 32-bit 'int' record length precedes data
                 b64  means Big-Endian 64-bit 'int' record length precedes data
                 l32  means Little-Endian 32-bit 'int' record length precedes data
                 l64  means Little-Endian 64-bit 'int' record length precedes data
         Default: gc
            NOTE: 'gc' results in files which cannot be used if copied between
                       machines of different hardware archeticture
         Example: VARFIX_FORMAT mf

 Environment name:  COB_FILE_PATH
   Parameter name:  file_path
          Purpose:  define default location where data files are stored
             Type:  file path directory
          Default:  .  (current directory)
          Example:  FILE_PATH ${HOME}/mydata

 Environment name:  COB_LS_FIXED
   Parameter name:  ls_fixed
          Purpose:  Defines if LINE SEQUENTIAL files should be fixed length
                    (or variable, by removing trailing spaces)
            Alias:  STRIP_TRAILING_SPACES  (0 = yes)
             Type:  boolean
          Default:  false
          Example:  LS_FIXED TRUE

 Environment name:  COB_LS_NULLS
   Parameter name:  ls_nulls
          Purpose:  Defines for LINE SEQUENTIAL files what to do with data
                    which is not DISPLAY type.  This could happen if a LINE
                    SEQUENTIAL record has BINARY/COMP data fields in it.
                    For v4.0+ (may change before its release candidate)
                    This option is only for GnuCOBOL format files
             Type:  boolean
          Default:  false
             Note:  The TRUE setting will insert a null character x"00" before
                    those values to escape them, and redo on read-in.
          Example:  LS_NULL = TRUE

For v4.0+
Environment name:  COB_LS_SPLIT
  Parameter name:  ls_split
         Purpose:  Defines for LINE SEQUENTIAL files what to do when a record
                   is longer than the program handles. If 'ls_split=true' then
                   the data is returned as multiple records
            Type:  boolean
         Default:  false
                   The record is truncated and the file skips to the next LF
         Example:  LS_SPLIT = TRUE

For v4.0+
Environment name:  COB_LS_VALIDATE
  Parameter name:  ls_validate
         Purpose:  Defines for LINE SEQUENTIAL files that the data should be
                   validated. If any record has non-DISPLAY characters then
                   an error status of 34 is returned
                   For v4.0+ (may change before its release candidate)
                   This option is only for GnuCOBOL format files
            Type:  boolean
         Default:  true
            Note:  The TRUE setting does data validation
                   The FALSE setting lets non-DISPLAY characters be written
                   If LS_NULLS is set, then LS_VALIDATE is not checked
         Example:  LS_VALIDATE = FALSE

For v4.0+ (may be replaced before its release candidate)
 Environment name: COB_MF_FILES
  Parameter name: mf_files
         Purpose:  Declares that all files in the program should be in
                   Micro Focus compatible format.
            Type:  boolean (evaluated for true only)
         Default:  false
         Example:  mf_files True

For v4.0+ (may be replaced before its release candidate)
 Environment name:  COB_MF_LS_NULLS
  Parameter name:  mf_ls_nulls
         Purpose:  Defines for Micro Focus compatible LINE SEQUENTIAL files
                   what to do with data which is not DISPLAY type.
                   This could happen if a LINE SEQUENTIAL record has
                   BINARY/COMP data fields in it.
            Type:  boolean
         Default:  true
            Note:  The TRUE setting will handle files that contain COMP data
                   in a similar manner to the method used by Micro Focus COBOL
         Example:  MF_LS_NULLS = TRUE

For v4.0+ (may be replaced before its release candidate)
 Environment name:  COB_MF_LS_INSTAB
   Parameter name:  mf_ls_instab
          Purpose:  Defines for LINE SEQUENTIAL files that multiple spaces
                    should be replaced by a TAB character, assuming a 'tab set'
                    value of 8. Each TAB means to skip to the next column that
                    is a multiple of 8
                    Similar to Micro Focus INSERTTAB=ON option
             Type:  boolean
          Default:  false
          Example:  MF_LS_INSTAB = TRUE

For v4.0+ (may be replaced before its release candidate)
 Environment name:  COB_MF_LS_SPLIT
  Parameter name:  mf_ls_split
         Purpose:  Defines for Micro Focus compatible LINE SEQUENTIAL files what
                   to do when a record is longer than the program handles.
                   If 'mf_ls_split=true' then
                   the data is returned as multiple records
            Type:  boolean
         Default:  true
         Example:  MF_LS_SPLIT = FALSE

For v4.0+ (may be replaced before its release candidate)
 Environment name:  COB_MF_LS_VALIDATE
  Parameter name:  mf_ls_validate
         Purpose:  Defines for Micro Focus compatible LINE SEQUENTIAL files
                   that the data should be validated.
                   If any record has non-DISPLAY characters then
                   an error status of 34 is returned
            Type:  boolean
         Default:  false
            Note:  The TRUE setting does data validation
                   The FALSE setting lets non-DISPLAY characters be written
                   If MF_LS_NULLS is set, then MF_LS_VALIDATE is not checked
         Example:  MF_LS_VALIDATE = FALSE

For v4.0+
 Environment name:  COB_SHARE_MODE
  Parameter name:  share_mode
         Purpose:  Defines what file sharing option should be used
            Type:  -- choice of values ---
                   none - nothing overrides application code
                   read - files opened as SHARE READ ONLY
                   all  - files opened as SHARE ALL OTHERS
                   no   - files opened as SHARE NO OTHERS
         Default:  none
         Example:  share_mode = ALL

For v4.0+
 Environment name:  COB_RETRY_MODE
  Parameter name:  retry_mode
         Purpose:  Defines what I/O retry sharing option should be used
            Type:  --- choice of values ---
                   none    - nothing overrides application code
                   never   - I/O is never retried
                   forever - I/O will be retried until success
         Default:  none
         Example:  retry_mode = never

For v4.0+
 Environment name:  COB_RETRY_TIMES
  Parameter name:  retry_times
         Purpose:  Defines how many times I/O should be retried
            Type:  integer
         Default:  0
         Example:  retry_times = 10

For v4.0+
 Environment name:  COB_RETRY_SECONDS
  Parameter name:  retry_seconds
         Purpose:  Defines how many seconds I/O should be retried
            Type:  integer
         Default:  0
         Example:  retry_seconds = 6

For v4.0+
 Environment name:  COB_KEYCHECK
  Parameter name:  keycheck
         Purpose:  Must INDEXED file keys match COBOL SELECT exactly
            Type:  boolean
         Default:  true
         Example:  keycheck = off

 Environment name:  COB_SYNC
   Parameter name:  sync
          Purpose:  Should the file be synced to disk after each write/update
             Type:  boolean
          Default:  false
          Example:  SYNC: TRUE

 Environment name:  COB_SORT_MEMORY
   Parameter name:  sort_memory
          Purpose:  Defines how much RAM to assign for sorting data
                    if this size is exceeded the  SORT  will be done
                    on disk instead of memory
             Type:  size  but must be more than 1M
          Default:  128M
          Example:  SORT_MEMORY 64M

 Environment name:  COB_SORT_CHUNK
   Parameter name:  sort_chunk
          Purpose:  Defines how much RAM to assign for sorting data in chunks
             Type:  size  but must be within 128K and 16M
          Default:  256K
          Example:  SORT_CHUNK 1M

10.2.3.5 Screen I/O

Environment name:  COB_BELL
  Parameter name:  bell
         Purpose:  Defines how a request for the screen to beep is handled
            Type:  FLASH, SPEAKER, FALSE, BEEP
         Default:  BEEP
         Example:  BELL SPEAKER

Environment name:  COB_REDIRECT_DISPLAY
  Parameter name:  redirect_display
         Purpose:  Defines if DISPLAY output should be sent to 'stderr'
            Type:  boolean
         Default:  false
         Example:  redirect_display Yes

Environment name:  COB_SCREEN_ESC
  Parameter name:  screen_esc
         Purpose:  Enable handling of ESC key during ACCEPT
            Type:  boolean
         Default:  false
            Note:  is only evaluated if COB_SCREEN_EXCEPTIONS is active
         Example:  screen_esc Yes

Environment name:  COB_SCREEN_EXCEPTIONS
  Parameter name:  screen_exceptions
         Purpose:  enable exceptions for function keys during ACCEPT
            Type:  boolean
         Default:  false
         Example:  screen_exceptions Yes

Environment name:  COB_TIMEOUT_SCALE
  Parameter name:  timeout_scale
         Purpose:  specify translation in milliseconds for ACCEPT clauses
                   BEFORE TIME value / AFTER TIMEOUT
            Type:  integer
                   0 means 1000 (Micro Focus COBOL compatible), 1 means 100
                   (ACUCOBOL compatible), 2 means 10, 3 means 1
         Default:  0
         Example:  timeout_scale 3

Environment name:  COB_INSERT_MODE
  Parameter name:  insert_mode
         Purpose:  specify default insert mode for ACCEPT; 0=off, 1=on
            Type:  boolean
         Default:  false
            Note:  also sets the cursor type (if available)
         Example:  insert_mode Y

Environment name:  COB_MOUSE_FLAGS
 Parameter name:  mouse_flags
        Purpose:  specify which mouse events will be sent as function key
                  to the application during ACCEPT and how they will be
                  handled
           Type:  int (by bits)
        Default:  1
           Note:  0 disables the mouse cursor, any other value enables it,
                  any value containing 1 will enable internal handling (click
                  to position, double-click to enter).
                  See copy/screenio.cpy for list of events and their values.
          Alias:  MOUSE_FLAGS
        Example:  11 (enable internal handling => 1, left press => 2,
                      double-click => 8; 1+2+8=11)
Environment name:  COB_MOUSE_INTERVAL
 Parameter name:  mouse_interval
        Purpose:  specifies the maximum time (in thousands of a second)
                  that can elapse between press and release events for them
                  to be recognized as a click.
           Type:  int (0 - 166)
        Default:  100
           Note:  0 disables the click resolution (instead press + release
                  are recognized), also disables positioning by mouse click

Environment name:  COB_DISPLAY_PRINT_PIPE
 Parameter name:  display_print_pipe
        Purpose:  Defines command line used for sending output of
                  DISPLAY UPON PRINTER to (via pipe)
                  This is very similar to Micro Focus COBPRINTER
           Note:  Each executed DISPLAY UPON PRINTER statement causes a
                  new invocation of command-line (= new process start).
                  Each invocation receives the data referenced in
                  the DISPLAY statement and is followed by an
                  end-of-file condition.
                  COB_DISPLAY_PRINT_FILE, if set, takes precedence
                  over COB_DISPLAY_PRINT_PIPE.
          Alias:  COBPRINTER
           Type:  string
        Default:  not set
        Example:  print 'cat >>/tmp/myprt.log'

Environment name:  COB_DISPLAY_PRINT_FILE
 Parameter name:  display_print_file
        Purpose:  Defines file to be appended to by DISPLAY UPON PRINTER
           Note:  Each DISPLAY UPON PRINTER opens, appends and closes the file.
           Type:  string       : $$ is replaced by process id
        Default:  not set
        Example:  display_printer '/tmp/myprt.log'

Environment name:  COB_DISPLAY_PUNCH_FILE
 Parameter name:  display_punch_file
        Purpose:  Defines file to be created on first
                  DISPLAY UPON SYSPUNCH/SYSPCH
           Note:  The file will be only be closed on runtime exit.
           Type:  string       : $$ is replaced by process id
        Default:  not set
        Example:  display_punch './punch_$$.out'

Environment name:  COB_LEGACY
  Parameter name:  legacy
         Purpose:  keep behaviour of former runtime versions, currently only
                   for setting screen attributes for non input fields
            Type:  boolean
         Default:  not set
         Example:  legacy true

Environment name:  COB_EXIT_WAIT
  Parameter name:  exit_wait
         Purpose:  to wait on main program exit if an extended screenio
                   DISPLAY was issued without an ACCEPT following
            Type:  boolean
         Default:  true
         Example:  COB_EXIT_WAIT off

Environment name:  COB_EXIT_MSG
  Parameter name:  exit_msg
         Purpose:  string to display if COB_EXIT_WAIT is processed, set to '@w{}'
                   if no actual display but an ACCEPT should be done
            Type:  string
         Default:  'end of program, please press a key to exit' (localized)
         Example:  COB_EXIT_MSG '@w{}'

10.2.3.6 Report I/O

Environment name:  COB_COL_JUST_LRC
  Parameter name:  col_just_lrc
         Purpose:  If true, then COLUMN defined as LEFT, RIGHT or CENTER
                   will have the data justified within the field limits
                   If false, then the data is just copied into the column as is
            Type:  boolean
         Default:  TRUE
         Example:  col_just_lrc True

10.2.3.7 File I/O Environment Variables and/or dictionary file

GnuCOBOL 4.+ only!

Before a file is opened a check is done for environment variables that
may define various attributes of the file
First a check is made for attributes for files of the same ORGANIZATION
IX_OPTIONS for INDEXED, SQ_OPTIONS for SEQUENTIAL, RL_OPTIONS for RELATIVE
LS_OPTIONS for LINE SEQUENTIAL, LA_OPTIONS for LINE ADVANCING SEQUENTIAL
If none of these are present, it then checks for IO_OPTIONS

Then an additional check is done for IO_asgnmame where 'asgname' was
the ASSIGN EXTERNAL name used in the program

The environment variable (or dictionary file) may contain any of the
following keywords, separated by spaces and/or commas

You can specify just the keyword and it is assumed to mean set to true,
or no-keyword (or no_keyword or nokeyword) which means set to false,
or keyword=true or keyword=false.  The valid keywords are:
Keyword          Meaning
=========        ======================================================
type=xx          Set file organization where 'xx' is one of
                 IX = INDEXED, SQ = SEQUENTIAL, RL = RELATIVE
                 LS = LINE SEQUENTIAL, LA = LINE ADVANCING
mf               Set file to Micro Focus compatible format
gc               Set to original GnuCOBOL default format
recsz            The size for fixed size record file
maxsz            Maximum record size for variable length records
minsz            Minimum record size for variable length records
ls_nulls         Do NUL insertion before characters less than a SPACE,
                 Default: false
ls_validate      Validate data for LINE Sequential Files, Default: true
crlf             Lines end with CR LF (Windows format for text files)
lf               Lines end with LF (Unix format for text files)
sync             Sync all writes to disk
B32              Use 32-bit Big-Endian format 'int' as record length
L32              Use 32-bit Little-Endian format 'int' as record length
B64              Use 64-bit Big-Endian format 'int' or 'size_t' as record length
L64              Use 64-bit Little-Endian format 'int' or 'size_t' as record length
trace            Enable I/O trace when program execution tracing is enabled
stats            Write I/O statistic information on file close
retry_times      Default number of times to retry I/O
retry_seconds    Number of seconds between I/O retry attempts
retry_forever    Retry I/O forever
retry_never      Never retry I/O operations
ignore_lock      Ignore record locks
advancing_lock   Advance to the next record if lock condition
share_all        Share file with ALL others
share_read       Share file for READ only
share_no         Share file with NO others

 ---- For INDEXED files -----
format=ixhandler INDEXED file format: CISAM,DISAM,VBISAM,BDB,LMDB
format=auto      INDEXED file format is determined by inspecting the file
nkeys=n          number of indexes
key1=(loc:len)   loc (zero relative) of key, len of key
key2=(loc:len,loc:len ...)
                 define composite index
dupn=Y           index allows dups

  ---- For INDEXED BDB files -----
big_endian       Set internal 'int' byte order to BIG ENDIAN
little_endian    Set internal 'int' byte order to LITTLE ENDIAN

10.2.4 Program Arguments

Regardless of the manner in which a main program is executed (i.e. directly or via cobcrun), any arguments specified to the program may be retrieved via any of the following:

10.3 Binary Truncation

By default, the GnuCOBOL compiler will truncate binary data items to the precision indicated by their PICTURE ( 6.9.37 PICTURE) clause, if they have one. This applies to COMP, BINARY and COMP-4 items Only. | | The fact is, however, that binary truncation has a significant effect on the performance of GnuCOBOL programs. When binary truncation is in effect, arithmetic operations performed against all types of numeric data items (even USAGE DISPLAY) are slowed down.

Before continuing, it’s worth making the point that we’re not talking about astronomical performance degradations here. Today’s computers are fast, and a user sitting at the keyboard, running a GnuCOBOL program is unlikely to notice. But, if you have a GnuCOBOL program that has to process large amounts of data, performing some significant “number crunching” against that data as it goes, the impact of truncation could become noticeable.

The following program compares the performance of performing arithmetic operations (in a totally non-scientific, non-rigorous way) against data items with a USAGE ( 6.9.61 USAGE) of DISPLAY, COMP and BINARY-LONG. It was actually my intent when I first wrote the program to merely demonstrate the relative performance differences between different types of numeric data storage, and it certainly met that objective.

IDENTIFICATION DIVISION.
PROGRAM-ID. DEMOMATH.
DATA DIVISION.
WORKING-STORAGE SECTION.
01  Begin-Time.
    05 BT-HH                    PIC 9(2).
    05 BT-MM                    PIC 9(2).
    05 BT-SS                    PIC 9(2).
    05 BT-HU                    PIC 9(2).
01  Binary-Item         BINARY-LONG SIGNED VALUE 0.
01  Comp-Item           COMP    PIC S9(9)  VALUE 0.
01  Display-Item        DISPLAY PIC S9(9)  VALUE 0.
01  End-Time.
    05 ET-HH                    PIC 9(2).
    05 ET-MM                    PIC 9(2).
    05 ET-SS                    PIC 9(2).
    05 ET-HU                    PIC 9(2).
78  Repeat-Count                VALUE 10000000.
01  Time-Diff                   PIC ZZ9.99.
PROCEDURE DIVISION.
010-Test-Usage-DISPLAY.
    ACCEPT  Begin-Time FROM TIME
    PERFORM Repeat-Count TIMES
        ADD 7 TO Display-Item
    END-PERFORM
    PERFORM 100-Determine-Time-Diff
    DISPLAY 'USAGE DISPLAY: ' Time-Diff ' SECONDS'
    .
020-Test-Usage-COMP.
    ACCEPT Begin-Time FROM TIME
    PERFORM Repeat-Count TIMES
        ADD 7 TO Comp-Item
    END-PERFORM
    PERFORM 100-Determine-Time-Diff
    DISPLAY 'USAGE COMP:    ' Time-Diff ' SECONDS'
    .
040-Test-Usage-BINARY.
    ACCEPT Begin-Time FROM TIME
    PERFORM Repeat-Count TIMES
        ADD 7 TO Binary-Item
    END-PERFORM
    PERFORM 100-Determine-Time-Diff
    DISPLAY 'USAGE BINARY:  ' Time-Diff ' SECONDS'
    .
099-Done.
    STOP RUN
    .
100-Determine-Time-Diff.
    ACCEPT End-Time FROM TIME
    COMPUTE Time-Diff =
      ( (ET-HH * 360000 + ET-MM * 6000 + ET-SS * 100 + ET-HU)
      - (BT-HH * 360000 + BT-MM * 6000 + BT-SS * 100 + BT-HU) )
      / 100
    .

Each data item has 7 added to it ten million times.

The time (to one-one-hundredth of a second) will be retrieved before and after each test and the difference between the two is displayed. This is why the computations were done so many times — it was to make sure the timing was measurable with only a 1/100 second “stopwatch”.

I also ran the tests multiple times, just to make sure I had consistent results (I did). Like I mentioned earlier, this is not a rigorous, scientific benchmark of numeric performance; it’s just a quick-and-dirty comparison.

Here are the results:

Test 1:
USAGE DISPLAY:   1.72 SECONDS
USAGE COMP:      0.62 SECONDS
USAGE BINARY:    0.02 SECONDS

Test 2:
USAGE DISPLAY:   1.69 SECONDS
USAGE COMP:      0.61 SECONDS
USAGE BINARY:    0.02 SECONDS

Test 3:
USAGE DISPLAY:   1.69 SECONDS
USAGE COMP:      0.65 SECONDS
USAGE BINARY:    0.02 SECONDS

The results I saw here were consistent with those that would have been obtained from most of the COBOL implementations I have ever worked with — USAGE COMP has a significant performance advantage over USAGE DISPLAY and USAGE BINARY-LONG (and presumably the other BINARY-*xxx* usages as well) perform identically, within the measurement tolerances of the test.

Imagine my surprise, however, when I discovered that the use of -fnotrunc switch also made a difference:

Test 4:
USAGE DISPLAY:   1.72 SECONDS
USAGE COMP:      0.07 SECONDS
USAGE BINARY:    0.02 SECONDS

Test 5:
USAGE DISPLAY:   1.72 SECONDS
USAGE COMP:      0.07 SECONDS
USAGE BINARY:    0.02 SECONDS

Test 6:
USAGE DISPLAY:   1.73 SECONDS
USAGE COMP:      0.06 SECONDS
USAGE BINARY:    0.02 SECONDS

As you can see, there was a huge drop in USAGE COMP timings by turning off truncation. As a result, I see absolutely no reason whatsoever why the -fnotrunc switch option shouldn’t be used on all GnuCOBOL compilations.

If you want to squeeze every last bit of performance out of your GnuCOBOL programs, don’t forget to investigate the -O switch, -O2 switch and the -Os switch, all of which influence the optimization of compiled code. Actually run programs using various optimization switches (or not) and compare execution times against those of unoptimized compiled versions of your programs. Don’t just compare the generated C code because sometimes the differences can’t be seen at the C source-code level.

Test 7:
cobc -x demomath.cbl -O2;demomath
USAGE DISPLAY:   1.68 SECONDS
USAGE COMP:      0.60 SECONDS
USAGE BINARY:    0.00 SECONDS

Test 8:
cobc -x demomath.cbl -fnotrunc -O2;demomath
USAGE DISPLAY:   1.67 SECONDS
USAGE COMP:      0.01 SECONDS
USAGE BINARY:    0.00 SECONDS

All tests above carried out under Linux with a AMD FX8350 under very low loading prior to the test. I would have also tried on a i7-7700 but that is under Windows 10 and I do not have a GC version on it - Vince.