# cc65 Compiler Intro

## Ullrich von Bassewitz,
CbmNut,
Greg King,
Stephan Mühlstrasser

How to use the cc65 C language system -- an introduction.

## 1. Overview

- 1.1 Before we start
- 1.2 The sample modules
- 1.3 Translation phases

## 2. The compiler

## 3. The assembler

## 4. The linker

## 5. The easy way (using the cl65 utility)

## 6. Running The Executable

- 6.1 Apple
- 6.2 Atari
- 6.3 Atmos
- 6.4 Commodore
- 6.5 GEOS
- 6.6 Ohio Scientific Challenger 1P
- 6.7 Contributions wanted

## 1. Overview

This is a short intro of how to use the compiler and the bin-utils. It contains a step-by-step example of how to build a complete application from one C and one assembly modules. This file does not contain a complete reference for the tools used in the process. There are separate files describing those tools, in detail (see index.html).

I do assume that you have downloaded and installed the compiler and target-specific files. Windows users should use the friendly .exe installer (named cc65-2.13.0-1.exe for version 2.13.0 of the package - adjust the version number if necessary). It does not only install the target files, but will also set up necessary environment variables for you.

If you're going for the .ZIP archives, please note that there is one file for the host platform (Windows, DOS or OS/2), one file for each target platform (C64 or whatever) and a separate file containing the docs (which include the file you're currently reading). So for most uses, you will need at least 3 files and unpack all three into one directory. In case of the .ZIP archives, you will also need to set the environment variables `CC65_INC`, `LD65_LIB` and `LD65_CFG` as described below.

Note: There is a much simpler way to compile this example, by using the cl65 compile-and-link utility. However, it makes sense to understand how the separate steps work. How to do the example with the cl65 utility is described later.

## 1.1 Before we start

You will find a copy of the sample modules, used in the next section, in the "`cc65/samples/tutorial`" directory. If you encounter problems with missing include files and/or libraries, please check the environment variables `CC65_INC`, `LD65_LIB` and `LD65_CFG`. They should point to the `include`, `lib` and `cfg` subdirectories of the directory, where you installed cc65.

## 1.2 The sample modules

To explain the development flow, I will use the following example modules:

hello.c:

> `

>             #include <stdio.h>
>             #include <stdlib.h>

>             extern const char text[];       /* In text.s */

>             int main (void)
>             {
>                 printf ("%s\n", text);
>                 return EXIT_SUCCESS;
>             }

> `

text.s:

> `

>             .export _text
>             _text:  .asciiz "Hello world!"

> `

## 1.3 Translation phases

We assume that the target file should be named "hello", and the target system is the C64.

> `

>         +---------+
>         | hello.c |
>         +---------+
>              |
>             cc65
>              \/
>         +---------+       +---------+       +---------+
>         | hello.s |       | text.s  |       | crt0.o  |
>         +---------+       +---------+       +---------+
>              |                 |                 |
>             ca65              ca65              ar65
>              \/                \/                \/
>         +---------+       +---------+       +---------+
>         | hello.o |       | text.o  |       | c64.lib |
>         +---------+       +---------+       +---------+
>              |                    \          /
>              |                     \        /
>              |                      \      /
>              +----------------------->ld65<
>                                        \/
>                                      hello

> `

`crt0.o` (the startup code) and `c64.lib` (the C64 version of the runtime and C library) are provided in binary form in the cc65 package. Actually, the startup code is contained in the library, so you won't need to care about it.

## 2. The compiler

The compiler translates one C source into one assembly source, for each invocation. It does not create object files directly, and it is not able to translate more than one file per run.

In the example above, we would use the following command line, to translate `hello.c` into `hello.s`:

> `

>             cc65 -O -t c64 hello.c

> `

The `-O` switch tells the compiler to do an additional optimizer run, which is usually a good idea, since it makes the code smaller. If you don't care about the size, but want to have slightly faster code, use `-Oi` to inline some runtime functions.

