Write a COBOL program that calls a C subroutine using the CALL verb and USING BY…
- User
Write a COBOL program that calls a C subroutine using the
CALLverb andUSING BY REFERENCE. Assistant
1. Understand the Goal: The user wants a COBOL program that calls a C function (subroutine). The specific requirement is to use the
CALLverb with theUSING BY REFERENCEphrase for passing arguments.-
Identify the Components:
- COBOL Program: Needs a
IDENTIFICATION DIVISION,ENVIRONMENT DIVISION,DATA DIVISION(specificallyWORKING-STORAGE SECTIONfor variables andLINKAGE SECTIONif applicable, though usually parameters are passed from Working-Storage), andPROCEDURE DIVISION. - C Subroutine: Needs a standard C function definition that accepts pointers (since COBOL is passing "BY REFERENCE").
- Interface/Interoperability: This is the tricky part. It varies by compiler (Enterprise COBOL for z/OS, Micro Focus COBOL, GnuCOBOL, etc.). I should probably provide a generic example that works on common platforms like Linux/GnuCOBOL or Windows/Micro Focus, but the logic applies to Mainframe (z/OS) as well, provided the data types are mapped correctly.
- COBOL Program: Needs a
-
Determine the Scenario:
- Let's keep it simple: Pass two numbers, have the C function add them, and return the result (or modify one of them).
- COBOL side:
- Variable A (PIC 9(4))
- Variable B (PIC 9(4))
- Variable Result (PIC 9(4))
- C side:
- Function signature:
void add_numbers(int *a, int *b, int *result)(Using pointers because COBOL is passing references).
- Function signature:
-
Drafting the COBOL Code:
- Identification: Standard boilerplate.
- Data:
WS-NUM1PIC 9(4) VALUE 10.WS-NUM2PIC 9(4) VALUE 20.WS-SUMPIC 9(4) VALUE 0.
- Procedure:
- Display "Before call".
CALL "c_subroutine" USING BY REFERENCE WS-NUM1, WS-NUM2, WS-SUM. Note: The literal string "c_subroutine" must match the C function name (usually). Some compilers might require specific naming conventions orENTRYpoints.- Display "After call".
-
Drafting the C Code:
- Need to handle the COBOL data types. COBOL
PIC 9(4)is usually a BCD (Binary Coded Decimal) or Display format (digits), not a Cintorshort. - Correction: To make interoperability easier, it's best to use
USAGE COMP-5(native binary) orUSAGE BINARYin COBOL, which maps better to Cintorshort. - Let's use
PIC S9(9) USAGE COMP-5(maps tointon 32-bit/64bit systems usually). - Or, stick to the prompt's focus ("BY REFERENCE") and keep the data types simple but explicit.
- Let's try to stick to GnuCOBOL/OpenCOBOL style as it's the most accessible for a user testing this locally. In GnuCOBOL,
PIC 9(4)is often just a string, butUSAGE BINARYorCOMPmaps to C types. - Decision: I will use
BINARYorCOMPdata types in COBOL to ensure easy mapping to Cintpointers. If I use display numeric, the C code has to parse strings, which distracts from the main point (the CALL mechanism).
- Need to handle the COBOL data types. COBOL
-
Refining the Interface:
- COBOL:
WORKING-STORAGE SECTION. 01 WS-NUM1 PIC S9(9) BINARY VALUE 10. 01 WS-NUM2 PIC S9(9) BINARY VALUE 20. 01 WS-RESULT PIC S9(9) BINARY VALUE 0. ... CALL "add_nums" USING BY REFERENCE WS-NUM1 BY REFERENCE WS-NUM2 BY REFERENCE WS-RESULT. - C:
#include <stdio.h> // void add_nums(int *n1, int *n2, int *res) { // *res = *n1 + *n2; // }
- COBOL:
-
Platform Specifics (Important):
- Mainframe (z/OS): C functions need to be compiled with specific linkage conventions (often
#pragma linkage(func, COBOL)). - Linux (GnuCOBOL): Standard C compilation. Needs
-export-dynamicif compiling C separately, or just link the object file. - I will provide a generic C code but add notes about GnuCOBOL as the execution environment, as it's the standard "free" way to run this.
- Mainframe (z/OS): C functions need to be compiled with specific linkage conventions (often
-
Constructing the Example:
-
Part 1: The C Code (subroutine.c)
- Function name:
add_numbers. - Args:
int *a,int *b,int *result. - Body:
*result = *a + *b;. - Crucial: COBOL
BY REFERENCEmeans the address is passed. C must expect pointers.
- Function name:
-
Part 2: The COBOL Code (main.cob)
- Define variables as Binary (
COMPorCOMP-5) to match Cint. CALL "add_numbers" USING BY REFERENCE ...- Note:
BY REFERENCEis the default in many COBOL dialects ifBYis omitted, but the prompt explicitly asked for it, so I must write it out.
- Define variables as Binary (
-
Part 3: Compilation/Execution Instructions
- Compile C to object:
gcc -c subroutine.c - Compile COBOL and link:
cobc -x -free main.cob subroutine.o(GnuCOBOL syntax).
- Compile C to object:
-
-
Reviewing against constraints:
CALLverb used? Yes.USING BY REFERENCEused? Yes.- Is it a C subroutine? Yes.
-
Refining Data Types:
- If I use
PIC 9(4)(Display) in COBOL, the C side receives achar*(orunsigned char*). If I convert it tointinside C usingatoi, it works but is messier. - If I use
PIC S9(9) COMP-5(Native Binary), C receives anint*. This is much cleaner for a tutorial. - Self-Correction: I will use
USAGE COMP-5(orBINARY) and explain why. This ensures the bits line up.
- If I use
-
Writing the response:
- Introduction.
- C Code block.
- COBOL Code block.
- Explanation of how
BY REFERENCEworks (pointers). - Explanation of Data Types (Comp-5 vs Display).
- Compilation steps (using GnuCOBOL/GCC as the example environment).
-
Final Polish:
- Make sure the C code handles 32-bit or 64-bit pointers correctly (standard
intvsint32_tetc, butintis usually fine for a simple example). - Ensure COBOL variable names are clear.
- Make sure the C code handles 32-bit or 64-bit pointers correctly (standard
(Self-Correction during drafting): What if the user is on a Mainframe? The code logic is the same, but the compilation steps are JCL. I should mention that the logic applies generally but the compile commands are for a Unix/Windows environment (GnuCOBOL).
Let's stick to the "Add two numbers" logic. It's the "Hello World" of inter-language calls.
C Code:
#include <stdio.h> void add_nums(int *a, int *b, int *result) { *result = *a + *b; }COBOL Code:
IDENTIFICATION DIVISION. PROGRAM-ID. MAINPROG. DATA DIVISION. WORKING-STORAGE SECTION. 01 WS-NUM1 PIC S9(9) COMP-5 VALUE 15. 01 WS-NUM2 PIC S9(9) COMP-5 VALUE 30. 01 WS-RESULT PIC S9(9) COMP-5 VALUE 0. PROCEDURE DIVISION. DISPLAY "Start of COBOL Program". CALL "add_nums" USING BY REFERENCE WS-NUM1 BY REFERENCE WS-NUM2 BY REFERENCE WS-RESULT. DISPLAY "Number 1: " WS-NUM1. DISPLAY "Number 2: " WS-NUM2. DISPLAY "Result: " WS-RESULT. STOP RUN.This looks solid. I will structure the output clearly with files and compilation instructions. Here is a complete example demonstrating how to call a C subroutine from COBOL.
This example uses GnuCOBOL (OpenCOBOL) and GCC, which are standard on Linux/Unix environments. The logic remains the same for Mainframe environments (z/OS), though the compilation commands (JCL) would differ.
The Concept
When COBOL uses
BY REFERENCE, it passes the memory address of the variable to the C function. In C, this is handled via pointers.We will create a COBOL program that passes two numbers to a C function, which will add them together and update a result variable.
1. The C Subroutine (
math_ops.c)In this file, we define a function that accepts pointers to integers.
int *a: Corresponds toBY REFERENCEin COBOL.*a: Dereferences the pointer to get or set the actual value.
#include <stdio.h> /* The function name 'add_numbers' must be lowercase. GnuCOBOL usually resolves CALL "ADD_NUMBERS" to this lowercase name. If using a mainframe, you might need pragma linkage or specific naming conventions. */ void add_numbers(int *num1, int *num2, int *result) { // Dereference the pointers to access the values int val1 = *num1; int val2 = *num2; // Perform the logic *result = val1 + val2; // Optional: Print from C to prove we are here printf("C Subroutine: Received %d and %d. Calculated result: %d\n", val1, val2, *result); }
2. The COBOL Program (
main.cob)We define the variables as
USAGE IS COMP-5(orCOMP) to ensure they map correctly to C integers (binary format).IDENTIFICATION DIVISION. PROGRAM-ID. MAIN-COBOL. DATA DIVISION. WORKING-STORAGE SECTION. * USAGE COMP-5 ensures native binary format compatible with C 'int' 01 WS-NUM-1 PIC S9(9) USAGE COMP-5 VALUE 10. 01 WS-NUM-2 PIC S9(9) USAGE COMP-5 VALUE 25. 01 WS-RESULT PIC S9(9) USAGE COMP-5 VALUE 0. PROCEDURE DIVISION. DISPLAY "=========================================" DISPLAY "COBOL: Starting program." DISPLAY "COBOL: Value 1 is " WS-NUM-1 DISPLAY "COBOL: Value 2 is " WS-NUM-2 DISPLAY "COBOL: Result before call is " WS-RESULT DISPLAY "COBOL: Calling C function 'add_numbers'..." * The literal name usually matches the C function name (case sensitive * depending on the compiler environment). CALL "add_numbers" USING BY REFERENCE WS-NUM-1 BY REFERENCE WS-NUM-2 BY REFERENCE WS-RESULT END-CALL. DISPLAY "-----------------------------------------" DISPLAY "COBOL: Back from C." DISPLAY "COBOL: Result after call is " WS-RESULT DISPLAY "=========================================" STOP RUN.
3. How to Compile and Run (Linux/Unix with GnuCOBOL)
You must compile the C code into an object file, and then compile the COBOL code, linking them together.
Step 1: Compile C code to an object file
gcc -c math_ops.c -o math_ops.oStep 2: Compile COBOL and Link The
cobccommand compiles the COBOL source and links the C object file (math_ops.o) into the final executable.cobc -x -free main.cob math_ops.o(Note:
-xbuilds an executable,-freeallows free-format source code if you didn't use column 7 indicators).Step 3: Run
./mainExpected Output
========================================= COBOL: Starting program. COBOL: Value 1 is +000000010 COBOL: Value 2 is +000000025 COBOL: Result before call is +000000000 COBOL: Calling C function 'add_numbers'... C Subroutine: Received 10 and 25. Calculated result: 35 ----------------------------------------- COBOL: Back from C. COBOL: Result after call is +000000035 =========================================Key Details Explanation
USAGE COMP-5: Standard COBOL display numbers (PIC 9) are stored as characters or packed decimal. C expects raw binary integers.COMP-5(Native Binary) maps directly to a Cint(usually 4 bytes).BY REFERENCE: In theCALLstatement,BY REFERENCEis the default in COBOL, but writing it explicitly is good practice. It tells the runtime to pass the address ofWS-NUM-1rather than a copy of the value. This allows the C code to modify the memory at that address, effectively updating the COBOL variable.- C Pointers:
Because COBOL passed addresses, the C function parameters must be declared as pointers (
int *). If you tried to acceptint num1in C, you would get the memory address as a number (e.g., 6422304) rather than the value 10.
-