ZetCode

Modula-2 calling C

last modified November 27, 2026 Modula-2

GNU Modula-2 is a front end of GCC, so its programs are linked with the same tools as C programs, and they can call any C function. The bridge is a special definition module, DEFINITION MODULE FOR "C". It declares C functions in Modula-2 syntax and has no implementation module; the linker finds the functions in the C library or in an object file. The calls are not checked against the C headers, so the declarations must be right.

The environment and processes article already called system and setenv from gm2's libc module. This article writes such modules itself. The C files are compiled with gcc-15, the C compiler of the same GCC version, which the gm2-15 package installs along with the Modula-2 compiler. All Modula-2 examples are compiled with -fiso.

printf from libc

gm2 ships a module libc with declarations of common C library functions, among them printf.

greeting.mod
MODULE greeting;

FROM libc IMPORT printf;

VAR
  year: INTEGER;

BEGIN
  year := 1978;
  printf("Hello there!\n");
  printf("Modula-2 was published in %d.\n", year)
END greeting.

printf is declared as PROCEDURE printf(format: ARRAY OF CHAR; ...): [INTEGER]. The three dots allow any number of further arguments, as in C, and the brackets around the result type let the program call it as a statement and ignore the count of written characters. A string passed to a C function arrives as a pointer to its first character; gm2 terminates string constants with 0C, so C sees a proper string. gm2 also translates C escapes such as \n in strings passed to C functions. In WriteString("a\nb") the backslash stays a backslash and the call prints four characters.

$ gm2 -fiso greeting.mod -o greeting
$ ./greeting
Hello there!
Modula-2 was published in 1978.

Matching C types

In a variadic call, the compiler cannot check the extra arguments against the format. Each one must have the C type that its conversion expects.

formats.mod
MODULE formats;

FROM libc IMPORT printf;

VAR
  n: INTEGER;
  c: CARDINAL;
  big: LONGINT;
  x: REAL;
  small: SHORTREAL;
  ch: CHAR;
  name: ARRAY [0..15] OF CHAR;

BEGIN
  n := -42;
  c := 4000000000;
  big := 9000000000;
  x := 3.14159;
  small := 2.5;
  ch := 'W';
  name := "Wirth";
  printf("INTEGER   %d\n", n);
  printf("CARDINAL  %u\n", c);
  printf("LONGINT   %ld\n", big);
  printf("REAL      %8.3f\n", x);
  printf("CHAR      %c\n", ch);
  printf("string    [%-8s]\n", name);
  printf("SHORTREAL %f\n", small)
END formats.

On x86-64 Linux, INTEGER is C's int, CARDINAL its unsigned int, LONGINT a long, REAL a double and CHAR a char. A character array is passed by address and printed with %s up to its 0C. The last line is wrong: C promotes a float in a variadic call to double, but gm2 passes a SHORTREAL as it is, and printf reads garbage, here 0. Convert it first with VAL(REAL, small); LFLOAT does not help, because a LONGREAL is not a C double either. A wrong conversion is not an error but a wrong number, and with %s it can crash the program.

$ gm2 -fiso formats.mod -o formats
$ ./formats
INTEGER   -42
CARDINAL  4000000000
LONGINT   9000000000
REAL         3.142
CHAR      W
string    [Wirth   ]
SHORTREAL 0.000000

Two output libraries

printf writes through the C library's stdout, and STextIO through its own ISO channel. Each has its own buffer, and the two do not know of each other.

order.mod
MODULE order;

FROM libc IMPORT printf;
FROM STextIO IMPORT WriteString, WriteLn;

BEGIN
  WriteString("one from STextIO"); WriteLn;
  printf("two from printf\n");
  WriteString("three from STextIO"); WriteLn;
  printf("four from printf\n")
END order.

On a terminal, C flushes its buffer at every newline, but the ISO channel holds back the last line mark of each line until the next output on the channel, so the lines are glued together and the line breaks come late. Through a pipe it is worse: C collects all its output in a large buffer and writes it only when the program ends, so both printf lines come last. A program should use one of the two libraries for a stream, or flush both whenever it switches.