The `-t` switch is followed by the target system name.

If the compiler does not complain about errors in our "hello world" program, we will have a file named "`hello.s`", in our directory, that contains the assembly source for the hello module.

For more information about the compiler, see cc65.html.

## 3. The assembler

The assembler translates one assembly source into an object file, for each invocation. The assembler is not able to translate more than one source file per run.

Let's translate the "hello.s" and "text.s" files from our example:

> `

>             ca65 hello.s
>             ca65 -t c64 text.s

> `

The `-t` switch is needed when translating the `text.s` file, so the text is converted from the input character-set (usually ISO-8859-1) into the target character-set (PETSCII, in this example) by the assembler. The compiler-generated file `hello.s` does not contain any character constants, so specification of a target is not necessary (it wouldn't do any harm, however).

If the assembler does not complain, we should now have two object files (named `hello.o` and `text.o`) in the current directory.

For more information about the assembler, see ca65.html.

## 4. The linker

The linker combines several object and library files into one output file. ld65 is very configurable, but fortunately has built-in configurations, so we don't need to mess with configuration files, here.

The compiler uses small functions to do things that cannot be done inline without a big impact on code size. Those runtime functions, together with the C library, are in an object-file archive named after the system, in this case, "`c64.lib`". We have to specify that file on the command line, so that the linker can resolve those functions.

Let's link our files to get the final executable:

> `

>             ld65 -o hello -t c64 hello.o text.o c64.lib

> `

The argument after `-o` specifies the name of the output file, the argument after `-t` gives the target system. The following arguments are object files or libraries. Since the target library resolves imports in `hello.o` and `text.o`, it must be specified after those files.

After a successful linker run, we have a file named "`hello`", ready for our C64!

For more information about the linker, see ld65.html.

## 5. The easy way (using the cl65 utility)

The cl65 utility is able to do all of the steps described above, in just one command line, and it has defaults for some options that are very well-suited for our example.

To compile both files into one executable, enter:

> `

>             cl65 -O hello.c text.s

> `

The cl65 utility knows how to translate C files into object files (it will call the compiler, and then the assembler). It does know also how to create object files from assembly files (it will call only the assembler, for that). It knows how to build an executable (it will pass all object files to the linker). And finally, it has the C64 as a default target, and will supply the correct startup file and runtime library names to the linker, so you don't have to care about that.

The one-liner above should give you a C64 executable named "`hello`" in the current directory.

For more information about the compile & link utility, see cl65.html.

## 6. Running The Executable

Note: this section is incomplete!

Depending on the target, cc65 chooses several methods of making a program available for execution. Here, we list sample emulators and instructions for running the program. Unless noted, similar instructions would also apply to a real machine. One word of advice: we suggest you clear the screen at the start, and wait for a keypress at the end of your program, as each target varies in its start and exit conditions.

## 6.1 Apple

### AppleWin

Available at https://github.com/AppleWin/AppleWin:

Emulates Apple ][/enhanced Apple //e computers, with sound, video, joysticks, serial port, and disk images. Includes monitor. Only for Windows. The package comes with a DOS 3.3 disk (called "master.dsk") image; however, you will need AppleCommander 1.4.0 or later (available at https://applecommander.github.io/).

Compile the tutorial with

> `

>     cl65 -O -t apple2 hello.c text.s

> `

for the Apple ][, or:

> `

>     cl65 -O -t apple2enh hello.c text.s

> `

for the enhanced Apple //e.

Then, put the file onto an Apple disk image, for use with an emulator. Copy the `master.dsk` which comes with AppleWin, and rename it to `cc65.dsk`, then use AppleCommander:

> `

>     java -jar ac.jar -as cc65.dsk test < hello

> `

Note that a convention in the Apple world is that "hello" is the file which is run automatically upon booting a DOS disk, sort of like the "autoexec.bat" of the MSDOS/Windows world. We've avoided that in the example, however by using "test" as the name of the program as it will appear on the Apple disk.

Start the emulator, click on the Disk 1 icon, and point to cc65.dsk; then, click the big Apple logo, to boot the system. Then, type this on the Apple:

> `

>     BRUN TEST

> `

You will see "Hello, World!" appear on the same line. Thanks to Oliver Schmidt for his help in completing this section.

## 6.2 Atari

### Atari800Win PLus

Available at http://www.atari.org.pl/PLus/index_us.htm:

Emulates Atari 400/800/65XE/130XE/800XL/1200XL/5200, with stereo sound, disk images, scanline-exact NTSC/PAL video, joysticks, mouse, cartridges, and RAM expansions. Includes monitor. Unfortunately, only for Windows. You will need the emulator, "atarixl.rom" or "atariosb.rom"/"ataribas.rom", and "dos25.xfd" files (not supplied).

Compile the tutorial with

> `

>     cl65 -O -t atari hello.c text.s

> `

Start the emulator, choose File>Autoboot image or File>Load executable, and point to the "hello" executable. It is customary to rename executables of that type to "hello.xex". The file has a 7-byte header meant to be loaded directly from Atari DOS 2/2.5 or compatibles.

On a real Atari, you would need a disk drive, and Atari DOS 2.5 or compatible. Turn on the computer, type

> `

>     DOS

> `

at the BASIC prompt, then choose N. CREATE MEM.SAV, then choose L. BINARY LOAD, and enter `HELLO`.

The emulation, also, supports that method. Look at Atari>Settings, and check Enable H: Patch for Hard Disk Devices, then Atari>Hard disks, and set the path of H1: to your executables directory, then use "H0:HELLO.XEX" in the above procedure (after pressing `L`), to access your harddrive directly.

Note: There is no delay after the program exits, as you are returned to the DOS menu. Your C program should wait for a keypress if you want to see any output.

### Stella

Available at http://stella.sourceforge.net:

Stella is a multi-platform Atari 2600 VCS emulator. The latest version is available on the emulator's website. It is also available through the package manager of most Linux distributions (Fedora, Ubuntu, ..).

Compile the Atari 2600 sample with

> `

>     make SYS=atari2600 samples

> `

Then execute it with

> `

>     stella samples/atari2600hello

> `

### Harmony Cartridge

Available at http://harmony.atariage.com/Site/Harmony.html:

The Harmony Cartridge allows running any Atari 2600 binary on real hardware. The binary must be copied on an SD card, to be inserted in the Harmony Cartridge. It can then be inserted on an Atari 2600 console, and run any binary on the SD card.

## 6.3 Atmos

### Oricutron

Available at http://code.google.com/p/oriculator/:

Emulates Oric-1 and Atmos computers, with sound, disk images, scanline-exact NTSC/PAL video, and movie export. Includes a monitor. Fortunately, for all SDL platforms. You will need just the emulator; all ROMs are supplied.

Compile the tutorial with

> `

>     cl65 -O -t atmos hello.c text.s -o hello.tap

> `

Start the emulator, choose F1 and Insert tape..., and point to the "hello.tap" executable. After it has finished loading, type

> `

>     RUN

> `

On a real Atmos, you would need a tape drive. Turn on the computer, type

> `

>     CLOAD""

> `

at the BASIC prompt. After it has finished loading, type

> `

>     RUN

> `

The emulation, also, supports that method.

## 6.4 Commodore

### VICE

Available at http://vice-emu.sourceforge.net/:

Emulates Commodore 64/128/VIC-20/PET/CBM II/Plus 4 computers. Supports printers, serial port and adapters, stereo sound, disk drives and images, RAM expansions, cartridges, ethernet connection, cycle-exact NTSC/PAL video, mice, graphics tablet, lightpens, and joysticks. Includes monitor. Runs on MSDOS/PCDOS, Win9x/ME/NT/2000/XP, OS2, BeOS x86, Acorn RISC OS, and most Unixes.

Compile the tutorial with

> `

>     cl65 -O -t <sys> hello.c text.s

> `

Substitute the name of a Commodore computer for that `<sys>`:

- `c128`
- `c16`
- `c64`
- `cbm510`
- `cbm610`
- `pet`
- `plus4`
- `vic20`

Start the desired version of the emulator (CBM610 programs run on the CBM II [`xcbm2`] emulator).

In the Windows versions of VICE, choose File>Autoboot disk/tape image..., choose your executable, and click OK.

In the Unix versions, hold down the mouse's first button. Move the pointer to Smart-attach disk/tape..., and release the button. Choose your executable, and click Autostart.

The file has a 14-byte header which corresponds to a PRG-format BASIC program, consisting of a single line, similar to this:

> `

>     1000 sys2061

> `

On a real Commodore with attached disk drive, you would type:

> `

>     LOAD "0:HELLO",8

> `

for VIC-20/C64, or:

> `

>     DLOAD "HELLO"

> `

on PET/CBM II/C128/C16/Plus 4; then, type

> `

>     RUN

> `

On a Commodore 128, you can combine those two commands:

> `

>     RUN "HELLO"

> `

The output will appear on a separate line, and you will be returned to a BASIC prompt.

## 6.5 GEOS

Available at Click Here Software's GEOS download section:

Graphics Environment Operating System. It provides a WIMP GUI (Windows, Icons, and Mouse-Pointer Graphical User Interface) for Commodore's computer models 64 and 128. It can be controlled by many different types of input devices:

- keyboard
- joysticks
- mice
- trackballs
- graphics drawing tablets
- light-pens

The tutorial files are different for GEOS. You will find them "next door," in "`cc65/samples/geos`"; they are called "`hello1.c`" and "`hello1res.grc`".

Compile the tutorial with

> `

>     cl65 -t geos-cbm -O -o hello1 hello1res.grc hello1.c

> `

Copy the resulting file "`hello1`" onto a (GEOS-format) disk.

Boot the GEOS master disk/image.

> When you want to run GEOS in an emulator, you must adjust that emulator so that it does a "true drive" emulation. Each emulator has its own way of turning that feature on.

> VICE even has different ways that depend on which operating system is running the emulator.
> - In Windows, you must click on Options (in an always visible menu). Then, you must click on True drive emulation.
> - In Unix, you must hold down the second button on your mouse. Move the pointer down to Drive settings. Then, move the pointer over to Enable true drive emulation. (If there is a check-mark in front of those words, that feature already is turned on -- then, move the pointer off of that menu.) Release the mouse button.

Find the CONVERT program on the boot disk [tap the 6-key; then, you should see its icon in the fourth position on the deskTop's directory notePad]. Move GEOS's pointer over to CONVERT's icon; double-click it to run that program. Click on the Disk icon; put the disk with "`hello1`" into the drive; and, click the OK icon. Use the little icons under the list of file-names to move through that list until you find "`hello1`". Click on it; and then, click on the Convrt icon. CONVERT will ask you to confirm that you choose the correct file; click YES if you did (or, click NO if you made a mistake). After the program has converted "`hello1`" from a CBM file into a GEOS file, it will announce what it did -- click on OK. CONVERT will show the file list again. This time, click on Quit.

(You might need to put the boot disk back into the drive, in order to reload deskTop. Then, you must swap back to the disk with the tutorial program on it, and click on its disk icon [on the right side of the screen].)

Now, you must find hello1. Click on the lower left-hand corner of the directory notePad. Look at the eight file-positions on each page until you see hello1. Double-click on its icon.

The output is shown in a GEOS dialog box; click OK when you have finished reading it.

## 6.6 Ohio Scientific Challenger 1P

The `osic1p` runtime library returns to the boot prompt when the main() program exits. Therefore, the C file in the tutorial must be modified slightly, in order to see the results on the screen. Otherwise, the program would print the text string, and then jump to the boot prompt, making it impossible to see the results of running the tutorial program.

In addition to that, the `osic1p` target does not yet have support for stdio functions. Only the functions from the conio library are available.

Therefore, modify the "`hello.c`" source file, as follows:

> `

>     #include <conio.h>
>     #include <stdlib.h>

>     extern const char text[];       /* In text.s */

>     int main (void)
>     {
>         clrscr ();
>         cprintf ("%s\r\nPress <RETURN>.\r\n", text);
>         cgetc ();
>         return EXIT_SUCCESS;
>     }

> `

Compile the tutorial with

> `

>     cl65 -O -t osic1p -u __BOOT__ -o hello.lod hello.c text.s

> `

The program is configured for a Challenger 1P computer with, at least, 32 kB of RAM. See the Ohio Scientifc-specific documentation for instructions about how to compile for other RAM sizes.

Plug a cassette player into your C1P computer; or, connect an RS-232 cable between your C1P and a PC (set the PC's serial port to 300 Bits Per Second, 8 data bits, No parity, and 2 stop bits). (Turn on the computers.)

Tap the "BREAK" key, to display the boot prompt; then, tap the "`M`" key, to enter the 65V PROM monitor. Tap the "`L`" key. Either start the cassette player (with a tape of the program), or start a transfer of the program file "`hello.lod`" from the PC. After a while, you should see the following text on the screen:

> `

>     Hello world!
>     Press <RETURN>.

> `

(Stop the cassette player.) After hitting the RETURN key, you should see the boot prompt again.

### WinOSI

Available at http://osi.marks-lab.com/#Emulator:

Emulates the Ohio Scientific Challenger computers in different configurations. Configure it to emulate a C1P (model 600 board) with 32 kB of RAM.

Compile the tutorial with the same command that is used to make the program for a real machine.

Start the emulator. Tap the "`M`" key, to enter the 65V PROM monitor; then, tap the "`L`" key. If you had configured WinOSI to ask for a file when it starts to read data from the serial port, then you will see a file dialog box; otherwise, you must tap your host keyboard's F10 function key. Select the file "`hello.lod`". After a moment, you should see the following text on the screen:

> `

>     Hello world!
>     Press <RETURN>.

> `

After hitting the RETURN key, you should see the boot prompt again.

### C1Pjs

Available at http://www.pcjs.org/docs/c1pjs/:

Emulates the Ohio Scientific Challenger 1P computer in different configurations. The 32 kB RAM machine that must be used with the default compiler settings is here.

In addition to cc65, the srec_cat program from the SRecord tool collection must be installed. Some Linux distributions also provide srecord directly as an installable package.

Compile the tutorial with this command line:

> `

>     cl65 -O -t osic1p hello.c text.s

> `

Convert the binary file into a text file that can be loaded via the Ohio Scientific 65V PROM monitor, at start address 0x200:

> `

>     srec_cat hello -binary -offset 0x200 -o hello.c1p -Ohio_Scientific -execution-start-address=0x200

> `

Open the URL that points to the 32 kB machine; and, wait until the emulator has been loaded. Click on the "BREAK" button to display the boot prompt; then, press the "`M`" key to enter the 65V PROM monitor. Click the "Browse..." button; and, select the file "`hello.c1p`" that was created as the output of the above invocation of the "`srec_cat`" command. Press the "Load" button. You should see the following text on the screen:

> `

>     Hello world!
>     Press <RETURN>.

> `

After hitting the RETURN key, you should see the boot prompt again.

## 6.7 Contributions wanted

We need your help! Recommended emulators and instructions for other targets are missing. We suggest that you choose emulators with good compatibility. Also, being able to run all computers in the target series is good for target compatibility testing. A machine-language monitor is almost essential for debugging, but a native debugger could be used, as well.

Finally, emulators which run on Unix or Windows would help to reach a wider audience.