Programming the Atari 8-bit in C with cc65

GRAPHICS 0 screen reading MOVE WITH JOYSTICK, FIRE TO QUIT with an asterisk in the middle

cc65 is a free C compiler and toolchain for 6502 machines, and the Atari 8-bit has been one of its best-supported targets for decades. The package includes the compiler (cc65), a macro assembler (ca65), a linker (ld65) and a one-step front end (cl65). Real Atari software built with it includes the IP65 network stack and the FujiNet example templates. C won't match hand-tuned assembly for speed, but it gets you working, maintainable programs quickly, and you can drop to ca65 for the parts that need speed.

What you'll learn: choosing a target, the memory map cc65 gives you, compiling and running a program, talking to the OS and hardware from C, using drivers, writing assembly with ca65, the linker configurations, and source-level debugging in Altirra.

What you need: a cc65 release or snapshot for your OS, with its bin directory on your PATH, plus Altirra or atari800.

1. Two targets: atari and atarixl

-t atari -t atarixl
Runs on Every Atari 8-bit XL and newer only (not the 600XL)
Default load address $2000 $2400
Usable RAM (BASIC off) $2000–$BC1F load address–$CFFF, plus RAM under the ROM
Screen Wherever the OS puts it (read SAVMSC, $58) Moved below the program
Notes The recommended default Banks the OS ROM out. Clears the screen at start and exit. Not compatible with DOSes that use RAM under the ROM. _sys() is unsupported.

Use atari unless you really need the extra memory. The default atari linker configuration assumes the BASIC ROM is disabled: hold OPTION while booting an XL/XE, or remove the BASIC cartridge.

2. Hello, Atari

/* joy.c - move a star with the joystick, fire to quit */
#include <atari.h>
#include <conio.h>
#include <joystick.h>

int main(void)
{
    unsigned char joy, x = 20, oldx = 20;

    joy_install(joy_static_stddrv);
    clrscr();
    OS.color4 = 0x00;              /* border, shadow at $2C8 */
    OS.color2 = 0x84;              /* GR.0 background, shadow at $2C6 */
    cputsxy(2, 2, "MOVE WITH JOYSTICK, FIRE TO QUIT");

    for (;;) {
        waitvsync();                /* one step per frame */
        joy = joy_read(JOY_1);
        if (JOY_BTN_1(joy)) break;
        if (JOY_LEFT(joy)  && x > 0)  --x;
        if (JOY_RIGHT(joy) && x < 39) ++x;
        if (x != oldx) { cputcxy(oldx, 12, ' '); oldx = x; }
        cputcxy(x, 12, '*');
    }
    joy_uninstall();
    return 0;
}

Build and run:

cl65 -t atari -O -o joy.xex joy.c

Load joy.xex in Altirra with File > Boot Image, or copy it to a DOS disk and binary-load it.