$ gm2 -fiso order.mod -o order
$ ./order
one from STextIOtwo from printf

three from STextIOfour from printf
$ ./order | cat
one from STextIO
three from STextIO
two from printf
four from printf

A definition module for C

The libc module has no fflush, so the program declares it itself, together with puts. A definition module FOR "C" has the name of the module after the string, and lists the C functions as procedure headings.

CStdio.def
DEFINITION MODULE FOR "C" CStdio;

FROM SYSTEM IMPORT ADDRESS;

EXPORT UNQUALIFIED fflush, puts;

PROCEDURE fflush(stream: ADDRESS): INTEGER;
PROCEDURE puts(s: ARRAY OF CHAR): INTEGER;

END CStdio.

EXPORT UNQUALIFIED tells gm2 to call the functions by their plain C names. Without it, gm2 prefixes the module name, and the link fails with "undefined reference to `CStdio_puts'". C's FILE * becomes an ADDRESS; fflush(NULL) flushes all output streams, so the program never needs the address of stdout. A character array parameter is passed as a pointer, like const char *.

ordered.mod
MODULE ordered;

FROM libc IMPORT printf;
FROM CStdio IMPORT fflush, puts;
FROM STextIO IMPORT WriteString, WriteLn;
IMPORT IOChan, StdChans;

PROCEDURE FlushM2;
BEGIN
  IOChan.Flush(StdChans.StdOutChan())
END FlushM2;

PROCEDURE FlushC;
BEGIN
  IF fflush(NIL) # 0 THEN
    WriteString("fflush failed"); WriteLn
  END
END FlushC;

BEGIN
  WriteString("one from STextIO"); WriteLn;
  FlushM2;
  printf("two from printf\n");
  FlushC;
  WriteString("three from STextIO"); WriteLn;
  FlushM2;
  IF puts("four from puts") < 0 THEN HALT(1) END;
  FlushC
END ordered.

The program flushes the ISO channel with IOChan.Flush before each C call, and the C buffers with fflush before it writes with STextIO again. The module needs no compilation step of its own: the functions are in the C library, which is linked anyway. The lines now come in order on a terminal and through a pipe.

$ gm2 -fiso ordered.mod -o ordered
$ ./ordered
one from STextIO
two from printf
three from STextIO
four from puts
$ ./ordered | cat
one from STextIO
two from printf
three from STextIO
four from puts

The C math library

RealMath covers the usual functions, but the C math library has more, such as cube roots, the length of a hypotenuse and the error function. They need only declarations.

CMath.def
DEFINITION MODULE FOR "C" CMath;

EXPORT UNQUALIFIED cbrt, hypot, erf;

PROCEDURE cbrt(x: REAL): REAL;
PROCEDURE hypot(x, y: REAL): REAL;
PROCEDURE erf(x: REAL): REAL;

END CMath.
cmath.mod
MODULE cmath;

FROM CMath IMPORT cbrt, hypot, erf;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteFixed;

BEGIN
  WriteString("cbrt(27)     "); WriteFixed(cbrt(27.0), 6, 0); WriteLn;
  WriteString("cbrt(-8)     "); WriteFixed(cbrt(-8.0), 6, 0); WriteLn;
  WriteString("hypot(3, 4)  "); WriteFixed(hypot(3.0, 4.0), 6, 0); WriteLn;
  WriteString("erf(1)       "); WriteFixed(erf(1.0), 6, 0); WriteLn
END cmath.

double parameters and results become REAL. A C program needs -lm to link these functions; gm2 adds the math library to every link, so no option is needed. Unlike a power with the exponent 1/3, cbrt accepts negative numbers.

$ gm2 -fiso cmath.mod -o cmath
$ ./cmath
cbrt(27)     3.000000
cbrt(-8)     -2.000000
hypot(3, 4)  5.000000
erf(1)       0.842701

Linking your own C code

C code of your own is compiled into an object file and linked with the program. The C file computes the mean and the range of an array.

