Getting Started¶
Dependencies¶
C11 compiler (GCC or Clang)
CMake 3.12+ and
pkg-configPulseAudio development library (
libpulse-simple) – optional, forSOUND/BEEP/PLAY
On Debian/Ubuntu:
sudo apt-get install build-essential cmake pkg-config libpulse-dev
On Fedora/RHEL:
sudo dnf install gcc make cmake pkgconf-pkg-config pulseaudio-libs-devel
macOS binary downloads¶
The release provides separate archives for Apple Silicon
(gwbasic-0.18.3-macos-arm64.tar.gz) and Intel
(gwbasic-0.18.3-macos-x86_64.tar.gz). Both require macOS 15 or later.
Download them from the v0.18.3 release assets
page.
Download the matching BUILD-macos-*.json and SHA256SUMS-macos-* files into the
same directory to verify the archive and its build record. For Apple Silicon:
shasum -a 256 --check SHA256SUMS-macos-arm64
tar -xzf gwbasic-0.18.3-macos-arm64.tar.gz
cd gwbasic-0.18.3-macos-arm64
bin/gwbasic hello.bas
bin/gwbasic-compile hello.bas -c --runtime .
./hello
On Intel, substitute x86_64 for arm64. Native compilation needs Apple’s
Command Line Tools, installed with xcode-select --install. The interpreter
needs no Homebrew libraries. Audio output is disabled in these archives.
The binaries are not Developer ID signed or notarised. macOS may ask you to approve downloaded software; the Homebrew installation is another option. Tests exercise extracted archives on macOS 15, including interpreter and native execution, input, arrays, strings, file I/O and paths containing spaces. They do not cover the interactive editor or terminal graphics.
BUILD.json inside each archive records the source commit, architecture,
dependencies and build environment. The separate BUILD-macos-*.json also
records the extracted-package tests. All archives use the same tagged source.
Building¶
git clone https://github.com/evvaletov/gw-basic-2026.git
cd gw-basic-2026
mkdir -p build
(cd build && cmake ..)
cmake --build build
The binary is build/gwbasic. Run the examples below from the repository root.
Usage¶
Interactive Mode¶
The editor keeps its logical screen size for the session. If a POSIX terminal
shrinks, a viewport follows the cursor and keeps pending commands and INPUT
answers intact; enlarging the window reveals the saved screen cells. The
--full option chooses the logical size from the terminal at startup.
Running build/gwbasic with no arguments launches the full-screen editor:
$ build/gwbasic
GW-BASIC 2026 0.18.3
(C) Eremey Valetov 2026. MIT License.
Based on Microsoft GW-BASIC assembly source.
Ok
PRINT 2+2
4
Ok
FOR I=1 TO 5:PRINT I;:NEXT
1 2 3 4 5
Ok
Use arrow keys to move the cursor freely. Press Enter on any screen line to re-enter it. F1-F10 insert common commands (F2 runs the program).
Entering, replacing, or deleting a numbered program line leaves the cursor ready
for the next line. Direct commands print Ok when they finish. During INPUT
or LINE INPUT, the editor returns the answer following the prompt.
Running a Program File¶
build/gwbasic tests/programs/prime_sieve.bas
Piped Input¶
printf '10 FOR I=1 TO 10:PRINT I*I;:NEXT\nRUN\n' | build/gwbasic
Direct Mode Expressions¶
Type expressions and statements at the Ok prompt:
PRINT SIN(3.14159/2)
1
A$="HELLO WORLD":MID$(A$,7,5)="BASIC":PRINT A$
HELLO BASIC
Command-Line Options¶
Usage: gwbasic [options] [file.bas]
Options:
-f, --full Use full terminal size (default: 25x80)
-h, --help Show this help
--lpt DEVICE|FILE Printer output destination (default: LPT1.TXT)
Use LPT1 or /dev/lp0 for real hardware
-v, --version Show version
Ahead-of-Time Compiler¶
gwbasic-compile reads ASCII .bas programs and emits C source. With -c,
it invokes the gcc command to produce native executables linked against
libgwrt.a. On macOS, Apple’s Command Line Tools provide this command through
Clang; on Linux, install GCC.
Convert a tokenized program with SAVE "program.bas",A before compiling it.
Basic Usage¶
Save this as program.bas:
10 PRINT "HELLO FROM BASIC"
20 END
# Emit C source to stdout
build/gwbasic-compile program.bas
# Compile to native executable
build/gwbasic-compile -c --runtime . program.bas
Both numbered (10 PRINT "HI") and unnumbered (PRINT "HI") sources
compile. Each unnumbered line receives a number ten greater than the previous
line, starting at 10. Explicit line numbers are preserved. Keep the assigned
numbers distinct when mixing the two forms.
Compiler Options¶
Usage: gwbasic-compile [options] input.bas
Options:
-o FILE Output C source file (default: stdout)
-c Compile to executable (invoke gcc)
-O LEVEL Code generation and GCC optimization tier, 0-3 (default: 2)
--keep-c Keep generated C file (with -c)
--runtime DIR Path to runtime headers/library
--warn Static analysis warnings
--safe Runtime safety checks (implies --warn)
--safe=sanitize Above + address/UB sanitizers (with -c)
--no-gc-check Skip per-line garbage collection and Break checks
--fast-math Skip division-by-zero checks
--inline-arrays Use direct indexing for eligible numeric arrays
--emit-obj Compile to an object file (.o)
--main-name N Rename the generated entry point
--max-output-size MB Limit generated C output (default: 256; 0: unlimited)
Optimization Tiers and Arrays¶
-O0 disables constant folding, dead-code removal after unconditional
transfers, and the fast expression emitter in the BASIC compiler. -O1
enables constant folding and dead-code removal; -O2 and -O3 also enable
the fast emitter. The selected level is passed to GCC when compiling C.
FOR/NEXT validation and runtime control-stack behavior are the same at every
tier.
--inline-arrays caches storage for numeric arrays whose DIM bounds are
known at compile time, then indexes that storage directly. The runtime still
owns the array, so delegated statements use the same data. CLEAR and ERASE
invalidate cached pointers. String arrays and arrays with dynamic bounds use
the runtime access path. With --safe, array access uses the checked runtime
path throughout.
Runtime Type Declarations¶
DEFINT, DEFSNG, DEFDBL, and DEFSTR take effect when execution reaches
them, including inside branches, loops and subroutines. Entry-prefix declarations
allow fixed-type native expressions. Programs with later declarations also
compile natively: their expressions carry a runtime type and look up separate
numeric/string scalar and array storage using the current defaults.
Both paths support $EXTERN calls and renamed hosted entry points. Complex
statements and DEF FN bodies continue to use shared runtime handlers, including
foreign calls within their expressions. There is no whole-program interpreter
fallback for DEFTYPE. Runtime-selected arrays use shared lookup even with
--inline-arrays; --safe adds its usual bounds diagnostics. Tagged arithmetic
keeps its checks under --fast-math. GCC optimization and sanitizer options
still apply to the generated C. Hosted entries must run sequentially and cannot
recursively call back into the same runtime.
Performance Flags (--no-gc-check / --fast-math)¶
--no-gc-check skips the gwrt_check_line() call emitted at the start of
every non-REM line. That call updates the current BASIC line number, checks
the string pool for garbage collection, and checks for Ctrl+Break when the
TUI is active. Disabling it can affect error locations and string-space usage.
FRE("") still requests garbage collection explicitly.
--fast-math removes the explicit divide-by-zero check around the /
operator and permits the host floating-point result for a zero divisor.
This flag changes BASIC error behavior; use it only when the program already
validates its divisors.
Memory Safety (--warn / --safe)¶
The --warn flag enables compile-time static analysis warnings:
Uninitialized variables: variables used before their first assignment (via LET, FOR, READ, INPUT)
GOTO/GOSUB to nonexistent line: jump targets that don’t exist in the program
Unreachable code: lines after unconditional GOTO/END/STOP that are not jump targets
The --safe flag (implies --warn) adds runtime safety checks to the
generated C:
Integer overflow detection: generated integer addition, subtraction, multiplication, and negation use checked functions that raise “Overflow”
Enhanced array diagnostics: subscript errors report the array name, subscript value, line number, and which dimension exceeded its bound
GOSUB stack diagnostics: stack overflow reports the source line and current depth
The --safe=sanitize flag (with -c) additionally passes
-fsanitize=address,undefined to GCC. This instruments the generated C;
instrumenting libgwrt.a also requires rebuilding the runtime with those flags.
# Warnings only (zero runtime cost)
build/gwbasic-compile --warn program.bas
# Runtime safety checks
build/gwbasic-compile --safe -c --runtime . program.bas
# Instrument generated C (debugging)
build/gwbasic-compile --safe=sanitize -c --runtime . program.bas
Cross-Language Linking (--emit-obj / --main-name)¶
--emit-obj produces a .o object file instead of a final executable;
--main-name NAME renames the entry point so it doesn’t collide with
the host project’s main(). Together they let you link BASIC into a
larger C or Fortran build.
For example, save this as greet.bas:
10 PRINT "HELLO FROM BASIC"
20 END
# BASIC source compiled to greet.o with renamed entry point
build/gwbasic-compile --emit-obj --main-name=run_basic_greet \
--runtime . greet.bas
Save this C driver as driver.c:
#include <stddef.h>
extern int run_basic_greet(int argc, char **argv);
int main(void) {
run_basic_greet(0, NULL); /* runs the BASIC program */
return 0;
}
Link both together:
gcc driver.c greet.o -L./build -lgwrt -lm -lpthread -lpulse-simple -o greet
Save this Fortran driver as driver.f90 (using iso_c_binding):
program main
use iso_c_binding
interface
function run_basic_greet(argc, argv) bind(c, name="run_basic_greet")
use iso_c_binding
integer(c_int), value :: argc
type(c_ptr), value :: argv
integer(c_int) :: run_basic_greet
end function
end interface
integer(c_int) :: rc
rc = run_basic_greet(0, c_null_ptr)
end program
gfortran driver.f90 greet.o -L./build -lgwrt -lm -lpthread -lpulse-simple -o greet
Omit -lpthread -lpulse-simple in these link commands if the runtime was built
without PulseAudio.
The BASIC code shares the gw interpreter state with libgwrt, so a
single binary runs at most one BASIC program at a time. Do not call a generated
entry point concurrently or recursively. Calls from BASIC to C or Fortran use
the '$EXTERN pragma described next.
Foreign Functions from BASIC ('$EXTERN)¶
A '$EXTERN pragma declares a C function that compiled BASIC can call
directly. It is written as an apostrophe comment, so the interpreter
ignores it while the compiler picks it up. Save this as demo.bas:
10 '$EXTERN Cmul(DOUBLE, DOUBLE) AS DOUBLE
20 '$EXTERN Greet(STRING) AS STRING
30 '$EXTERN Getn AS INTEGER
40 PRINT Cmul(2.5, 4)
50 PRINT Greet("World")
60 PRINT Getn
Type mapping at the boundary:
BASIC type |
C type |
|---|---|
|
|
|
|
|
|
|
|
Save the C implementation as lib.c; it supplies the symbols at link time:
#include <stdint.h>
#include <stdio.h>
int16_t Getn(void) { return 42; }
double Cmul(double a, double b) { return a * b; }
const char *Greet(const char *who) {
static char buf[128];
snprintf(buf, sizeof buf, "Hello, %s!", who);
return buf; /* callee owns the buffer; BASIC copies it */
}
Build and link as in the --emit-obj example above:
build/gwbasic-compile --emit-obj --runtime . demo.bas # -> demo.o
gcc -c lib.c -o lib.o
gcc demo.o lib.o -L./build -lgwrt -lm -lpthread -lpulse-simple -o demo
Notes and constraints:
The function name is matched case-insensitively at the call site (BASIC convention). The emitted C symbol preserves the case written in the pragma:
Cmulcalls C’sCmul.An external call name takes precedence over a variable name in expressions, including
DEF FNbodies. WithQdeclared as a zero-argument external, the body ofDEF FNA(Q)=Q+1calls the externalQ. Use distinct external and parameter names. Static and runtime-typed native builds use this lookup order; the standalone interpreter ignores external declarations.The BASIC call name must be a legal BASIC identifier (it starts with a letter) because the call site is tokenized as ordinary BASIC. To call a C function whose name contains underscores or other characters, add an
= c_symbolalias; the call name stays BASIC-legal, and the emitted C symbol is whatever you write:10 '$EXTERN Cmul(DOUBLE, DOUBLE) AS DOUBLE = c_multiply 20 PRINT Cmul(2.5, 4)
The linked function must have the declared ABI, for example
double c_multiply(double a, double b). Use a C wrapper for APIs with pointers, output parameters, or other unsupported argument types.A string-returning extern works wherever a string expression is expected, including
PRINT,WRITE,INSTR, and string comparison (IF Greet(N$) = "...").String arguments cross as
const char *buffers valid during the call. ASTRINGresult is copied into the BASIC string pool before those argument buffers expire. The callee retains ownership of any buffer it provides.For Fortran callees, declare the routine
bind(c)with a matching name.
Building for DOS / FreeDOS¶
GW-BASIC 2026 cross-compiles to DOS using OpenWatcom V2 (wcc / wcc386).
Two targets are available:
16-bit real-mode (recommended for FreeDOS)¶
Produces a standalone MZ executable that runs without a DOS extender.
wmake -f Makefile.dos16
Requires OpenWatcom V2 with 16-bit DOS target. Uses MEDIUM memory model
(-mm): code can exceed 64KB, data must fit in 64KB.
32-bit DOS/4GW¶
Produces an LE executable requiring DOS4GW.EXE at runtime.
Also builds the compiler (GWBASCOM.EXE) and runtime library (GWRT.LIB).
wmake -f Makefile.dos
Running on FreeDOS¶
Copy GWBASIC.EXE (and DOS4GW.EXE for the 32-bit build) to your FreeDOS
system. Run programs from the command line:
C:\> GWBASIC PROGRAM.BAS
Running without arguments launches the interactive editor. The TUI renders
through BIOS INT 10h with the screen buffer in far memory, so the full-screen
editor, F-key bar, cursor positioning, and scrolling all work on bare FreeDOS
without ANSI.SYS.
Verifying the DOS Build¶
Two automated checks run from a Linux host:
./build_dos.sh 16 # produces gwbasic16.exe
./build_dos.sh 32 # produces gwbasic.exe
bash tests/run_dos_smoke.sh # runs gwbasic16.exe under DOSBox-X, diffs golden
The smoke harness validates non-interactive features (arithmetic, strings, control flow, GOSUB, FOR/NEXT, DATA/READ, DEF FN, file I/O via OPEN/PRINT#). The interactive TUI checks below can be exercised manually under DOSBox-X or real FreeDOS. The v0.18.1 release QA uses a headless FreeDOS/QEMU session for startup, numbered edits, AUTO, INPUT editing and wrapping, break handling, CLS, and exit:
Check |
What to do |
Expected |
|---|---|---|
TUI startup |
Launch |
|
Cursor keys |
Press up/down/left/right |
Cursor moves freely without printing characters |
Re-enter line |
Type |
Line re-tokenized; subsequent |
F1 (LIST) |
Press F1 then Enter |
Inserts |
F2 (RUN) |
Type a program, press F2 |
Runs it ( |
Insert toggle |
Press Ins; type characters mid-line |
Cursor switches between block (insert) and underline (overwrite) shapes; characters insert vs overstrike accordingly |
Home / End |
Press Home, End |
Cursor jumps to column 0 / past last printable char on the row |
Scroll |
Fill the screen with output |
Bottom row pinned to the F-key bar; new lines push old ones up |
Ctrl-C |
Run |
Program stops with |
KEY OFF / KEY ON |
|
F-key bar disappears / reappears |
CLS |
|
Screen clears, cursor at top-left |
Exit |
|
Returns to DOS prompt cleanly (no leftover escape codes) |
The 16-bit build defaults to an 8 KiB string pool to leave room for program
storage and garbage collection in its 64 KiB near-data segment. Other builds
use 32 KiB. Increasing the pool with CLEAR reduces memory available for program
lines and arrays.
The 16-bit link disables OpenWatcom far-call rewriting (OPTION NOFARCALLS).
With the same object files, the default rewrite produced layout-dependent
FreeDOS/JemmEx faults; preserving far calls avoided them. The floating-point
mode remains unchanged. Both build_dos.sh 16 and Makefile.dos16 reserve a
16 KiB stack for nested expression evaluation. Compared with the previous
8 KiB stack, this leaves 8 KiB less near-heap space for program storage,
arrays and the string collector’s scratch buffer.