cc65 Users Guide
1. Overview
cc65 was originally a C compiler for the Atari 8-bit machines written by John R. Dunning. In prior releases I've described the compiler by listing up the changes made by me. I have made many more changes in the meantime (and rewritten major parts of the compiler), so I will no longer do that, since the list would be too large and of no use to anyone. Instead I will describe the compiler in respect to the ANSI/ISO C standard.
There is a separate document named funcref.html that covers the library available for the compiler, including which standard functions are missing or limited on this target. If you know C, and are interested in doing actual programming, the library documentation is probably of much more use than this document.
This tree targets the Atari Lynx exclusively and contains Lynx-specific
code-generation improvements (65C02 runtime fast paths, direct 65C02
emission, jump-table switches, and self-modifying-code runtime variants).
See Optimizations & Limitations for a
summary and design/LYNX_CODEGEN_DESIGN.md in the source tree for the full
design and measurements.
If you need some hints for getting the best code out of the compiler, you may have a look at coding.html which covers some code generation issues.
2. Usage
The compiler translates C files into files containing assembly code that may be translated by the ca65 macroassembler (for more information about the assembler, have a look at ca65.html).
2.1. Command line option overview
The compiler may be called as follows:
--------------------------------------------------------------------------- Usage: cc65 [options] file Short options: -Cl Make local variables static -Dsym[=defn] Define a symbol -E Stop after the preprocessing stage -I dir Set an include directory search path -O Optimize code -Oi Optimize code, inline more code -Or Enable register variables -Os Inline some standard functions -T Include source as comment -V Print the compiler version number -W warning[,...] Suppress warnings -d Debug mode -g Add debug info to object file -h Help (this text) -j Default characters are signed -o name Name the output file -r Enable register variables -t sys Set the target system -v Increase verbosity Long options: --add-source Include source as comment --all-cdecl Make functions default to __cdecl__ --bss-name seg Set the name of the BSS segment --check-stack Generate stack overflow checks --code-name seg Set the name of the CODE segment --codesize x Accept larger code by factor x --cpu type Set cpu type (65C02, 65SC02) --create-dep name Create a make dependency file --create-full-dep name Create a full make dependency file --data-name seg Set the name of the DATA segment --debug Debug mode --debug-info Add debug info to object file --debug-opt name Configure optimizations with a file --debug-opt-output Debug output of each optimization step --dep-target target Use this dependency target --disable-opt name Disable an optimization step --eagerly-inline-funcs Eagerly inline some known functions --enable-opt name Enable an optimization step --help Help (this text) --include-dir dir Set an include directory search path --inline-stdfuncs Inline some standard functions --list-opt-steps List all optimizer steps and exit --list-warnings List available warning types for -W --local-strings Emit string literals immediately --register-space b Set space available for register variables --register-vars Enable register variables --rodata-name seg Set the name of the RODATA segment --signed-chars Default characters are signed --static-locals Make local variables static --target sys Set the target system --verbose Increase verbosity --version Print the compiler version number --writable-strings Make string literals writable ---------------------------------------------------------------------------
2.2. Command line options in detail
Here is a description of all the command line options:
--all-cdecl-
Tells the compiler that functions which aren't declared explicitly with either the
__cdecl__or__fastcall__calling conventions should have the cdecl convention. (Normally, functions that aren't variadic are fast-called.) --bss-name seg-
Set the name of the bss segment. See also
#pragma bss-name. --check-stack-
Tells the compiler to generate code that checks for stack overflows. See
#pragma check-stackfor an explanation of this feature. --code-name seg-
Set the name of the code segment. See also
#pragma code-name --codesize x-
This options allows finer control about speed vs. size decisions in the code generation and optimization phases. It gives the allowed size increase factor (in percent). The default is 100 when not using
-Oiand 200 when using-Oi(-Oiis the same as-O --codesize 200). --cpu type-
Accepted for backwards compatibility only. The valid arguments are
65C02and65SC02; any other value is an error. The argument is otherwise ignored, because the compiler always generates code for the Lynx's 65SC02. See also-t, --target. --create-dep name-
Tells the compiler to generate a file containing the dependency list for the compiled module in makefile syntax. The output is written to a file with the given name. The output does not include system include files (in angle brackets).
--create-full-dep name-
Tells the compiler to generate a file containing the dependency list for the compiled module in makefile syntax. The output is written to a file with the given name. The output does include system include files (in angle brackets).
--data-name seg-
Set the name of the data segment. See also
#pragma data-name -d, --debug-
Enables debug mode, for debugging the behavior of cc65.
--debug-opt name-
The named file contains a list of specific optimization steps to enable or disable. Each line contains the name of an optimization step with either a
+(enable) or-(disable) prefix. The nameallcan be used to enable or disable all optimizations. Comment lines may begin with#or;.Use
--list-opt-stepsto generate a complete list of available optimization steps.Use
--debugto see a list of optimizations applied during compilation. --debug-opt-output-
For debugging the output of each optimization pass, step by step. Generates a
name.optoutput listing for each optimized functionname. --dep-target target-
When generating a dependency file, don't use the actual output file as the target of the dependency, but the file specified with this option. The option has no effect if neither
--create-depnor--create-full-depis specified. -D sym[=definition]-
Define a macro on the command line. If no definition is given, the macro is defined to the value "1".
-g, --debug-info-
This will cause the compiler to insert a
.DEBUGINFOcommand into the generated assembler code. This will cause the assembler to include all symbols in a special section in the object file. --eagerly-inline-funcs-
Have the compiler eagerly inline these functions from the C library:
-
memcpy() -
memset() -
strcmp() -
strcpy() -
strlen()
Note: This has two consequences:
-
You may not use names of standard C functions for your own functions. If you do that, your program is not standard-compliant anyway; but, using
--eagerly-inline-funcsactually will break things. -
The inlined string and memory functions will not handle strings or memory areas larger than 255 bytes.
--eagerly-inline-funcsimplies the--inline-stdfuncscommand line option.See also
#pragma allow-eager-inline. -
-h, --help-
Print the short option summary shown above.
--inline-stdfuncs-
Allow the compiler to inline some standard functions from the C library like strlen. This will not only remove the overhead for a function call, but will make the code visible for the optimizer. See also the
-Oscommand line option and#pragma inline-stdfuncs. --list-warnings-
List the names of warning types available for use with
-W. --local-strings-
Emit string literals into the rodata segment as soon as they're encountered in the source (even if you do nothing but get the sizeof those strings). The default is to keep string literals until end of assembly, merge read only literals if possible, and then output the literals into the data or rodata segment that is active at that point. Use of this option prevents merging of duplicate strings, but the options that change the name of one of the data segments will work.
You can also use
#pragma local-stringsfor fine grained control. -o name-
Specify the name of the output file. If you don't specify a name, the name of the C input file is used, with the extension replaced by ".s".
-r, --register-vars-
-rwill make the compiler honor theregisterkeyword. Local variables may be placed in registers (which are actually zero page locations). There is some overhead involved with register variables, since the old contents of the registers must be saved and restored. Since register variables are of limited use without the optimizer, there is also a combined switch:-Orwill enable both, the optimizer and register variables.For more information about register variables see register variables.
The compiler setting can also be changed within the source file by using
#pragma register-vars. --register-space-
This option takes a numeric parameter and is used to specify, how much zero page register space is available. Please note that just giving this option will not increase or decrease by itself, it will just tell the compiler about the available space. You will have to allocate that space yourself using an assembler module with the necessary allocations, and a linker configuration that matches the assembler module. The default value for this option is 6 (bytes).
If you don't know what all this means, please don't use this option.
--rodata-name seg-
Set the name of the rodata segment (the segment used for readonly data). See also
#pragma rodata-name -j, --signed-chars-
Using this option, you can make the default characters signed. Since the 6502 has no provisions for sign extending characters (which is needed on almost any load operation), this will make the code larger and slower. A better way is to declare characters explicitly as "signed" if needed. You can also use
#pragma signed-charsfor better control of this option. -v, --verbose-
Using this option, the compiler will be somewhat more verbose if errors or warnings are encountered.
--writable-strings-
Make string literals writable by placing them into the data segment instead of the rodata segment. You can also use
#pragma writable-stringsto control this option from within the source file. -Cl, --static-locals-
Use static storage for local variables instead of storage on the stack. Since the stack is emulated in software, this gives shorter and usually faster code, but the code is no longer reentrant. The difference between
-Cland declaring local variables as static yourself is, that initializer code is executed each time, the function is entered. So when usingvoid f (void) { unsigned a = 1; ... }the variable
awill always have the value1when entering the function and using-Cl, while invoid f (void) { static unsigned a = 1; .... }the variable
awill have the value1only the first time that the function is entered, and will keep the old value from one call of the function to the next.You may also use
#pragma static-localsto change this setting in your sources. -I dir, --include-dir dir-
Set a directory where the compiler searches for include files. You may use this option multiple times to add more than one directory to the search list.
-O, -Oi, -Or, -Os-
Enable an optimizer run over the produced code.
Using
-Oi, the code generator will inline some code where otherwise a runtime functions would have been called, even if the generated code is larger. This will not only remove the overhead for a function call, but will make the code visible for the optimizer.-Oiis an alias for-O --codesize 200.-Orwill make the compiler honor theregisterkeyword. Local variables may be placed in registers (which are actually zero page locations). See also the--register-varscommand line option, and the discussion of register variables below.Using
-Oswill allow the compiler to inline some standard functions from the C library like strlen. This will not only remove the overhead for a function call, but will make the code visible for the optimizer. See also the--inline-stdfuncscommand line option.It is possible to concatenate the modifiers for
-O. For example, to enable register variables and inlining of standard functions, you may use-Ors. -T, --add-source-
This include the source code as comments in the generated code. This is normally not needed.
-t sys, --target sys-
Accepted for backwards compatibility only. The only valid argument is
lynx; any other target system is an error. Because this build of cc65 always targets the Atari Lynx, the option has no effect on the generated output. See also--cpu. -V, --version-
Print the version number of the compiler. When submitting a bug report, please include the operating system you're using, and the compiler version.
-W name[,name,...]-
This option allows to control warnings generated by the compiler. It is followed by a comma-separated list of warnings that should be enabled or disabled. To disable a warning, its name is prefixed by a minus sign. If no such prefix exists, or the name is prefixed by a plus sign, the warning is enabled.
The following warning names currently are recognized:
const-comparison-
Warn if the result of a comparison is constant.
error-
Treat all warnings as errors.
no-effect-
Warn about statements that don't have an effect.
remap-zero-
Warn about a
#pragma charmap()that changes a character's code number from/to 0x00. struct-param-
Warn when passing structs by value.
unknown-pragma-
Warn about #pragmas that aren't recognized by cc65.
unused-label-
Warn about unused labels.
unused-param-
Warn about unused function parameters.
unused-var-
Warn about unused variables.
The full list of available warning names can be retrieved by using the option
--list-warnings.You may use also
#pragma warnto control this setting, for smaller pieces of code, from within your sources.
3. Input and output
The compiler will accept one C file per invocation and create a file with the same base name, but with the extension replaced by ".s". The output file contains assembler code suitable for use with the ca65 macro assembler.
Include files in quotes are searched in the following places:
-
The current file's directory.
-
Any directory added with the
-Ioption on the command line. -
The value of the environment variable
CC65_INCif it is defined.
Include files in angle brackets are searched in the following places:
-
Any directory added with the
-Ioption on the command line. -
The value of the environment variable
CC65_INCif it is defined. -
A subdirectory named
includeof the directory defined in the environment variableCC65_HOME, if it is defined. -
An optionally compiled-in directory.
4. Differences to the ISO standard
Apart from the things listed below, the compiler does support additional keywords, has several functions in the standard headers with names outside the reserved namespace and a few syntax extensions. As this is a Lynx-only fork, these cc65 extensions are always enabled and cannot be turned off.
Here is a list of differences between the language, the compiler accepts, and the one defined by the ISO standard:
-
The datatypes "float" and "double" are not available.
-
C Functions may not return structs (or unions), and structs may not be passed as parameters by value. However, struct assignment *is* possible.
-
Most of the C library is available with only the fastcall calling convention (see below). It means that you must not mix pointers to those functions with pointers to user-written, cdecl functions (the calling conventions are incompatible).
-
The
volatilekeyword has almost no effect. That is not as bad as it sounds, since the 6502 has so few registers that it isn't possible to keep values in registers anyway. -
Using an undeclared type name in a declaration (for example
time_t x;when notypedeffortime_tis in scope, typically a missing#include) is reported asUnknown type name 'time_t'. This compiler still accepts a genuine implicitint(with a warning), but an unknown identifier sitting in type position followed by another identifier, or by*, is diagnosed as a bad type name instead of being silently treated asint.
There may be some more minor differences I'm currently not aware of. The biggest problem is the missing float data type. With this limitation in mind, you should be able to write fairly portable code.
5. Extensions
This cc65 version has some extensions to the ISO C standard.
-
The compiler allows to insert assembler statements into the output file. The syntax is
asm [optional volatile] (<string literal>[, optional parameters]) ;or
__asm__ [optional volatile] (<string literal>[, optional parameters]) ;The first form is in the user namespace; and, is disabled if the
-Aswitch is given.There is a whole section covering inline assembler statements, see there.
-
The normal calling convention -- for non-variadic functions -- is named "fastcall". The syntax for a function declaration that explicitly uses fastcall is
<return type> fastcall <function name> (<parameter list>)or
<return type> __fastcall__ <function name> (<parameter list>)An example is
void __fastcall__ f (unsigned char c)The first form of the fastcall keyword is in the user namespace.
For functions that are
fastcall, the rightmost parameter is not pushed on the stack but left in the primary register when the function is called. That significantly reduces the cost of calling those functions. -
There is another calling convention named "cdecl". Variadic functions (their prototypes have an ellipsis [
...]) always use that convention. The syntax for a function declaration using cdecl is<return type> cdecl <function name> (<parameter list>)or
<return type> __cdecl__ <function name> (<parameter list>)An example is
int* __cdecl__ f (unsigned char c)The first form of the cdecl keyword is in the user namespace.
For functions that are
cdecl, the rightmost parameter is pushed onto the stack before the function is called. That increases the cost of calling those functions, especially when they are called from many places. -
There are two pseudo variables named
__AX__and__EAX__. Both refer to the primary register that is used by the compiler to evaluate expressions or return function results.__AX__is of typeunsigned intand__EAX__of typelong unsigned intrespectively. The pseudo variables may be used as lvalue and rvalue as every other variable. They are most useful together with short sequences of assembler code. For example, the macro#define hi(x) \ (__AX__ = (x), \ asm ("txa"), \ asm ("ldx #$00"), \ __AX__)will give the high byte of any unsigned value.
-
Inside a function, the identifier
__func__gives the name of the current function as a string. Outside of functions,__func__is undefined. Example:#define PRINT_DEBUG(s) printf ("%s: %s\n", __func__, s);The macro will print the name of the current function plus a given string.
-
cc65 allows the initialization of
voidvariables. This may be used to create arbitrary structures that are more compatible with interfaces written for assembler languages. Here is an example:void GCmd = { (char)3, (unsigned)0x2000, (unsigned)0x3000 };That will be translated as follows:
_GCmd: .byte 3 .word $2000 .word $3000Since the variable is of type
void, you may not use it as-is. However, taking the address of the variable results in avoid*which may be passed to any function expecting a pointer. Also, thesizeofoperator will give the length of the initializer:GLen = sizeof GCmd;will assign the value 5 to
GLen. -
cc65 implements flexible array struct members as defined in the C99 ISO standard. As an extension, these fields may be initialized. There are several exceptions, however (which is probably the reason why the standard does not define this feature, because it is highly unorthogonal). Flexible array members cannot be initialized ...
-
... when defining an array of structs with flexible members.
-
... if such a struct is a member field of another struct which is not the last field.
-
... if the struct which contains a flexible array member is declared as
register, and the size and compiler settings do allow the compiler actually to place the struct into the register bank in the zero page.
Please note that -- as defined in the ISO C standard -- the
sizeofoperator returns the struct size with the flexible array member having size zero, even if it is initialized. -
-
Computed gotos, a GCC extension, has limited support. With it you can use fast jump tables from C. You can take the address of a label with a double ampersand, putting them in a static const array of type void *. Then you can jump to one of these labels as follows:
static const void * const jumptable[] = { &&add, &&sub }; goto *jumptable[somevar]; add: ...code...In the jump table, no expressions are supported. The array index used in the goto must be a simple variable or a constant.
-
Binary literals, a C++14 feature and a GCC C extension, are accepted.
unsigned char foo = 0b101; // sets it to 5
6. Predefined macros
The compiler defines several macros at startup:
__CC65__-
This macro is always defined. Its value is the version number of the compiler in hex. For example, version 2.14 of the compiler has this macro defined as
0x02E0. __DATE__-
This macro expands to the date of translation of the preprocessing translation unit in the form "Mmm dd yyyy".
__EAGERLY_INLINE_FUNCS__-
Is defined if the compiler was called with the
--eagerly-inline-funcscommand line option. __FILE__-
This macro expands to a string containing the name of the C source file.
__LINE__-
This macro expands to the current line number.
__LYNX__-
This macro is always defined: the Atari Lynx is the only target supported by this tree, and the compiler always generates 65SC02 code for it.
__OPT__-
Is defined if the compiler was called with the
-Ocommand line option. __OPT_i__-
Is defined if the compiler was called with the
-Oicommand line option. __OPT_r__-
Is defined if the compiler was called with the
-Orcommand line option. __OPT_s__-
Is defined if the compiler was called with the
-Oscommand line option. __STDC_HOSTED__-
This macro is expands to the integer constant 1.
__TIME__-
This macro expands to the time of translation of the preprocessing translation unit in the form "hh:mm:ss".
Macros for upstream cc65 targets (such as __C64__ or __ATARI__) are
still emitted by the compiler when the corresponding -t option is given,
but those targets are unusable in this tree because their libraries have been
removed.
7. #pragmas
The compiler understands some pragmas that may be used to change code
generation and other stuff. Some of these pragmas understand a special form:
If the first parameter is push, the old value is saved onto a stack
before changing it. The value may later be restored by using the pop
parameter with the #pragma.
7.1. #pragma allow-eager-inline ([push,] on|off)
Allow eager inlining of known functions. If the argument is "off", eager
inlining is disabled, otherwise it is enabled. Please note that (in contrast
to the --eagerly-inline-funcs
command line option) this pragma does not imply the --inline-stdfuncs command line option. Rather it marks code to be safe for
eager inlining of known functions if inlining of standard functions is enabled.
The #pragma understands the push and pop parameters as explained above.
7.2. #pragma bss-name ([push,] <name>)
This pragma changes the name used for the BSS segment (the BSS segment is used to store uninitialized data). The argument is a string enclosed in double quotes.
Note: The default linker configuration file does only map the standard segments. If you use other segments, you have to create a new linker configuration file.
Beware: The startup code will zero only the default BSS segment. If you use another BSS segment, you have to do that yourself, otherwise uninitialized variables do not have the value zero.
The #pragma understands the push and pop parameters as explained above.
Example:
#pragma bss-name ("MyBSS")
7.3. #pragma charmap (<index>, <code>)
Each literal string and each literal character in the source is translated by use of a translation table. That translation table is preset when the compiler is started, depending on the target system. For the Lynx target, the mapping is plain ASCII.
This pragma allows to change entries in the translation table, so the translation for individual characters, or even the complete table may be adjusted. Both arguments are assumed to be unsigned characters with a valid range of 0-255.
Beware of some pitfalls:
-
The character index is actually the code of the character in the C source; so, character mappings do always depend on the source character set. That means that
#pragma charmap()is not portable -- it depends on the build environment. -
While it is possible to use character literals as indices, the result may be somewhat unexpected, since character literals are themselves translated. For that reason, I would suggest to avoid character literals, and use numeric character codes instead.
-
It is risky to change index
0x00, because string functions depend on it. If it is changed, then the'\0'at the end of string literals will become non-zero. Functions that are used on those literals won't stop at the end of them. cc65 will warn you if you do change that code number. You can turn off thatremap-zerowarning if you are certain that you know what you are doing (see#pragma warn()).
Example:
/* Use a space wherever an 'a' occurs in ISO-8859-1 source */ #pragma charmap (0x61, 0x20);
7.4. #pragma check-stack ([push,] on|off)
Tells the compiler to insert calls to a stack checking subroutine to detect stack overflows. The stack checking code will lead to somewhat larger and slower programs, so you may want to use this pragma when debugging your program and switch it off for the release version. If a stack overflow is detected, the program is aborted.
If the argument is "off", stack checks are disabled (the default), otherwise they're enabled.
The #pragma understands the push and pop parameters as explained above.
7.5. #pragma code-name ([push,] <name>)
This pragma changes the name used for the CODE segment (the CODE segment is used to store executable code). The argument is a string enclosed in double quotes.
Note: The default linker configuration file does only map the standard segments. If you use other segments, you have to create a new linker configuration file.
The #pragma understands the push and pop parameters as explained above.
Example:
#pragma code-name ("MyCODE")
7.6. #pragma codesize ([push,] <int>)
This pragma allows finer control about speed vs. size decisions in the code
generation and optimization phase. It gives the allowed size increase factor
(in percent). The default is can be changed by use of the --codesize compiler option.
The #pragma understands the push and pop parameters as explained above.
7.7. #pragma data-name ([push,] <name>)
This pragma changes the name used for the DATA segment (the DATA segment is used to store initialized data). The argument is a string enclosed in double quotes.
Note: The default linker configuration file does only map the standard segments. If you use other segments, you have to create a new linker configuration file.
The #pragma understands the push and pop parameters as explained above.
Example:
#pragma data-name ("MyDATA")
7.8. #pragma inline-stdfuncs ([push,] on|off)
Allow the compiler to inline some standard functions from the C library like strlen. If the argument is "off", inlining is disabled, otherwise it is enabled.
See also the --inline-stdfuncs
command line option.
The #pragma understands the push and pop parameters as explained above.
7.9. #pragma local-strings ([push,] on|off)
When "on", emit string literals to the data segment when they're encountered in the source. The default ("off") is to keep string literals until end of assembly, merge read only literals if possible, and then output the literals into the data or rodata segment that is active at that point.
Using this #pragma it is possible to control the behaviour from within
the source. When #pragma local-strings is active, string literals are
output immediately, which means that they go into the currently active data
or rodata segment, but cannot be merged. When inactive, string literals are
remembered and output as a whole when translation is finished.
7.10. #pragma message (<message>)
This pragma is used to display informational messages at compile-time.
The message intented to be displayed must be a string literal.
Example:
#pragma message ("in a bottle")
Results in the compiler outputting the following to stderr:
example.c(42): Note: in a bottle
7.11. #pragma optimize ([push,] on|off)
Switch optimization on or off. If the argument is "off", optimization is disabled, otherwise it is enabled. Please note that this pragma only effects whole functions. The setting in effect when the function is encountered will determine if the generated code is optimized or not.
Optimization and code generation is also controlled by the codesize pragma.
The default is "off", but may be changed with the -O compiler option.
The #pragma understands the push and pop parameters as explained above.
7.12. #pragma rodata-name ([push,] <name>)
This pragma changes the name used for the RODATA segment (the RODATA segment is used to store readonly data). The argument is a string enclosed in double quotes.
Note: The default linker configuration file does only map the standard segments. If you use other segments, you have to create a new linker configuration file.
The #pragma understands the push and pop parameters as explained above.
Example:
#pragma rodata-name ("MyRODATA")
7.13. #pragma regvaraddr ([push,] on|off)
The compiler does not allow to take the address of register variables. The regvaraddr pragma changes this. Taking the address of a register variable is allowed after using this pragma with "on" as argument. Using "off" as an argument switches back to the default behaviour.
Beware: The C standard does not allow taking the address of a variable declared as register. So your programs become non-portable if you use this pragma. In addition, your program may not work. This is usually the case if a subroutine is called with the address of a register variable, and this subroutine (or a subroutine called from there) uses register variables. So be careful with this #pragma.
The #pragma understands the push and pop parameters as explained above.
Example:
#pragma regvaraddr(on) /* Allow taking the address
* of register variables
*/
7.14. #pragma register-vars ([push,] on|off)
Enables or disables use of register variables. If register variables are
disabled (the default), the register keyword is ignored. Register
variables are explained in more detail in a separate
chapter.
The #pragma understands the push and pop parameters as explained above.
7.15. #pragma signed-chars ([push,] on|off)
Changes the signedness of the default character type. If the argument is
"on", default characters are signed, otherwise characters are unsigned. The
compiler default is to make characters unsigned since this creates a lot
better code. This default may be overridden by the --signed-chars command line option.
The #pragma understands the push and pop parameters as explained above.
7.16. #pragma static-locals ([push,] on|off)
Use variables in the bss segment instead of variables on the stack. This
pragma changes the default set by the compiler option --static-locals. If the argument is "on",
local variables are allocated in the BSS segment, leading to shorter and in
most cases faster, but non-reentrant code.
The #pragma understands the push and pop parameters as explained above.
7.17. #pragma warn (name, [push,] on|off)
Switch compiler warnings on or off. "name" is the name of a warning (see the
-W compiler option for a list). The name is
followed either by "pop", which restores the last pushed state, or by "on" or
"off", optionally preceeded by "push" to push the current state before
changing it.
Example:
/* Don't warn about the unused parameter in function func */
#pragma warn (unused-param, push, off)
static int func (int unused)
{
return 0;
}
#pragma warn (unused-param, pop)
7.18. #pragma wrapped-call (push, <name>, <identifier>)
This pragma sets a wrapper for functions, often used for trampolines.
The name is a function returning void, and taking no parameters.
It must preserve the CPU's A and X registers if it wraps any
__fastcall__ functions that have parameters. It must preserve
the Y register if it wraps any variadic functions (they have "..."
in their prototypes).
The identifier is an 8-bit number that's set into tmp4.
The address of a wrapped function is passed in ptr4. The wrapper can
call that function by using "jsr callptr4".
This feature is useful, for example, with banked memory, to switch banks automatically to where a wrapped function resides, and then to restore the previous bank when it returns.
The #pragma requires the push or pop argument as explained above.
Example:
/* Note that this code can be in a header. */ void mytrampoline(void); /* Doesn't corrupt __AX__ */ #pragma wrapped-call (push, mytrampoline, 5) void somefunc1(void); void somefunc2(int, char *); #pragma wrapped-call (pop)
7.19. #pragma writable-strings ([push,] on|off)
Changes the storage location of string literals. For historical reasons, the C standard defines that string literals are of type "char[]", but writing to such a literal causes undefined behaviour. Most compilers (including cc65) place string literals in the read-only data segment, which may cause problems with old C code that writes to string literals.
Using this pragma (or the corresponding command line option --writable-strings) causes the
literals to be placed in the data segment so they can be written to without
worry.
The #pragma understands the push and pop parameters as explained above.
7.20. #pragma zpsym (<name>)
Tell the compiler that the -- previously as external declared -- symbol with the given name is a zero page symbol (usually from an assembler file). The compiler will create a matching import declaration for the assembler.
Example:
extern int foo;
#pragma zpsym ("foo"); /* foo is in the zeropage */
For the common case of a variable that is both defined and
used from C, the __zeropage
attribute (see below) is simpler: it places the storage in the zero page and
marks the symbol in a single declaration, with no companion assembler file and
no separate #pragma.
8. Variable storage and lifetime
Where the compiler places a variable depends on its storage class and scope, not on its type. There are three kinds of storage: the software C stack, the static segments (BSS, DATA and RODATA), and zero page register space. The heap used by malloc and friends is never used for variables the compiler allocates itself.
Variables declared auto — the default for any local declared inside a function — live on the cc65 software stack. This is a separate, downward-growing stack addressed through a zero page pointer; it is not the 6502 hardware stack, which the runtime uses only for return addresses and scratch. Each call allocates the locals on entry and releases them on exit, so their lifetime is exactly one invocation and their address is relative to the current stack pointer rather than fixed. Because this allocate-and-release happens every time a block is entered, declaring locals in nested blocks rather than at the top of the function costs extra code and time.
Variables with static storage duration — everything declared at file scope, plus any local declared static — are given a fixed address by the linker and exist for the whole run of the program. The segment is chosen by the initialization, not by the type: an uninitialized variable goes into BSS, which is reserved as a block and cleared to zero at startup; a variable with a non-const initializer goes into DATA, which holds its initial-value image; and a variable whose elements are const goes into RODATA. An uninitialized global is treated as a tentative definition, so repeating a declaration such as int i; in one module reserves space only once.
The only thing that distinguishes a plain global from a static one is linkage, not storage. A plain global has external linkage: its label is exported, so the linker and other modules can see it. A static global, and likewise a static local, has internal linkage: nothing is exported and the label is private to the module. Both are stored identically in BSS, DATA or RODATA. A static local and a static global are therefore stored the same way; scope only changes where the name is visible in the C source.
Variables declared register are a special case covered in the next section: they occupy a small amount of zero page space rather than any of the above. The table below summarises the common cases.
| Declaration | Stored in | Addressing | Linkage | Lifetime |
|---|---|---|---|---|
| auto local | software C stack | stack-pointer relative | none | one function call |
static local | BSS / DATA / RODATA | fixed address | internal (module-local) | whole program |
static global | BSS / DATA / RODATA | fixed address | internal (module-local) | whole program |
| plain global | BSS / DATA / RODATA | fixed address | external (exported) | whole program |
__zeropage global | ZEROPAGE | zero page (fast, 2-byte) | internal or external | whole program |
Within the static cases the segment follows the initializer: uninitialized goes to BSS (zeroed at startup), a non-const initializer goes to DATA, and const data goes to RODATA.
8.1. The __zeropage specifier
A file-scope variable can be placed in the 6502 zero page in one of two equivalent ways. The first is the __zeropage attribute, declared in <zeropage.h> (it expands to __attribute__((zeropage))), written as a suffix on the declaration — the same position cc65 accepts every other attribute. The second is the __zeropage__ keyword, a prefix specifier that sits alongside the storage class. This replaces the older idiom of defining the variable in an assembler .zeropage segment and importing it with #pragma zpsym.
#include <zeropage.h>
/* Attribute (suffix) form: */
unsigned char fastFlag __zeropage; /* definition: lives in ZEROPAGE */
int scanPos __zeropage;
/* Keyword (prefix) form - equivalent, and combines with a storage class: */
__zeropage__ unsigned char fastFlag;
static __zeropage__ unsigned char privCounter; /* either order is accepted */
/* In a shared header, so every module agrees on the address size: */
extern unsigned char fastFlag __zeropage; /* reference: imported as zeropage */
The two forms are interchangeable and may even be combined on one declaration. The keyword is the double-underscore spelling only, so it never collides with an identifier named zeropage; as a prefix it reads with the placement up front (__zeropage__ int scanPos;). Like a storage class it must precede the type.
The defining translation unit emits the object into the built-in ZEROPAGE segment, whose zero-page address size makes the label a true zero-page symbol; it is exported with .exportzp. Any translation unit that marks the matching extern as __zeropage imports it with .importzp and addresses it through the fast 2-byte zero-page addressing modes. A static __zeropage object is private to its module but still zero-page addressed. To keep the address size consistent across modules, put the tagged extern in a header that every user includes; a module that omits it on one side produces an address-size mismatch at link time.
Either form is rejected where it cannot apply: on functions or typedefs, on local (automatic) objects — it is valid only at file scope — and on a definition that carries an initializer (the ZEROPAGE segment, like an assembler .res cell, holds no initialization image). Zero page is a scarce, 256-byte resource shared with the cc65 runtime (the C-stack pointer, sreg, the ptr/tmp scratch cells, register variables, and so on), so reserve it for a few hot scalars and pointers rather than arrays or large structs. Over-allocating the zero page is reported by ld65 as a ZEROPAGE segment overflow.
9. Register variables
The runtime for all supported platforms has 6 bytes of zero page space
available for register variables (this could be increased, but I think it's a
good value). So you can declare register variables up to a total size of 6 per
function. The compiler will allocate register space on a "first come, first
served" base and convert any register declarations that exceed the
available register space silently to auto. Parameters can also be
declared as register, this will in fact give slightly shorter code than
using a register variable.
Since a function must save the current values of the registers on entry and
restore them on exit, there is an overhead associated with register variables,
and this overhead is quite high (about 20 bytes per variable). This means that
just declaring anything as register is not a good idea.
The best use for register variables are pointers, especially those that point to structures. The magic number here is about 3 uses of a struct field: If the function contains this number or even more, the generated code will be usually shorter and faster when using a register variable for the struct pointer. The reason for this is that the register variable can in many cases be used as a pointer directly. Having a pointer in an auto variable means that this pointer must first be copied into a zero page location, before it can be dereferenced.
Second best use for register variables are counters. However, there is not much difference in the code generated for counters, so you will need at least 100 operations on this variable (for example in a loop) to make it worth the trouble. The only savings you get here are by the use of a zero page variable instead of one on the stack or in the data segment.
Register variables must be explicitly enabled, either by using -Or or --register-vars on the command line or by use of #pragma register-vars. Register variables
are only accepted on function top level, register variables declared in
interior blocks are silently converted to auto. With register variables
disabled, all variables declared as register are actually auto variables.
Please take care when using register variables: While they are helpful and can lead to a tremendous speedup when used correctly, improper usage will cause bloated code and a slowdown.
10. Inline assembler
The compiler allows to insert assembler statements into the output file. The syntax is
asm [optional volatile] (<string literal>[, optional parameters]) ;
or
__asm__ [optional volatile] (<string literal>[, optional parameters]) ;
The first form is in the user namespace.
The asm statement can be used only inside a function. Please note that
the result of an inline assembler expression is always of type void.
The contents of the string literal are preparsed by the compiler; and, inserted
into the generated assembly output, so that it can be processed further by
the backend -- and, especially the optimizer. For that reason, the compiler does
allow only regular 6502 opcodes to be used with the inline assembler. Pseudo
instructions (like .import, .byte, and so on) are not allowed,
even if the ca65 assembler (which is used to translate the generated assembler
code) would accept them. The built-in inline assembler is not a replacement for
the full-blown macro assembler which comes with the compiler.
Note: Inline assembler statements are subject to all optimizations done by the compiler. There currently is no way to protect an inline assembler statement -- alone -- from being moved or removed completely by the optimizer. If in doubt, check the generated assembler output; or, disable optimizations (for that function).
As a shortcut, you can put the volatile qualifier in your asm
statements. It will disable optimization for the functions in which those
asm volatile statements sit. The effect is the same as though you put
#pragma optimize(push, off) above those functions, and #pragma
optimize(pop) below those functions.
The string literal may contain format specifiers from the following list. For each format specifier, an argument is expected which is inserted instead of the format specifier, before passing the assembly code line to the backend.
-
%b- Numerical 8-bit value -
%w- Numerical 16-bit value -
%l- Numerical 32-bit value -
%v- Assembler name of a global variable or function -
%o- Stack offset of a local variable -
%g- Assembler name of a C label -
%s- The argument is converted to a string -
%%- The % sign itself
Using those format specifiers, you can access C #defines, variables, or
similar stuff from the inline assembler. For example, to load the value of
a C #define into the Y index register, one would use
#define OFFS 23
__asm__ ("ldy #%b", OFFS);
Or, to access a struct member of a static variable:
typedef struct {
unsigned char x;
unsigned char y;
unsigned char color;
unsigned char data[32];
} pixel_t;
static pixel_t pixel;
__asm__ ("ldy #%b", offsetof(pixel_t, color));
__asm__ ("lda %v,y", pixel);
/* or to access an array member */
static unsigned char i;
__asm__ ("ldy %v", i);
__asm__ ("lda %v+%b,y", pixel, offsetof(pixel_t, data));
The next example shows how to use global variables to exchange data between C and assembler; and, how to handle assembler jumps:
static unsigned char globalSubA, globalSubB, globalSubResult;
/* return a-b, return 255 if b>a */
unsigned char sub (unsigned char a, unsigned char b)
{
globalSubA = a;
globalSubB = b;
__asm__ ("sec");
__asm__ ("lda %v", globalSubA);
__asm__ ("sbc %v", globalSubB);
__asm__ ("bcs %g", jumpSubNoError);
__asm__ ("lda #$FF");
jumpSubNoError:
__asm__ ("sta %v", globalSubResult);
return globalSubResult;
}
Arrays also can be accessed:
static const unsigned char globalSquareTable[] = {
0, 1, 4, 9, 16, 25, 36, 49, 64, 81,
100, 121, 144, 169, 196, 225
};
static unsigned char globalSquareA, globalSquareResult;
/* return a*a for a<16, else 255 */
unsigned char square (unsigned char a)
{
if (a > 15) {
return 255;
}
globalSquareA = a;
__asm__ ("ldx %v", globalSquareA);
__asm__ ("lda %v,x", globalSquareTable);
__asm__ ("sta %v", globalSquareResult);
return globalSquareResult;
}
Note: Do not embed the assembler labels that are used as names of global
variables or functions into your asm statements. Code such as this:
int foo;
int bar (void) { return 1; }
...
__asm__ ("lda _foo"); /* DON'T DO THAT! */
...
__asm__ ("jsr _bar"); /* DON'T DO THAT EITHER! */
might stop working if the way that the compiler generates those names is changed in a future version. Instead, use the format specifiers from the table above:
__asm__ ("lda %v", foo); /* OK */
...
__asm__ ("jsr %v", bar); /* OK */
11. The C language: operators
cc65 accepts the full set of C operators. This section summarises how they
behave on the Lynx target, where the native integer types are 8, 16 and 32 bits
wide (char is 8 bits, int is 16 bits and long
is 32 bits) and there is no floating-point type — the float and
double operators do not exist (see section 4). On
top of the standard operators this fork adds three hardware operators
(!*, !/, !%) that route multiplication and
division through the Suzy math unit.
11.1. Standard operators
All of the usual C operators are available and follow the standard precedence, associativity and promotion rules:
-
Arithmetic:
+,-,*,/,%, and unary+/-. Multiplication and division of runtime values are emitted as calls to the software runtime routines; multiplication or division by a constant power of two is strength-reduced to a shift. There is no floating-point arithmetic. -
Increment / decrement: prefix and postfix
++and--. -
Relational and equality:
<,<=,>,>=,==,!=. -
Logical:
&&,||, and unary!, with the usual short-circuit evaluation. -
Assignment: plain
=and the compound forms+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=. Struct assignment is supported even though structs may not be returned from, or passed by value to, functions (see section 4). -
Conditional, comma, cast and
sizeof: the ternary?:, the comma operator,, cast expressions(type)x, andsizeofall behave as in standard C. -
Member, pointer and subscript:
.,->, unary*(indirection), unary&(address-of) and[]. Pointer arithmetic scales by the pointed-to type using the software multiply.
11.2. Bitwise operators
The bitwise operators work on the integer types in their natural width —
8 bits for char, 16 for int, 32 for long
— after the usual integer promotions:
&— bitwise AND|— bitwise OR^— bitwise XOR~— one's-complement (unary)<<— left shift>>— right shift (arithmetic for signed operands, logical for unsigned)
Because the 6502 shifts one bit at a time, shifting by a small constant is
cheap while shifting by a large or runtime count is correspondingly more
expensive. Each operator has a matching compound-assignment form
(&=, |=, ^=, <<=,
>>=).
11.3. Suzy hardware operators
This fork adds three multiplicative operators that are specific to the Lynx and
are rejected by any other compiler: !*, !/ and
!%. They are written exactly like their standard counterparts
*, / and % and share the same precedence,
associativity and type/promotion rules, but instead of the software runtime loops
they route the operation through Suzy's hardware math unit (a 16×16→32
multiply and a 32÷16 divide):
unsigned a, b, c, q, r;
...
q = a !* b; // hardware multiply (low 16 bits of the product)
q = a !/ b; // hardware divide
r = a !% b; // hardware remainder, computed as a - (a/b)*b
The standard *, / and % operators are
unchanged and keep using the software routines, so Suzy math is strictly opt-in:
only the call sites you mark with ! use the hardware. Compiler-generated
multiplies (array indexing, pointer scaling) always use software. A hardware
multiply completes in roughly 11–14 CPU cycles and a divide in at most ~100,
several times faster than the software loops.
Notes and limitations:
-
The operators are fork-specific. Code that uses them will not compile with other cc65 builds or other C compilers.
-
Because the standalone
!*yields only the low 16 bits of the product,(a !* b) !/ cwould overflow whenevera*b > 65535. The compiler therefore recognises the fused forma !* b !/ c— when both factors are runtime 16-bit ints — as a single operation that keeps the full 32-bit product as the dividend, avoiding the overflow. A constant orlongfactor, or a trailing!%, falls back to the per-operator path. The divisor of the fused form must be a 16-bit integer — the Suzy divider takes 16 bits, and by the time the divisor’s type is known the fusion is already committed, so alongdivisor is a compile error rather than a silent truncation. Write(a !* b) !/ cto divide by along: the parenthesized form takes the standalone path (16-bit product, software long division). -
The hardware remainder register is unusable (a documented Lynx bug), so
!%is computed asa - (a/b)*b: one hardware divide plus one hardware multiply. -
Division by zero yields
0xFFFF(the hardware returns all-ones); as in standard C the result is otherwise undefined. -
The math unit is shared, global hardware state. Do not use these operators inside interrupt handlers, and do not mix them with asynchronous (non-blocking) sprite rendering, which uses the same unit — either would corrupt results. The synchronous Lynx graphics library is safe by construction.
For the full hardware contract and the runtime entry points, see
design/LYNX_CODEGEN_DESIGN.md §2.6 in the source tree.
12. Calling assembly functions from C
This section covers the internal details of cc65 code generation needed to call assembly functions from C. It was originally written by Brad Smith.
12.1. Calling conventions
There are two calling conventions used in cc65:
-
cdecl- passes all parameters on the C-stack. -
fastcall- passes the rightmost parameter in registersA/X/sregand all others on the C-stack.
The default convention is fastcall, but this can be changed with
the --all-cdecl command line option. If a convention is specified in
the function's declaration, that convention will be used instead.
Variadic functions will always use cdecl convention.
The cdecl and fastcall keywords (and their standard
compliant variations __cdecl__ and __fastcall__) are
always available.
If a function has a prototype, parameters are pushed to the C-stack as their respective types
(i.e. a char parameter will push 1 byte), but if a function has no prototype, default
promotions will apply. This means that with no prototype, char will be promoted
to int and be pushed as 2 bytes. "K & R"-style forward declarations may be used,
but they will function the same as if no prototype was used.
12.2. Prologue, before the function call
If the function is declared as fastcall, the rightmost argument will be loaded into
the A/X/sreg registers:
-
A- 8-bit parameter, or low byte of larger types -
X- 16-bit high byte, or second byte of 32-bits -
sreg- Zeropage pseudo-register including high 2 bytes of 32-bit parameter
All other parameters will be pushed to the C-stack from left to right. The rightmost parameter will have the lowest address on the stack, and multi-byte parameters will have their least significant byte at the lower address.
The sp pseudo-register is a zeropage pointer to the base of the C-stack.
If the function is variadic, the Y register will contain the number of
bytes pushed to the stack for this function.
Example:
// C prototype
void cdecl foo(unsigned bar, unsigned char baz);
; C-stack layout within the function:
;
; +------------------+
; | High byte of bar |
; Offset 2 ->+------------------+
; | Low byte of bar |
; Offset 1 ->+------------------+
; | baz |
; Offset 0 ->+------------------+
; Example code for accessing bar. The variable is in A/X after this code snippet:
;
ldy #2 ; Offset of high byte of bar
lda (sp),y ; High byte now in A
tax ; High byte now in X
dey ; Offset of low byte of bar
lda (sp),y ; Low byte now in A
12.3. Epilogue, after the function call
11.3.1. Return requirements
If the function has a return value, it will appear in the A/X/sreg registers.
Functions with an 8-bit return value (char or unsigned char) are expected
to promote this value to a 16-bit integer on return, and store the high byte in X.
The compiler will depend on the promoted value in some cases (e.g. implicit conversion to int),
and failure to return the high byte in X will cause unexpected errors.
This problem does not apply to the sreg pseudo-register, which is only
used if the return type is 32-bit.
If the function has a void return type, the compiler will not depend on the result
of A/X/sreg, so these may be clobbered by the function.
The C-stack pointer sp must be restored by the function to its value before the
function call prologue. It may pop all of its parameters from the C-stack
(e.g. using the runtime function popa),
or it could adjust sp directly.
If the function is variadic, the Y register contains the number of bytes
pushed to the stack on entry, which may be added to sp to restore its
original state.
The internal pseudo-register regbank must not be changed by the function.
11.3.2. Clobbered state
The Y register may be clobbered by the function.
The compiler will not depend on its state after a function call.
The A/X/sreg registers may be clobbered if any of them
are not used by the return value (see above).
Many of the internal pseudo-registers used by cc65 are available for free use by any function called by C, and do not need to be preserved. Note that if another C function is called from your assembly function, it may clobber any of these itself:
-
tmp1 .. tmp4 -
ptr1 .. ptr4 -
regsave -
sreg(if unused by return)
13. Compiler diagnostics
The compiler reports problems as messages of the form file(line): severity: message, where severity is Warning, Error or Fatal. Warnings do not stop translation and can be tuned individually (see -W and --list-warnings); errors let parsing continue so that several can be found in one run, but no output file is produced; a fatal error aborts the compiler at once. Compilation also stops with Too many errors once the error count gets too high.
The tables below list the error and fatal-error messages the compiler can produce, grouped by the stage that emits them. Text such as %s, %u or %02X is filled in with the offending name or value at runtime. (Warnings are not listed here; use --list-warnings for the current set.) Messages that begin with ASM code error or report an internal inconsistency usually indicate a compiler bug rather than a mistake in your program.
13.1. Reading a diagnostic
For example, a header that uses a type the compiler does not know about:
src/Avl.h(48): Error: Unknown type name 'time_t'
names the file and line, the severity, and the specific problem - here, a time_t with no typedef or #include in scope.
13.2. Lexical, character and string constants
Reported while reading source characters, numbers and constants.
| Message | Meaning |
|---|---|
Invalid input character with code %02X | A byte that is not legal C source was found in the input file. |
Unexpected newline | A line ended in the middle of a token, e.g. an unterminated character constant. |
Numeric constant contains digits beyond the radix | A digit is too large for the constant's base (e.g. an 8 or 9 in an octal number). |
Floating constant exponent has no digits | The exponent of a floating-point constant (after e/E) is missing its digits. |
Illegal escaped character: 0x%02X | An unknown backslash escape sequence was used in a string or character constant. |
\x used with no following hex digits | A \x escape was not followed by any hexadecimal digits. |
Hex character constant out of range | A \x escape evaluates to a value too large for the character type. |
Octal character constant out of range | A \nnn octal escape evaluates to a value too large for the character type. |
'\'' expected | A closing single quote was expected to terminate a character constant. |
Character constant out of range | A character constant does not fit the target character type. |
Illegal character constant 0x%02X | A character constant contains a value that cannot be represented. |
Invalid hexadecimal number | A malformed hexadecimal number was scanned. |
Invalid hexadecimal digit: '%c' | A character that is not a valid hexadecimal digit was used where one was required. |
Unexpected end of string | The end of a string was reached while more input was expected. |
13.3. Preprocessor directives
Reported by the preprocessor for #include, conditionals, macros and #error/#warning.
| Message | Meaning |
|---|---|
#error: %s | A user #error directive was reached; the text is taken from the directive. |
#include expects \"FILENAME\" or <FILENAME> | An #include directive was not followed by a quoted or angle-bracketed file name. |
'#' is not followed by a macro parameter | In a function-like macro, the # stringize operator must be followed by a parameter name. |
'#endif' expected | A conditional block (#if/#ifdef/...) was left open at end of file. |
')' expected | A closing parenthesis is missing (macro argument list or pragma/expression). |
'...' expected | A variadic macro parameter list is malformed; '...' was expected. |
'\"' or '<' expected | A computed #include did not expand to a valid "FILENAME" or <FILENAME> form. |
Duplicate #else | More than one #else was found in a single conditional block. |
Duplicate #else/#elif | An #else or #elif appeared after an #else in the same conditional block. |
End-of-file reached in comment starting at line %u | A /* comment was never closed before end of file. |
Identifier expected | An identifier was required here (declarator, macro name, label, etc.) but not found. |
Invalid #error directive | The #error directive is malformed. |
Invalid #warning directive | The #warning directive is malformed. |
Macro argument count mismatch | A function-like macro was invoked with the wrong number of arguments. |
Macro redefinition is not identical | A macro was redefined with a different body than its previous definition. |
Preprocessor directive expected | A '#' was not followed by a valid preprocessor directive. |
Too many nested #if clauses | The conditional-inclusion nesting limit was exceeded. |
Unexpected #elif | An #elif was found without a matching #if. |
Unexpected '#else' | An #else was found without a matching #if. |
Unexpected '#endif' | An #endif was found without a matching #if. |
Unterminated argument list invoking macro '%s' | End of file was reached inside a macro call's argument list. |
13.4. Declarations, types and initializers
Reported while parsing declarations, type specifiers, qualifiers, struct/union/enum and initializers.
| Message | Meaning |
|---|---|
Unknown type name '%s' | An undeclared identifier was used where a type name was expected (typically a missing typedef or #include). |
Type expected | A type specifier was required here but none was found. |
Identifier expected for argument %u | An __asm__ argument that must be an identifier was something else. |
Illegal type | The type produced by the declaration or expression is not valid here. |
Illegal type in initialization | The initializer's type is not compatible with the object being initialized. |
Illegal type %04lX | Internal type code that is not valid in this context. |
Illegal type for variable '%s' | The named variable was declared with a type it cannot have (e.g. a function type). |
Illegal storage class | The storage-class specifier (auto/register/static/extern/typedef) is not allowed here. |
Invalid address size | An address-size qualifier resolved to an invalid value. |
Size of data type is unknown | The size of a type is needed but the type is incomplete. |
Invalid size in declaration (0x%06X) | The declared object is larger than the target supports. |
Size of '%s' is invalid (0x%06X) | The named object is larger than the target supports. |
Size of array '%s' is invalid | The named array has a zero or otherwise invalid element count. |
Size of array is invalid | An array has a zero or otherwise invalid element count. |
Cannot initialize variables with incomplete type | An object of incomplete type (e.g. an array of unknown size) cannot be initialized. |
Constant initializer expected | A static/global initializer must be a constant expression. |
Non constant initializer | A static/global object was initialized with a non-constant value. |
Non constant initializers | One or more static/global initializers are not constant expressions. |
Too many initializers | More initializers were supplied than the aggregate has elements. |
'{' expected | An opening brace was expected (e.g. to begin an initializer or block). |
'}' expected | A closing brace was expected to end an initializer or aggregate. |
Bit-field has invalid type | A bit-field was declared with a type that may not be used for bit-fields. |
Negative width in bit-field | A bit-field was declared with a negative width. |
Zero width for named bit-field | A named bit-field was declared with width zero (only unnamed zero-width fields are allowed). |
Width of bit-field exceeds its type | The bit-field width is larger than the underlying type can hold. |
Flexible array member cannot be first struct field | A flexible array member must be preceded by at least one named member. |
Flexible array member must be last field | A flexible array member may only appear as the final struct member. |
Address size qualifier mismatch | Conflicting address-size qualifiers were applied. |
Cannot specify more than one address size qualifier | Only one of the address-size qualifiers may be given. |
Cannot specify more than one calling convention qualifier | Only one calling-convention qualifier may be given. |
Cannot take the address of a register variable | Objects with register storage class have no address. |
Functions are not allowed to return arrays | A function's return type may not be an array. |
Functions are not allowed to return functions | A function's return type may not be a function. |
function definition has qualified void return type | A function returning void may not have a qualified void return type. |
Function's and pointer's calling conventions are different | A function pointer was assigned a function with an incompatible calling convention. |
Not pointer to a function; can't use a calling convention | A calling-convention qualifier was applied to something that is not a function pointer. |
Invalid '__cdecl__' qualifier | The __cdecl__ qualifier was used in an invalid position. |
Invalid '__far__' qualifier | The __far__ qualifier was used in an invalid position. |
Invalid '__fastcall__' qualifier | The __fastcall__ qualifier was used in an invalid position. |
Invalid '__near__' qualifier | The __near__ qualifier was used in an invalid position. |
Invalid qualifiers for array | Type qualifiers were applied to an array in a way the standard does not allow. |
Variadic functions cannot be __fastcall__ | A function with a variable argument list cannot use the __fastcall__ convention. |
Variadic-function pointers cannot be __fastcall__ | A pointer to a variadic function cannot use the __fastcall__ convention. |
Redefinition for parameter '%s' | The same parameter name was declared twice in one function. |
Symbol '%s' is already different kind | The name is already declared as a different kind of entity (e.g. tag vs. variable). |
Unknown identifier: '%s' | An identifier was referenced that has not been declared. |
Cannot convert from 'void' to something else | A void value cannot be converted to another type. |
Incompatible pointer types at '%s' | Two pointer types in this expression are not compatible. |
Pointer types differ in type qualifiers | Two pointer types differ only in qualifiers but the conversion drops or adds them illegally. |
Cannot initialize externals | An object declared extern may not carry an initializer here. |
Cannot initialize flexible array members of storage class 'register' | A register object may not have an initialized flexible array member. |
Variable '%s' has unknown size | The named variable's type has no known size, so storage cannot be allocated. |
Body for function '%s' has already been defined | A function with a body was defined more than once. |
Global variable '%s' has already been defined | A global object was defined more than once. |
Global variable '%s' already was defined in the '%s' segment. | A global object was placed in conflicting segments by repeated definitions. |
__asm__ is not allowed here | An __asm__ statement appeared in a context where it is not permitted. |
Attribute name expected | A __attribute__ specifier was not followed by an attribute name. |
Illegal attribute: '%s' | An unrecognized attribute name was used. |
Attributes must be specified in the first declaration | Attributes have to appear on the first declaration of a symbol. |
Too many type specifiers | More type specifiers were combined than is legal (e.g. long long long). |
13.5. Expressions and operators
Reported while type-checking expressions, operators, calls and lvalues.
| Message | Meaning |
|---|---|
Expression expected | An expression was required here but none was found. |
Constant expression expected | A constant expression is required in this context. |
Constant integer expression expected | A constant integer expression is required in this context. |
Integer expression expected | An expression of integer type is required here. |
Constant integer expected | A constant integer value is required here. |
Boolean expression expected | A scalar/boolean expression is required (e.g. in a condition). |
Preprocessor expression expected | A constant expression was required in a preprocessor conditional. |
Argument must have integer type | A built-in or operator required an integer argument. |
Array subscript is not an integer | An array index expression is not of integer type. |
Subscripted value is neither array nor pointer | Subscripting was applied to something that is not an array or pointer. |
Cannot subscript | The operand cannot be subscripted with []. |
Struct expected | A struct or union value was required here. |
Struct pointer expected | A pointer to a struct or union was required (e.g. before ->). |
Struct/union has no field named '%s' | The named member does not exist in the struct or union. |
Cannot take address of bit-field | Bit-fields have no address, so & cannot be applied. |
Illegal indirection | The * operator was applied to a non-pointer value. |
Illegal address | The & operator was applied to something that has no address. |
Illegal function call | A call was attempted on something that is not callable. |
Call to undefined function '%s' | A function was called that has not been declared. |
Too few arguments in function call | Fewer arguments were passed than the function declares. |
Too many arguments in function call | More arguments were passed than the function declares. |
Argument expected after comma | A trailing comma in an argument list was not followed by an argument. |
Variable identifier expected | A modifiable variable was expected at this position. |
Invalid lvalue | The operand is not a modifiable lvalue. |
Invalid lvalue in assignment | The left side of an assignment is not a modifiable lvalue. |
Assignment to const | An object declared const cannot be assigned to. |
Increment of read-only variable | ++ cannot be applied to a const/read-only object. |
Decrement of read-only variable | -- cannot be applied to a const/read-only object. |
Incompatible types | The operand types are not compatible for this operation. |
Incompatible pointer types | Two pointer operands point to incompatible types. |
Invalid left operand type | The left operand has a type not allowed for this operator. |
Invalid left operand for binary operator '-' | The left operand of '-' has an invalid type. |
Invalid operands for binary operator '+' | The operand types are not valid for '+'. |
Invalid operands for binary operator '-' | The operand types are not valid for '-'. |
Invalid right operand for binary operator '-' | The right operand of '-' has an invalid type. |
Invalid right operand for binary operator '%s' | The right operand of the named binary operator has an invalid type. |
Invalid left operand for relational operator | The left operand of a relational operator has an invalid type. |
Invalid right operand for relational operator | The right operand of a relational operator has an invalid type. |
Division by zero | A constant division by zero was detected. |
Modulo operation with zero | A constant modulo by zero was detected. |
13.6. Statements and control flow
Reported while parsing statements, loops, switch and goto.
| Message | Meaning |
|---|---|
';' expected | A semicolon was expected to end a statement or declaration. |
',' expected | A comma was expected to separate items in a list. |
'break' statement not within loop or switch | A break appeared outside any loop or switch. |
'continue' statement not within a loop | A continue appeared outside any loop. |
Function '%s' must return a value | Control reached the end of a non-void function without returning a value. |
Returning a value in function with return type void | A value was returned from a function declared void. |
Label at end of compound statement | A label has no statement following it before the closing brace. |
'default' label not within a switch statement | A default label appeared outside any switch. |
Case label not within a switch statement | A case label appeared outside any switch. |
Multiple default labels in one switch | A switch statement has more than one default label. |
Duplicate case label | Two case labels in the same switch have the same value. |
Range error | A case label value is outside the range of the switch quantity's type. |
Switch quantity is not an integer | The controlling expression of a switch must have integer type. |
Array name expected | A computed-goto label table operand must be an array. |
Expected a static array | The computed-goto label table must be a static array. |
Label name expected | A label name was expected (goto or label table). |
Only arrays with <= 127 labels are supported, got %lu | A computed-goto label table exceeds the 127-entry limit. |
Only simple expressions are supported for computed goto | The computed-goto target expression is too complex. |
13.7. Symbols, functions and scope
Reported for undefined, conflicting or duplicated symbols, labels and function definitions.
| Message | Meaning |
|---|---|
Undefined symbol: '%s' | A symbol was used that is not defined in scope. |
Undefined symbol '%s' for argument %u | An __asm__ argument refers to an undefined symbol. |
Undefined label: '%s' | A goto refers to a label that is never defined in the function. |
Label '%s' is defined more than once | The same label name was defined twice in one function. |
Conflicting types for '%s' | A symbol was redeclared with a type incompatible with its previous declaration. |
Multiple definition for '%s' | A symbol was defined more than once. |
'main' must always return an int | The main function must be declared to return int. |
'main' cannot be declared as __fastcall__ | The main function may not use the __fastcall__ calling convention. |
Parameter name omitted | A function definition's parameter list is missing a name for a parameter. |
Duplicate macro parameter: '%s' | A function-like macro lists the same parameter name twice. |
Too many local variables | A function declares more local variables than the compiler can handle. |
13.8. #pragma, segments and wrapped-call
Reported for malformed #pragma directives and segment / wrapped-call name stacks.
| Message | Meaning |
|---|---|
'(' expected | A pragma argument list must begin with an opening parenthesis. |
Invalid pragma | An unknown #pragma name was used. |
Invalid pragma argument | A #pragma argument is of the wrong form. |
Comma expected | A comma was expected between #pragma arguments. |
Pragma argument must be one of 'on', 'off', 'true' or 'false' | A boolean #pragma needs one of these keywords. |
Pragma argument out of bounds (%ld-%ld) | A numeric #pragma argument is outside its allowed range. |
Pragma expects a warning name as first argument | #pragma warn must name a warning first. |
Push or pop required | A stacked #pragma needs a push or pop action. |
Cannot pop, stack is empty | A #pragma pop was issued with nothing on the stack. |
Cannot push: stack overflow | Too many nested #pragma push operations. |
Character code out of range | A #pragma charmap code is outside the valid range. |
Character index out of range | A #pragma charmap index is outside the valid range. |
Identifier must be between 0-255 | A #pragma charmap identifier must fit in a byte. |
Illegal segment name: '%s' | A segment-name #pragma was given an invalid name. |
String literal expected | A string literal was required (e.g. a #pragma segment name or __asm__ text). |
Unexpected input following pragma directive | Extra tokens followed a complete #pragma. |
Value required for wrapped-call identifier | #pragma wrapped-call needs a value for its identifier. |
Wrapped-call target does not exist or is not a function | The #pragma wrapped-call target must be an existing function. |
Segment name stack is empty | A segment-name pop was issued with nothing on the stack. |
Segment name stack overflow | Too many nested segment-name pushes. |
WrappedCall stack is empty | A wrapped-call pop was issued with nothing on the stack. |
WrappedCall stack overflow | Too many nested wrapped-call pushes. |
13.9. Inline assembler and code generation
Reported for __asm__ statements and the assembly the compiler emits.
| Message | Meaning |
|---|---|
Error in __asm__ format specifier %u | An __asm__ format string has a malformed % specifier. |
Range error in argument %u | An __asm__ argument value is outside the range the specifier allows. |
Type of argument %u differs from format specifier | An __asm__ argument's type does not match its format specifier. |
Argument %u has no fixed stack offset | An __asm__ argument does not have a stable stack address. |
Code generation messed up: StackPtr is %d, should be %d | Internal consistency check: the tracked stack pointer is wrong (compiler bug). |
ASM code error: %s is not a valid mnemonic | The inline/generated assembly uses an unknown mnemonic. |
ASM code error: syntax error | The inline/generated assembly could not be parsed. |
ASM code error: ')' expected | A closing parenthesis is missing in an assembly operand. |
ASM code error: 'X' expected | The assembly operand expected the X register. |
ASM code error: 'Y' expected | The assembly operand expected the Y register. |
ASM code error: Cannot use local label '%s' in subroutine call | A local label may not be the target of a JSR/JMP in this context. |
ASM code error: Pseudo instruction '%s' not supported | An unsupported assembler pseudo-instruction was used inline. |
ASM label '%s' is already defined | The same assembly label was defined twice. |
Structs of this size are not supported | Struct assignment for this size cannot be generated. |
13.10. Fatal errors
Fatal errors abort compilation immediately. The first group are I/O failures; the rest are unrecoverable limits or unsupported features.
| Message | Meaning |
|---|---|
Too many errors | Compilation was aborted after too many errors were reported. |
Cannot open input file '%s': %s | The compiler could not open the named source file. |
Cannot open dependency file '%s': %s | The compiler could not open the make-dependency output file. |
Cannot stat '%s': %s | The compiler could not stat the named file. |
Cannot write to dependeny file (disk full?) | Writing the dependency file failed, possibly out of disk space. |
Cannot open output file '%s': %s | The compiler could not create the assembly output file. |
Cannot open debug output file '%s': %s | The compiler could not create the optimizer-debug output file. |
Cannot write to output file (disk full?) | Writing the assembly output failed, possibly out of disk space. |
Floating point type is currently unsupported | The float/double types are not implemented for this target. |
Can't redeclare enum constant '%s' as global variable | An enum constant name was reused as a global variable. |
14. Copyright
The original Atari 8-bit compiler copyright by John R. Dunning (covering small parts of the preprocessor and main parser) and the package-wide cc65 license that covers the rest are reproduced verbatim, alongside every other notice in the distribution, in the consolidated Licenses and copyright notices page.