stats.c
/* stats.c: small statistics functions for a Modula-2 program */

double mean(const int *values, int count)
{
    double sum = 0.0;

    for (int i = 0; i < count; i++)
        sum += values[i];
    return count > 0 ? sum / count : 0.0;
}

void range(const int *values, int count, int *low, int *high)
{
    *low = *high = values[0];
    for (int i = 1; i < count; i++) {
        if (values[i] < *low)
            *low = values[i];
        if (values[i] > *high)
            *high = values[i];
    }
}

range returns two values through pointers. The array comes with its length, because a C array does not know its size.

Stats.def
DEFINITION MODULE FOR "C" Stats;

EXPORT UNQUALIFIED mean, range;

PROCEDURE mean(values: ARRAY OF INTEGER; count: INTEGER): REAL;
PROCEDURE range(values: ARRAY OF INTEGER; count: INTEGER;
                VAR low, high: INTEGER);

END Stats.

An open array parameter in a FOR "C" module passes only the address of the first element, which matches const int *; HIGH is not passed, so the count is a parameter of its own. VAR parameters pass addresses and match int *.

scores.mod
MODULE scores;

FROM Stats IMPORT mean, range;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM SRealIO IMPORT WriteFixed;

CONST
  Count = 6;

VAR
  points: ARRAY [1..Count] OF INTEGER;
  low, high: INTEGER;

BEGIN
  points[1] := 72; points[2] := 95; points[3] := 58;
  points[4] := 81; points[5] := 66; points[6] := 90;
  WriteString("mean  "); WriteFixed(mean(points, Count), 2, 0); WriteLn;
  range(points, Count, low, high);
  WriteString("range "); WriteInt(low, 0); WriteString(" - ");
  WriteInt(high, 0); WriteLn
END scores.

The array points starts at index 1, but C sees only the address of its first element and counts from 0. gcc-15 -c compiles the C file to stats.o, and the object file is named on the gm2 command line, as the object file of a Modula-2 module would be. The definition module is read during the compilation of scores.mod and produces no code.

$ gcc-15 -c -Wall stats.c
$ gm2 -fiso scores.mod stats.o -o scores
$ ./scores
mean  77.00
range 58 - 95

Strings both ways

A C function can return a pointer to a string it owns, or fill a buffer that the caller provides. Both appear in the next C file.

labels.c
/* labels.c: strings between C and Modula-2 */
#include <stdio.h>

static const char *names[] = {
    "Monday", "Tuesday", "Wednesday", "Thursday",
    "Friday", "Saturday", "Sunday"
};

const char *day_name(int day)
{
    return day >= 1 && day <= 7 ? names[day - 1] : "unknown";
}

int greet(char *buf, int size, const char *name)
{
    return snprintf(buf, size, "Hello there, %s!", name);
}

day_name returns a pointer to a constant string; greet writes into the buffer with snprintf, never more than size bytes, and returns the length that the whole text would need.

Labels.def
DEFINITION MODULE FOR "C" Labels;

FROM SYSTEM IMPORT ADDRESS;

EXPORT UNQUALIFIED day_name, greet;

PROCEDURE day_name(day: INTEGER): ADDRESS;
PROCEDURE greet(VAR buf: ARRAY OF CHAR; size: INTEGER;
                name: ARRAY OF CHAR): INTEGER;

END Labels.
cstrings.mod
MODULE cstrings;

FROM Labels IMPORT day_name, greet;
FROM Strings IMPORT Assign;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;

TYPE
  CString = POINTER TO ARRAY [0..255] OF CHAR;

VAR
  name: CString;
  day: ARRAY [0..15] OF CHAR;
  line: ARRAY [0..19] OF CHAR;
  needed: INTEGER;

BEGIN
  name := day_name(3);
  Assign(name^, day);
  WriteString(day); WriteLn;
  needed := greet(line, HIGH(line) + 1, "Niklaus");
  WriteString(line); WriteLn;
  WriteString("needed "); WriteInt(needed, 0); WriteLn
END cstrings.

