Modula-2 compiling and debugging
last modified November 27, 2026 Modula-2
gm2 is a GCC front end, so it shares its options and tools with the C and
C++ compilers of GCC: -Wall for warnings, -O2 for
optimisation, -g for debugging information, the
gdb debugger and dependency files for make. It
adds options of its own for the Modula-2 dialects and for runtime checks.
This article goes through them from a compile error to a build with
make.
All examples use the ISO dialect, selected with -fiso. The
modules article covers separate compilation
with -c, which the last section automates.
A type error
A compile error starts with the file name, the line and the column, followed by the procedure or module in which it occurs. The column points at the operator or name that the compiler rejected.
MODULE cartons;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
VAR
items, boxes: CARDINAL;
perBox: INTEGER;
BEGIN
items := 50;
perBox := 12;
boxes := (items + perBox - 1) DIV perBox;
WriteString("boxes: "); WriteCard(boxes, 0); WriteLn
END cartons.
items is a CARDINAL and perBox an
INTEGER, and Modula-2 does not mix the two in one expression.
The compiler marks the + and then lists the declarations of
both variables, so the fix can be made at either place. No executable is
written, and gm2 exits with status 1. Declaring perBox as a
CARDINAL fixes the program, which then prints
boxes: 5.
$ gm2 -fiso cartons.mod -o cartons
cartons.mod:12:19: error: In program module ‘cartons’: type incompatibility between ‘INTEGER’ and ‘CARDINAL’
12 | boxes := (items + perBox - 1) DIV perBox;
| ~~~~~~^~~~~~~~
cartons.mod:7:3: error: variable declaration for ‘perBox’
7 | perBox: INTEGER;
| ^~~~~~~~~~~~~~~
cartons.mod:6:3: error: variable declaration for ‘items’
6 | items, boxes: CARDINAL;
| ^~~~~~~~~~~~~~~~~~~~~~
$ echo $?
1
A syntax error
A syntax error is often reported later than the place where it was made. The parser notices that something is wrong only when the next symbol does not fit.
MODULE packing;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
VAR
items, boxes, perBox: CARDINAL;
BEGIN
items := 50
perBox := 12;
boxes := (items + perBox - 1) DIV perBox;
WriteString("boxes: "); WriteCard(boxes, 0); WriteLn
END packing.
The semicolon after items := 50 is missing. To the parser,
perBox cannot start a new part of the same statement, so it
assumes that the module ends there, and every message after the first
follows from that guess. The rule for syntax errors is to read the first
message, look at the line before the place it names, and ignore the rest
until the first one is fixed.
$ gm2 -fiso packing.mod -o packing
packing.mod:10:3: warning: In program module ‘packing’: syntax warning, ‘END’ missing
10 | perBox := 12;
| ^~~~~~
packing.mod:10:10: warning: syntax warning, ‘.’ missing
10 | perBox := 12;
| ^~
packing.mod:1:8: error: module name at beginning ‘packing’ does not match the name at end ‘perBox’
1 | MODULE packing;
| ^~~~~~~
packing.mod:10:3: error: module name at end ‘perBox’ does not match the name at beginning ‘packing’
10 | perBox := 12;
| ^~~~~~
packing.mod:10:10: error: syntax error, found ‘:=’
10 | perBox := 12;
| ^~
packing.mod:14:1: error: no scope active: compilation failed
Warnings
A program can compile without errors and still be wrong. gm2 prints no
warnings by default; -Wall turns on the usual set.
MODULE warnings;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
TYPE
Shape = (Circle, Square, Triangle);
PROCEDURE Corners(s: Shape): INTEGER;
VAR
n: INTEGER;
BEGIN
CASE s OF
Circle: n := 0
| Square: n := 4
END;
RETURN n
END Corners;
PROCEDURE Twice(x: INTEGER): INTEGER;
VAR
result: INTEGER;
BEGIN
result := result + x;
RETURN result * 2
END Twice;
BEGIN
WriteString("square: "); WriteInt(Corners(Square), 0); WriteLn;
WriteString("twice 5: "); WriteInt(Twice(5), 0); WriteLn
END warnings.
The default build is silent. With -Wall the compiler reports
two problems. The CASE in Corners has no label
for Triangle and no ELSE, and
Twice reads result before anything is assigned
to it. The program prints garbage for the second line: a local variable
holds whatever was left in its memory.
$ gm2 -fiso warnings.mod -o warnings
$ ./warnings
square: 4
twice 5: 65538
$ gm2 -fiso -Wall warnings.mod -o warnings
warnings.mod:12:3: warning: In procedure ‘Corners’: not all enumeration type values in the CASE statements are specified, hint you either need to specify each value of ‘Shape’ or use an ELSE clause
12 | CASE s OF
| ^~~~
warnings.mod:12:3: warning: the missing enumeration field is: Triangle
warnings.mod:23:13: warning: In procedure ‘Twice’: attempting to access ‘result’ before it has been initialized
23 | result := result + x;
| ^~~~~~
Warnings from the optimiser
The front end checks uninitialised variables only in the first statements
of a procedure. A variable that is first read inside a loop slips through,
even with -Wall.
MODULE total;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
PROCEDURE Total(n: INTEGER): INTEGER;
VAR
i, sum: INTEGER;
BEGIN
FOR i := 1 TO n DO
sum := sum + i
END;
RETURN sum
END Total;
BEGIN
WriteString("1 + 2 + ... + 10 = ");
WriteInt(Total(10), 0); WriteLn
END total.
sum is never set to 0. The default build prints a random
number, and the build with -O2 happens to print the right
result, because the optimised code keeps sum in a register
that starts at 0; a bug whose symptoms depend on the optimisation level is
typical of uninitialised variables. The GCC back end analyses the data
flow when it optimises, and -Wuninitialized together with
-O2 finds the error.
$ gm2 -fiso -Wall total.mod -o total
$ ./total
1 + 2 + ... + 10 = 1226617439
$ gm2 -fiso -O2 total.mod -o total
$ ./total
1 + 2 + ... + 10 = 55
$ gm2 -fiso -O2 -Wuninitialized total.mod -o total
total.mod: In function ‘_M2_total_init’:
total.mod:7:6: warning: ‘sum’ is used uninitialized [-Wuninitialized]
7 | i, sum: INTEGER;
| ^~~
Runtime checks one by one
-fsoft-check-all, used in the
error handling article, turns on
eight groups of runtime checks. Each group also has an option of its own:
-frange for subranges, -findex for array indexes,
-fnil for NIL pointers, -fwholediv
for division by zero, -fwholevalue for integer overflow,
-ffloatvalue for real overflow, -fcase for
CASE without a matching label and -freturn for a
function that ends without RETURN.
MODULE hours;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
TYPE
Hour = [0..23];
VAR
counts: ARRAY Hour OF CARDINAL;
h: CARDINAL;
next: Hour;
BEGIN
FOR h := 0 TO 23 DO counts[h] := 0 END;
h := 23;
next := h + 1;
WriteString("next hour: "); WriteCard(next, 0); WriteLn;
INC(counts[h + 1]);
WriteString("counted"); WriteLn
END hours.
The program makes two mistakes: it assigns 24 to a variable of type
[0..23], and it uses 24 as an index into an array indexed by
that type. Without checks both pass unnoticed. -frange stops
at the assignment; the message names the types the wrong way round, but
the line is right. -findex lets the assignment through and
stops at the index. gm2 --help=modula-2 lists
-fbounds as well, but gm2 15.2 rejects it as an unrecognised
option.
$ gm2 -fiso hours.mod -o hours $ ./hours next hour: 24 counted $ gm2 -fiso -frange hours.mod -o hours $ ./hours hours.mod:16:3: In program module hours hours.mod:16:3:assignment will cause a range error, as the runtime instance value of ‘Hour’ does not overlap with the type ‘CARDINAL’ $ gm2 -fiso -findex hours.mod -o hours $ ./hours next hour: 24hours.mod:18:19: In program module hours hours.mod:18:19:if this access to the static array is ever made then the index will be out of bounds in the 1st array subscript
The cost of checks
Runtime checks make a program larger and slower, and optimisation makes it faster. The sieve of Eratosthenes, which spends its time indexing a large array, shows how much.
MODULE sieve;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
CONST
Limit = 20000000;
Rounds = 5;
VAR
composite: ARRAY [0..Limit] OF BOOLEAN;
i, j, round, count: CARDINAL;
BEGIN
FOR round := 1 TO Rounds DO
FOR i := 0 TO Limit DO composite[i] := FALSE END;
i := 2;
WHILE i * i <= Limit DO
IF NOT composite[i] THEN
j := i * i;
WHILE j <= Limit DO composite[j] := TRUE; INC(j, i) END
END;
INC(i)
END
END;
count := 0;
FOR i := 2 TO Limit DO
IF NOT composite[i] THEN INC(count) END
END;
WriteString("primes up to "); WriteCard(Limit, 0);
WriteString(": "); WriteCard(count, 0); WriteLn
END sieve.
The sieve marks the multiples of every prime up to 20 million and repeats
the work five times. The default build is not optimised. -O2
makes the program about three times faster. The checks add little to the
unoptimised build, which is slow anyway, but more than double the time of
the optimised one, because every index is compared with the bounds. A
common choice is to develop with -fsoft-check-all and to
release with -O2, keeping the checks where a wrong index
would do more harm than the lost speed.
$ gm2 -fiso sieve.mod -o sieve $ time ./sieve primes up to 20000000: 1270607 real 0m1.926s user 0m1.916s sys 0m0.010s $ gm2 -fiso -O2 sieve.mod -o sieve $ time ./sieve primes up to 20000000: 1270607 real 0m0.715s user 0m0.662s sys 0m0.010s $ gm2 -fiso -fsoft-check-all sieve.mod -o sieve $ time ./sieve primes up to 20000000: 1270607 real 0m2.032s user 0m2.017s sys 0m0.015s $ gm2 -fiso -O2 -fsoft-check-all sieve.mod -o sieve $ time ./sieve primes up to 20000000: 1270607 real 0m1.468s user 0m1.462s sys 0m0.006s
A backtrace
-g stores debugging information in the executable: the source
lines, the names and types of variables. gdb understands
Modula-2 and uses it to show where a program failed and how it got there.
MODULE marks;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
TYPE
Marks = ARRAY [1..5] OF INTEGER;
PROCEDURE Average(m: Marks; n: CARDINAL): INTEGER;
VAR
i: CARDINAL;
sum: INTEGER;
BEGIN
sum := 0;
FOR i := 1 TO n DO
sum := sum + m[i]
END;
RETURN sum DIV INTEGER(n)
END Average;
VAR
results: Marks;
BEGIN
results[1] := 70; results[2] := 85; results[3] := 92;
results[4] := 0; results[5] := 0;
WriteString("first three: "); WriteInt(Average(results, 3), 0); WriteLn;
WriteString("none: "); WriteInt(Average(results, 0), 0); WriteLn
END marks.
-batch runs the commands given with -ex and
quits, and -q suppresses the banner. The first lines come from
the thread support of the runtime library. The division by zero raises the
signal SIGFPE, and gdb stops the program before
the runtime library can print its message. The command
bt prints the backtrace: frame 0 is Average at
line 17 with n=0, frame 1 the module body at line 26, which
gm2 compiles into a function named _M2_marks_init. The frames
below belong to the runtime system that starts the program.
$ gm2 -fiso -g marks.mod -o marks $ gdb -q -batch -ex run -ex bt ./marks [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". [New Thread 0x7ffff6ffe640 (LWP 28928)] first three: 82 none: Thread 1 "marks" received signal SIGFPE, Arithmetic exception. 0x00005555555564ce in Average (m=..., n=0) at marks.mod:17 17 RETURN sum DIV INTEGER(n) #0 0x00005555555564ce in Average (m=..., n=0) at marks.mod:17 #1 0x0000555555556401 in _M2_marks_init (argc=1, argv=0x7fffffffb998, envp=0x7fffffffb9a8) at marks.mod:26 #2 0x00007ffff7f2ee55 in m2pim_M2Dependent_ConstructModules () from /lib/x86_64-linux-gnu/libm2pim.so.20 #3 0x0000555555556d92 in _M2_init (argc=1, argv=0x7fffffffb998, envp=0x7fffffffb9a8) at marks.mod:1 #4 0x0000555555556dfc in main (argc=1, argv=0x7fffffffb998, envp=0x7fffffffb9a8) at marks.mod:1
Stepping through a procedure
A breakpoint stops the program at a procedure or a line. From there,
gdb runs the program a line at a time and prints variables in
Modula-2 notation.
break Average stops at the first statement of the procedure.
info args and info locals print the parameters
and the local variables, next runs one line without entering
the procedures it calls, and finish runs to the end of the
procedure and prints the value it returns. print m[2] uses
the bounds of the array type: m starts at index 1, and
m[2] is the second mark, 85.
After three steps the first pass of the loop is done: sum is
70 and i is 1. The line first three: appears
before the breakpoint because the program stops in the middle of that
line, inside the call to Average.
$ gdb -q -batch -ex 'break Average' -ex run -ex 'info args' -ex next -ex next -ex next -ex 'info locals' -ex 'print m[2]' -ex finish ./marks
Breakpoint 1 at 0x243f: file marks.mod, line 13.
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff6ffe640 (LWP 28942)]
first three:
Thread 1 "marks" hit Breakpoint 1, Average (m=..., n=3) at marks.mod:13
13 sum := 0;
m = {70, 85, 92, 0, 0}
n = 3
14 FOR i := 1 TO n DO
15 sum := sum + m[i]
16 END;
sum = 70
i = 1
$1 = 85
0x0000555555556370 in _M2_marks_init (argc=1, argv=0x7fffffffb998, envp=0x7fffffffb9a8) at marks.mod:25
25 WriteString("first three: "); WriteInt(Average(results, 3), 0); WriteLn;
Value returned is $2 = 82
Building with make
A program with several modules needs several compile steps, and after a
change only some of them have to run again. make decides
which, given the dependencies between the files. gm2 writes them itself:
-MMD creates a .d file next to each object file
that lists the definition modules it imports. The example builds the
orders program of the sorting
article from its two modules.
GM2 = gm2 FLAGS = -fiso -Wall OBJS = orders.o Samples.o Sorts.o orders: $(OBJS) $(GM2) $(FLAGS) $(OBJS) -o $@ orders.o: orders.mod $(GM2) $(FLAGS) -fscaffold-main -MMD -c $< %.o: %.mod $(GM2) $(FLAGS) -MMD -c $< -include $(OBJS:.o=.d) .PHONY: clean clean: rm -f orders $(OBJS) $(OBJS:.o=.d)
The pattern rule compiles each implementation module into an object file.
The program module needs -fscaffold-main: without it,
-c does not generate the main function, and the
link fails with an undefined reference. The link step then needs only
object files. -include reads the .d files when
they exist. After a change to Sorts.def, make
recompiles Sorts.o and orders.o, which import
it, and leaves Samples.o alone. The recipe lines in a
Makefile must start with a tab.
$ make gm2 -fiso -Wall -fscaffold-main -MMD -c orders.mod gm2 -fiso -Wall -MMD -c Samples.mod gm2 -fiso -Wall -MMD -c Sorts.mod gm2 -fiso -Wall orders.o Samples.o Sorts.o -o orders $ ./orders data: 149 249 305 44 283 819 463 689 472 901 742 836 insertion: 901 836 819 742 689 472 463 305 283 249 149 44 quick: 44 149 249 283 305 463 472 689 742 819 836 901 merge: 901 472 742 283 463 44 305 836 149 249 689 819 $ make make: 'orders' is up to date. $ cat Sorts.d Sorts.o: \ Sorts.mod \ ./Sorts.def $ touch Sorts.def $ make gm2 -fiso -Wall -fscaffold-main -MMD -c orders.mod gm2 -fiso -Wall -MMD -c Sorts.mod gm2 -fiso -Wall orders.o Samples.o Sorts.o -o orders
Source
In this article we have read compile errors, turned on warnings with
-Wall and with the optimiser, selected runtime checks one by
one, measured the cost of checks and the gain of -O2, found a
crash with a gdb backtrace, stepped through a procedure and
built a program with make and generated dependencies. The
error handling article catches the
errors that the runtime checks raise, and the
unit testing article checks a module
with tests.
Author
List all Modula-2 tutorials.