The ingredients:

  • atari.h declares a structure called OS that is laid over page zero and pages two and three. It uses the familiar names: OS.savmsc, OS.color4, OS.stick0, OS.ch, OS.rtclok[3], OS.sdmctl, OS.sdlst, OS.chbas. Location 762 ($2FA) is called char_ because char is a C keyword. A BASIC structure covers BASIC's zero-page variables.
  • Hardware is reached through GTIA_WRITE/GTIA_READ ($D000), POKEY_WRITE/POKEY_READ ($D200), ANTIC ($D400) and PIA. For example, ANTIC.wsync = 0; waits for the end of the scan line.
  • Atari helpers include _graphics(mode) (same numbers as BASIC's GRAPHICS), _setcolor/_setcolor_low, _sound(voice, freq, dist, vol), waitvsync(), get_ostype(), get_tv() and _dos_type.
  • Function keys in conio are mapped to Atari plus a number key. cc65 parses command-line arguments for DOSes that pass them (up to 16, including the program name).

3. The memory picture and what it means

On the atari target the C stack starts at MEMTOP ($2E5) and grows down, and the heap grows up from the end of your program. The executable has two load chunks:

  1. A "system check" chunk, always loaded at $2E00. It aborts the load if there isn't enough memory or if the start address is below MEMLO.
  2. The main program at the start address.

If you leave the program in GRAPHICS 0, nothing else needs doing. If you'll switch to a bigger graphics mode, you must reserve memory at the top for its screen, or the graphics call will overwrite your stack. Typical figures, measured with a BASIC program: about 7,120 bytes for GRAPHICS 8 or 15, 3,198 for GRAPHICS 7, and 7,146 for the GTIA modes 9–11. They are rules of thumb only, because screen memory has alignment requirements.

cl65 -t atari -O -Wl -D__RESERVED_MEMORY__=7120 -o pic.xex pic.c

You can move the start address with --start-addr, and drop the system-check chunk (handy while debugging) with:

cl65 -t atari -Wl -D__SYSTEM_CHECK__=1 -o prog.xex prog.c

4. Drivers: graphics, joysticks, mice, memory

cc65 ships loadable drivers, which you can also link statically using the symbol names shown in brackets:

  • TGI graphics: atr3.tgi to atr15p2.tgi cover CIO modes 3–15, including double-buffered "p2" versions of modes 8, 9, 10 and 15, and GTIA 9/10/11. The default is atr8.tgi (320×192, two colours). For atarixl the names are atrx….
  • Joysticks: atrstd.joy handles the standard ports (four on 400/800, two on XL and later), and atrmj8.joy handles eight sticks on a MultiJoy adapter.
  • Mice: ST mouse, Amiga mouse, Atari trak-ball, touch tablet, or a joystick acting as a mouse. All connect to port 1. The P/M-graphics cursor uses page six ($600–$6FF), so your program can't use player-missile graphics as well.
  • Extended memory: atr130.emd gives access to a 130XE's second 64K.
  • Serial: atrrdev.ser works through an installed R: handler at up to 9600 baud with RTS/CTS. It was tested with the 850 interface.

5. Display lists, character codes and alignment

_antic.h provides display-list instruction macros, and cc65's "void variable" extension lets you write a display list as data:

unsigned char ScreenMemory[100];
void DisplayList = {
    DL_BLK8, DL_BLK8, DL_BLK8,
    DL_LMS(DL_CHR20x8x2), ScreenMemory,
    DL_CHR20x8x2, DL_CHR20x8x2, DL_CHR20x8x2,
    DL_BLK4, DL_CHR20x8x2,
    DL_JVB, &DisplayList
};
/* ... */
OS.sdlst = &DisplayList;

ANTIC has alignment rules for display lists, screen memory, fonts and P/M data. Usually you'll need a custom linker config with aligned segments, or posix_memalign() plus a copy. Strings use ATASCII by default. Include atari_screen_charmap.h to get internal screen codes for direct screen pokes, and atari_atascii_charmap.h to switch back. Remember that the internal code for a space is 0, so C string functions will stop there.

6. Assembly with ca65

ca65 uses the same object format and the same atari.inc equates as the C library. The repository's targettest/atari/asm-xex.s is a complete minimal program that prints through CIO:

        .include "atari.inc"
        .export  start

.proc   puts
        sta     ICBAL
        stx     ICBAH
        lda     #PUTREC
        sta     ICCOM
        ldx     #$FF
        stx     ICBLL
        inx
        stx     ICBLH
        jsr     CIOV
        rts
.endproc

.proc   start
        lda     #<msg
        ldx     #>msg
        jsr     puts
        rts
.endproc

msg:    .byte   "Hello world", ATEOL

(The original also has a short delay loop before returning.) Build it with:

cl65 -tatari -Catari-xex.cfg asm-xex.s -o prog.xex

That is the command given in the file's own header. Built this way, the program also gets the C library's system-check chunk at $2E00, and ld65 2.19 warns that segment STARTUP does not exist. For pure assembly, -Catari-asm-xex.cfg gives a cleaner result: one 44-byte segment at $2E00 plus the RUNAD segment.

You mix C and assembly by exporting _name symbols from ca65 files and declaring them extern in C. Atari-specific interrupt routines can be hooked into the runtime's VBI with the .INTERRUPTOR feature. On the Atari these run in NMI context.

7. Linker configurations

Config (-C) Purpose
atari.cfg (default) C programs at $2000, with the system-check chunk
atari-asm.cfg Assembly at $2E00. Define __AUTOSTART__ and/or __EXEHDR__ to drop the run trailer and/or the header and get a raw binary
atari-xex.cfg, atari-asm-xex.cfg Use ld65's native Atari XEX output: each MEMORY area becomes a segment, and you can give an INITAD per area
atari-cart.cfg 8K or 16K cartridges (-D__CARTSIZE__=0x4000). The option byte at $BFFD comes from __CARTFLAGS__
atari-cassette.cfg Cassette boot files up to 32K. util/w2cas.com writes them to tape on a real Atari
atarixl*.cfg Equivalents for the XL target, including atarixl-largehimem.cfg

8. Debugging in Altirra

Compile with -g and ask the linker for a debug-info file:

cl65 -t atari -g -O -Wl --dbgfile,joy.dbg -o joy.xex joy.c

Altirra's symbol loader understands ld65 debug files, and when you boot joy.xex it looks for a matching .dbg alongside .lst, .lab and .lbl. You can also load one by hand with .loadsym joy.dbg. Note that Altirra refuses ca65 listing files ("CA65 listings are not supported"), so use the debug file. A map file (-m joy.map) is the quickest way to find out where your code and data ended up.

Troubleshooting

  • The program won't load; it drops back to DOS at once. The system check failed. Your DOS's MEMLO is above the start address, or there isn't enough RAM. Raise --start-addr, or use a DOS with lower MEMLO.
  • GRAPHICS 8 corrupts variables or crashes. You didn't reserve the screen memory. See section 3.
  • ld65: Error: Duplicate external … when building from an IDE "run" button. The tool is compiling more files than you intended, or linking the same object twice. Run cl65 by hand from a terminal and add files one at a time.
  • Strings appear as garbage on direct screen writes. You're poking ATASCII where screen codes are expected. Use the screen charmap header.
  • Programs are slow. Prefer unsigned char loop variables. Make hot locals static, or compile with -Cl. Use -Oirs. Move inner loops to ca65.

Further reading

  • The doc/ folder of the cc65 distribution: atari.html (this platform), cl65.html, ld65.html (config file syntax) and funcref.html (every library function).
  • samples/ and targettest/atari/ in the cc65 source tree, for example displaylist.c and charmapping.c.
  • The FujiNet boot-disk-cc65-template project builds a bootable single-density ATR from cc65 code.

Credits