day_name returns an ADDRESS. The program assigns it to a pointer to a large character array, and Assign copies the string up to its 0C into a Modula-2 array. The array type only gives the pointer a shape; nothing past the 0C is read. For greet the buffer is a VAR open array, and the program passes its real size, HIGH(line) + 1. The greeting needs 21 characters plus the terminator, the buffer holds 20, so C cut it off and wrote a 0C at the end. The returned 21 tells the caller that a larger buffer is needed. Passing a wrong size here would let C write past the array.

$ gcc-15 -c -Wall labels.c
$ gm2 -fiso cstrings.mod labels.o -o cstrings
$ ./cstrings
Wednesday
Hello there, Niklau
needed 21

Callbacks: qsort

C's qsort sorts an array of any type; it takes a comparison function and calls it with the addresses of two elements. A Modula-2 procedure can be that function.

CSort.def
DEFINITION MODULE FOR "C" CSort;

FROM SYSTEM IMPORT ADDRESS, CSIZE_T;

EXPORT UNQUALIFIED Compare, qsort;

TYPE
  Compare = PROCEDURE (ADDRESS, ADDRESS): INTEGER;

PROCEDURE qsort(base: ADDRESS; count, size: CSIZE_T; cmp: Compare);

END CSort.

A procedure type declares the shape of the comparison function. It is exported too, so the program can name it. size_t is CSIZE_T from SYSTEM.

sorted.mod
MODULE sorted;

FROM SYSTEM IMPORT ADDRESS, ADR, TSIZE;
FROM CSort IMPORT qsort;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;

CONST
  Count = 8;

TYPE
  IntPtr = POINTER TO INTEGER;

VAR
  data: ARRAY [1..Count] OF INTEGER;

PROCEDURE Ascending(a, b: ADDRESS): INTEGER;
VAR
  x, y: IntPtr;
BEGIN
  x := a; y := b;
  IF x^ < y^ THEN RETURN -1
  ELSIF x^ > y^ THEN RETURN 1
  ELSE RETURN 0
  END
END Ascending;

PROCEDURE Descending(a, b: ADDRESS): INTEGER;
BEGIN
  RETURN -Ascending(a, b)
END Descending;

PROCEDURE Show(label: ARRAY OF CHAR);
VAR
  i: CARDINAL;
BEGIN
  WriteString(label);
  FOR i := 1 TO Count DO WriteInt(data[i], 4) END;
  WriteLn
END Show;

BEGIN
  data[1] := 31; data[2] := 4; data[3] := 15; data[4] := 92;
  data[5] := 6; data[6] := 53; data[7] := -5; data[8] := 8;
  Show("start      ");
  qsort(ADR(data), Count, TSIZE(INTEGER), Ascending);
  Show("ascending  ");
  qsort(ADR(data), Count, TSIZE(INTEGER), Descending);
  Show("descending ")
END sorted.

Ascending converts the two addresses to typed pointers and returns a negative number, zero or a positive number, as qsort expects. Descending negates it. Both are ordinary global procedures, so their values can be passed as procedure parameters; C calls them like any function pointer. ADR(data) and TSIZE(INTEGER) describe the array to C. Nothing checks that the comparator matches the element type: sorting REALs with this comparator would compare the first four bytes of each number as an integer. The sorting article writes the algorithms in Modula-2, with type-checked comparators.

$ gm2 -fiso sorted.mod -o sorted
$ ./sorted
start        31   4  15  92   6  53  -5   8
ascending    -5   4   6   8  15  31  53  92
descending   92  53  31  15   8   6   4  -5

Source

GNU Modula-2: interface to C

GNU Modula-2: the libc module

In this article we have called printf from gm2's libc module, matched Modula-2 types to C types, kept C and ISO output in order, declared C functions in a DEFINITION MODULE FOR "C", linked our own C object files, passed strings in both directions and sorted with qsort and a Modula-2 comparator. The low-level programming article covers ADDRESS, ADR and the other names from SYSTEM used here, and the modules article ordinary definition modules.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.