CXSTM8 UsersGuide
CXSTM8 UsersGuide
Soft ware
Version 4.4
Chapter 1
Introduction
Introduction................................................................................. 4
Document Conventions............................................................... 4
Typewriter font..................................................................... 4
Italics .................................................................................... 5
[ Brackets ] ........................................................................... 5
Conventions.......................................................................... 6
Command Line ..................................................................... 6
Flags ..................................................................................... 6
Compiler Architecture ................................................................ 8
Predefined Symbol...................................................................... 9
Linking........................................................................................ 9
Programming Support Utilities................................................. 10
Listings...................................................................................... 10
Optimizations............................................................................ 11
Support for ROMable Code...................................................... 12
Support for eeprom ................................................................... 12
Memory Models........................................................................ 13
Chapter 2
Tutorial Introduction
Acia.c, Example file.................................................................. 16
Default Compiler Operation ............................................... 17
Compiling and Linking............................................................. 19
Step 1: Compiling............................................................... 19
Step 2: Assembler............................................................... 20
Step 3: Linking ................................................................... 21
Step 4: Generating S-Records file ...................................... 23
Linking Your Application......................................................... 24
Generating Automatic Data Initialization................................. 25
Specifying Command Line Options ......................................... 28
Chapter 3
Programming Environments
Introduction............................................................................... 32
Modifying the Runtime Startup ................................................ 34
Description of Runtime Startup Code ................................ 35
i
Initializing data in RAM........................................................... 36
Memory Models for code smaller than 64K............................. 39
Memory Models for code larger than 64K ............................... 39
Handling Large Code and Constants ........................................ 41
Bit Variables ............................................................................. 42
The const and volatile Type Qualifiers..................................... 43
Performing Input/Output in C................................................... 45
Referencing Absolute Addresses.............................................. 46
Accessing Internal Registers .................................................... 48
Placing Data Objects in The Bss Section ................................. 48
Placing Data Objects in Short Range Memory......................... 49
Setting Short Range Size.................................................... 49
Placing Data Objects in Long Range Memory ......................... 50
Placing Data Objects in the EEPROM Space........................... 51
Redefining Sections.................................................................. 53
Inserting Inline Assembly Instructions..................................... 55
Inlining with pragmas......................................................... 55
Inlining with _asm.............................................................. 56
Inlining Labels.................................................................... 58
Writing Interrupt Handlers ....................................................... 59
Placing Addresses in Interrupt Vectors .................................... 60
Inline Function.......................................................................... 61
Interfacing C to Assembly Language ....................................... 62
Register Usage .......................................................................... 64
Heap Management Control with the C Compiler ..................... 65
Modifying The Heap Location ........................................... 67
Data Representation.................................................................. 69
Chapter 4
Using The Compiler
Invoking the Compiler.............................................................. 72
Compiler Command Line Options ..................................... 73
File Naming Conventions......................................................... 78
Generating Listings................................................................... 79
Generating an Error File ........................................................... 79
Return Status............................................................................. 79
Examples .................................................................................. 79
C Library Support ..................................................................... 80
How C Library Functions are Packaged............................. 80
Inserting Assembler Code Directly .................................... 80
Linking Libraries with Your Program................................ 80
Integer Library Functions................................................... 80
Common Input/Output Functions....................................... 81
ii
Functions Implemented as Macros..................................... 81
Including Header Files ....................................................... 82
Descriptions of C Library Functions ........................................ 83
Generate inline assembly code ........................................... 84
Abort program execution.................................................... 85
Find absolute value............................................................. 86
Arccosine............................................................................ 87
Arcsine................................................................................ 88
Arctangent .......................................................................... 89
Arctangent of y/x................................................................ 90
Convert buffer to double .................................................... 91
Convert buffer to integer .................................................... 92
Convert buffer to long ........................................................ 93
Test or get the carry bit....................................................... 94
Round to next higher integer .............................................. 95
Verify the recorded checksum............................................ 96
Verify the recorded checksum............................................ 97
Verify the recorded checksum............................................ 98
Verify the recorded checksum............................................ 99
Verify the recorded checksum.......................................... 100
Verify the recorded checksum.......................................... 101
Cosine ............................................................................... 102
Hyperbolic cosine............................................................. 103
Divide with quotient and remainder ................................. 104
Copy a buffer to an eeprom buffer ................................... 105
Erase the eeprom space .................................................... 106
Propagate fill character throughout eeprom buffer .......... 107
Exit program execution .................................................... 108
Exponential....................................................................... 109
Find double absolute value ............................................... 110
Copy a moveable code segment in RAM ......................... 111
Round to next lower integer ............................................. 112
Find double modulus ........................................................ 113
Extract fraction from exponent part ................................. 114
Get character from input stream ....................................... 115
Get a text line from input stream...................................... 116
Test the interrupt mask bit................................................ 117
Test the interrupt line level............................................... 118
Test for alphabetic or numeric character .......................... 119
Test for alphabetic character ............................................ 120
Test for control character.................................................. 121
Test for digit ..................................................................... 122
Test for graphic character ................................................. 123
iii
Test for lowercase character............................................. 124
Test for printing character ................................................ 125
Test for punctuation character.......................................... 126
Test for whitespace character ........................................... 127
Test for uppercase character............................................. 128
Test for hexadecimal digit................................................ 129
Find long absolute value .................................................. 130
Scale double exponent...................................................... 131
Long divide with quotient and remainder ........................ 132
Natural logarithm ............................................................. 133
Common logarithm .......................................................... 134
Test for maximum ............................................................ 135
Scan buffer for character .................................................. 136
Compare two buffers for lexical order ............................. 137
Copy one buffer to another............................................... 138
Copy one buffer to another............................................... 139
Propagate fill character throughout buffer ....................... 140
Test for minimum............................................................. 141
Extract fraction and integer from double ......................... 142
Raise x to the y power ...................................................... 143
Output formatted arguments to stdout.............................. 144
Put a character to output stream ....................................... 149
Put a text line to output stream......................................... 150
Generate pseudo-random number .................................... 151
Sin..................................................................................... 152
Hyperbolic sine................................................................. 153
Output arguments formatted to buffer.............................. 154
Real square root................................................................ 155
Seed pseudo-random number generator ........................... 156
Concatenate strings........................................................... 157
Scan string for first occurrence of character .................... 158
Compare two strings for lexical order.............................. 159
Copy one string to another ............................................... 160
Find the end of a span of characters in a set..................... 161
Find length of a string ...................................................... 162
Concatenate strings of length n ........................................ 163
Compare two n length strings for lexical order................ 164
Copy n length string ......................................................... 165
Find occurrence in string of character in set .................... 166
Scan string for last occurrence of character ..................... 167
Find the end of a span of characters not in set ................. 168
Scan string for first occurrence of string .......................... 169
Convert buffer to double .................................................. 170
iv
Convert buffer to long ...................................................... 171
Convert buffer to unsigned long....................................... 172
Tangent ............................................................................. 173
Hyperbolic tangent ........................................................... 174
Convert character to lowercase if necessary .................... 175
Convert character to uppercase if necessary .................... 176
Chapter 5
Using The Assembler
Invoking castm8...................................................................... 178
Object File............................................................................... 181
Listings.................................................................................... 181
Assembly Language Syntax.................................................... 182
Instructions ....................................................................... 183
Labels ............................................................................... 183
Temporary Labels............................................................. 184
Constants .......................................................................... 185
Expressions....................................................................... 186
Macro Instructions............................................................ 188
Conditional Directives...................................................... 191
Sections............................................................................. 192
Bit Handling ..................................................................... 193
Includes............................................................................. 194
Branch Optimization............................................................... 194
Old Syntax .............................................................................. 195
C Style Directives ................................................................... 196
Assembler Directives.............................................................. 196
Align the next instruction on a given boundary ............... 197
Define the default base for numerical constants............... 198
Switch to the predefined .bsct section. ............................. 199
Turn listing of conditionally excluded code on or off...... 200
Allocate constant(s) .......................................................... 201
Allocate constant block .................................................... 202
Turn listing of debug directives on or off......................... 203
Allocate variable(s) .......................................................... 204
Conditional assembly ....................................................... 205
Conditional assembly ....................................................... 206
Stop the assembly ............................................................. 207
End conditional assembly................................................. 208
End conditional assembly................................................. 209
End macro definition ........................................................ 210
End repeat section............................................................. 211
Give a permanent value to a symbol ................................ 212
v
Assemble next byte at the next even address relative to the
start of a section................................................................ 213
Generate error message. ................................................... 214
Conditional assembly ....................................................... 215
Conditional assembly ....................................................... 216
Conditional assembly ....................................................... 217
Conditional assembly ....................................................... 218
Conditional assembly ....................................................... 219
Conditional assembly ....................................................... 220
Conditional assembly ....................................................... 221
Conditional assembly ....................................................... 222
Conditional assembly ....................................................... 223
Conditional assembly ....................................................... 224
Conditional assembly ....................................................... 225
Include text from another text file.................................... 226
Turn on listing during assembly....................................... 227
Give a text equivalent to a symbol ................................... 228
Create a new local block .................................................. 229
Define a macro ................................................................. 230
Send a message out to STDOUT...................................... 232
Terminate a macro definition ........................................... 233
Turn on or off listing of macro expansion........................ 234
Turn off listing. ................................................................ 235
Disable pagination in the listing file ................................ 236
Creates absolute symbols ................................................. 237
Sets the location counter to an offset from the beginning of a
section............................................................................... 238
Start a new page in the listing file .................................... 239
Specify the number of lines per pages in the listing file .. 240
Repeat a list of lines a number of times ........................... 241
Repeat a list of lines a number of times ........................... 242
Restore saved section ....................................................... 244
Terminate a repeat definition ........................................... 245
Save section...................................................................... 246
Turn on or off section crossing......................................... 247
Define a new section ........................................................ 248
Give a resetable value to a symbol................................... 250
Insert a number of blank lines before the next statement in the
listing file.......................................................................... 251
Place code into a section. ................................................. 252
Specify the number of spaces for a tab character in the listing
file..................................................................................... 253
Define default header ....................................................... 254
vi
Declare bit symbol as being defined elsewhere ............... 255
Declare a variable to be visible ........................................ 256
Declare symbol as being defined elsewhere..................... 257
Declare a symbol as a default definition .......................... 258
Chapter 6
Using The Linker
Introduction............................................................................. 261
Overview................................................................................. 262
Linker Command File Processing........................................... 264
Inserting comments in Linker commands ........................ 265
Linker Options ........................................................................ 266
Global Command Line Options........................................ 267
Segment Control Options ................................................. 269
Segment Grouping............................................................ 273
Linking Files on the Command line ................................. 273
Example............................................................................ 274
Include Option .................................................................. 274
Example............................................................................ 275
Private Region Options..................................................... 275
Symbol Definition Option ................................................ 276
Reserve Space Option....................................................... 277
Handle Dependencies ....................................................... 278
Section Relocation .................................................................. 279
Address Specification....................................................... 279
Overlapping Control......................................................... 279
Setting Bias and Offset ........................................................... 280
Setting the Bias................................................................. 280
Setting the Offset.............................................................. 280
Using Default Placement.................................................. 280
Bit Segment Handling ...................................................... 280
Linking Objects....................................................................... 282
Linking Library Objects.......................................................... 282
Library Order.................................................................... 283
Libraries Setup Search Paths ............................................ 284
Automatic Data Initialization.................................................. 285
Descriptor Format............................................................. 285
Moveable Code ....................................................................... 286
Manual Segment Initialization................................................ 288
Checksum Computation.......................................................... 289
DEFs and REFs....................................................................... 291
Special Topics......................................................................... 292
vii
Private Name Regions ...................................................... 292
Renaming Symbols .......................................................... 293
Absolute Symbol Tables .................................................. 296
Description of The Map File .................................................. 297
Special Segments .debug and .info................................... 298
Return Value........................................................................... 299
Linker Command Line Examples........................................... 300
Chapter 7
Debugging Support
Generating Debugging Information........................................ 304
Generating Line Number Information.............................. 304
Generating Data Object Information................................ 304
The cprd Utility ...................................................................... 306
Command Line Options ................................................... 306
Examples .......................................................................... 307
The clst utility ......................................................................... 308
Command Line Options ................................................... 308
Chapter 8
Programming Support
The chex Utility ...................................................................... 312
Command Line Options ................................................... 312
Return Status .................................................................... 314
Examples .......................................................................... 314
The clabs Utility ..................................................................... 316
Command Line Options ................................................... 316
Return Status .................................................................... 317
Examples .......................................................................... 317
The clib Utility........................................................................ 319
Command Line Options ................................................... 319
Return Status .................................................................... 320
Examples .......................................................................... 320
The cobj Utility....................................................................... 322
Command Line Options ................................................... 322
Return Status .................................................................... 323
Examples .......................................................................... 323
The Ctat Utility ....................................................................... 324
Command Line Options ................................................... 324
Return Status .................................................................... 325
Examples .......................................................................... 325
The cvdwarf Utility ................................................................ 326
Command Line Options ................................................... 326
viii
Return Status .................................................................... 329
Examples .......................................................................... 329
Chapter A
Compiler Error Messages
Parser (cpstm8) Error Messages ............................................. 332
Code Generator (cgstm8) Error Messages.............................. 348
Assembler (castm8) Error Messages ...................................... 349
Linker (clnk) Error Messages ................................................. 352
Chapter B
Modifying Compiler Operation
The Configuration File............................................................ 356
Changing the Default Options ................................................ 358
Creating Your Own Options............................................. 358
Example .................................................................................. 359
Chapter C
STM8 Machine Library
Update an int bitfield in near memory.............................. 362
Integer multiplication by char .......................................... 363
Integer multiplication by char .......................................... 364
Integer multiplication by char with long result ................ 365
Integer multiplication by char with long result ................ 366
Eeprom char bit field update ............................................ 367
Write a char in eeprom ..................................................... 368
Write a long int in eeprom................................................ 369
Write a short int in eeprom............................................... 370
Move a structure in eeprom .............................................. 371
Add float to float .............................................................. 372
Compare floats.................................................................. 373
Divide float by float.......................................................... 374
Add float to float in memory ............................................ 375
Multiply float by float in memory .................................... 376
Subtract float from float in memory................................. 377
Multiply float by float ...................................................... 378
Negate a float.................................................................... 379
Subtract float from float ................................................... 380
Convert float to integer..................................................... 381
Convert float into long integer ......................................... 382
Compare a float in memory to zero .................................. 383
Get a long word from memory ......................................... 384
ix
Get a long word from memory ......................................... 385
Get a word from far memory............................................ 386
Get a word from far memory............................................ 387
Get a word from far memory............................................ 388
Get a word from far memory............................................ 389
Get a word from far memory............................................ 390
Get a word from far memory............................................ 391
Quotient of integer division.............................................. 392
Integer multiplication ....................................................... 393
Convert integer into float ................................................. 394
Convert integer into long.................................................. 395
Convert integer into long.................................................. 396
Convert integer into long.................................................. 397
Perform C switch statement on char................................. 398
Perform C switch statement on long ................................ 399
Perform C switch statement on integer ............................ 400
Long integer addition ....................................................... 401
Long integer addition ....................................................... 402
Bitwise AND for long integers......................................... 403
Long integer compare....................................................... 404
Quotient of long integer division ..................................... 405
Long addition ................................................................... 406
Long addition ................................................................... 407
Long bitwise AND ........................................................... 408
Long shift left ................................................................... 409
Long multiplication in memory........................................ 410
Negate a long integer in memory ..................................... 411
Long bitwise OR .............................................................. 412
Signed long shift right ...................................................... 413
Long subtraction............................................................... 414
Long subtraction............................................................... 415
Unsigned long shift right.................................................. 416
Long bitwise exclusive OR .............................................. 417
Long integer shift left ....................................................... 418
Remainder of long integer division .................................. 419
Multiply long integer by long integer .............................. 420
Negate a long integer........................................................ 421
Bitwise OR with long integers ......................................... 422
Long integer right shift..................................................... 423
Long test against zero....................................................... 424
Long integer subtraction................................................... 425
Long integer subtraction................................................... 426
x
Long integer compare with overflow ............................... 427
Convert long integer into float ......................................... 428
Load memory into long register ....................................... 429
Quotient of unsigned long integer division ...................... 430
Remainder of unsigned long integer division................... 431
Unsigned long integer shift right...................................... 432
Bitwise exclusive OR with long integers ......................... 433
Compare a long integer to zero ........................................ 434
Far pointer addition .......................................................... 435
Far pointer addition .......................................................... 436
Put a long integer in memory ........................................... 437
Put a long integer in memory ........................................... 438
Put a word in far memory................................................. 439
Get a far pointer from far memory ................................... 440
Get a far pointer from far memory ................................... 441
Get a far pointer from far memory ................................... 442
Get a far pointer from far memory ................................... 443
Store long register in far memory..................................... 444
Store long register in memory .......................................... 445
Quotient of signed char division....................................... 446
Quotient of signed char division....................................... 447
Remainder of signed char division ................................... 448
Remainder of signed char division ................................... 449
Multiply long integer by unsigned byte............................ 450
Convert unsigned integer into float .................................. 451
Convert unsigned integer into long .................................. 452
Convert unsigned integer into long .................................. 453
Convert unsigned integer into long .................................. 454
Convert unsigned long integer into float .......................... 455
Multiply unsigned integers with long result..................... 456
Multiply signed integers with long result......................... 457
Store a far pointer into far memory .................................. 458
Copy a structure into another ........................................... 459
Copy a structure in far memory........................................ 460
Copy a large structure in far memory............................... 461
Copy a structure into another ........................................... 462
Copy a large structure into another .................................. 463
Store a far pointer into far memory .................................. 464
Copy a structure into another ........................................... 465
Copy a structure in far memory........................................ 466
Copy a large structure in far memory............................... 467
Copy a structure into another ........................................... 468
xi
Copy a large structure into another .................................. 469
Chapter D
Compiler Passes
The cpstm8 Parser .................................................................. 472
Command Line Options ................................................... 472
Warning Levels ................................................................ 478
Extra verifications ............................................................ 478
Return Status .................................................................... 479
Example............................................................................ 479
The cgstm8 Code Generator ................................................... 480
Command Line Options ................................................... 480
Return Status .................................................................... 482
Example............................................................................ 482
The costm8 Assembly Language Optimizer .......................... 483
Command Line Options ................................................... 483
Disabling Optimization .................................................... 484
Return Status .................................................................... 484
Example............................................................................ 484
xii
Preface
T he Cross Compiler User's Guide for STM8 is a reference guide for
programmers writing C programs for STM8 microcontroller envi-
ronments. It provides an overview of how the cross compiler works,
and explains how to compile, assemble, link and debug programs. It
also describes the programming support utilities included with the cross
compiler and provides tutorial and reference information to help you
configure executable images to meet specific requirements. This man-
ual assumes that you are familiar with your host operating system and
with your specific target environment.
Chapter 6, “Using The Linker”, describes the linker and its options.
This chapter describes in detail all the features of the linker and their
use.
Introduction
This chapter explains how the compiler operates. It also provides a
basic understanding of the compiler architecture. This chapter includes
the following sections:
• Introduction
• Document Conventions
• Compiler Architecture
• Predefined Symbol
• Linking
• Listings
• Optimizations
• Memory Models
Introduction
The C cross compiler targeting the STM8 microcontroller reads C
source files, assembly language source files, and object code files, and
produces an executable file. You can request listings that show your C
source interspersed with the assembly language code and object code
that the compiler generates. You can also request that the compiler gen-
erate an object module that contains debugging information that can be
used by COSMIC’s C source level cross debugger or by other debug-
gers or in-circuit emulators.
Document Conventions
In this documentation set, we use a number of styles and typefaces to
demonstrate the syntax of various commands and to show sample text
you might type at a terminal or observe in a file. The following is a list
of these conventions.
Typewriter font
Used for user input/screen output. Typewriter (or courier) font is
used in the text and in examples to represent what you might type at a
terminal: command names, directives, switches, literal filenames, or
any other text which must be typed exactly as shown. It is also used in
other examples to represent what you might see on a screen or in a
printed listing and to denote executables.
For example, if you were instructed to type the compiler command that
generates debugging information, it would appears as:
If, however, the text included a partial listing of the file acia.c ‘an
example of text from a file or from output to the terminal’ then type-
writer font would still be used, but would be enclosed in a line box:
NOTE
Due to the page width limitations of this manual, a single invocation line
may be represented as two or more lines. You should, however, type the
invocation as one line unless otherwise directed.
Italics
Used for value substitution. Italic type indicates categories of items for
which you must substitute appropriate values, such as arguments or
hypothetical filenames. For example, if the text was demonstrating a
hypothetical command line to compile and generate debugging infor-
mation for any file, it might appear as:
[ Brackets ]
Items enclosed in brackets are optional. For example, the line:
[ options ]
options
means that one or more options must be specified because options is not
enclosed by brackets.
file1.[o|stm8]
means that one file with the extension .o or .sm8 may be specified, and
the line:
file1 [ file2 . . . ]
Conventions
All the compiler utilities share the same optional arguments syntax.
They are invoked by typing a command line.
Command Line
A command line is generally composed of three major parts:
Flags
Flags are used to select options or specify parameters. Options are rec-
ognized by their first character, which is always a ‘-’ or a ‘+’, followed
by the name of the flag (usually a single letter). Some flags are simply
yes or no indicators, but some must be followed by a value or some
additional information. The value, if required, may be a character
string, a single character, or an integer. The flags may be given in any
order, and two or more may be combined in the same argument, so long
as the second flag can’t be mistaken for a value that goes with the previ-
ous one.
Each utility can display its version number, build date and host system
by specifying the -vers option. The host name is ended by the -F
sequence if a license is necessary for executing the utility.
If the code is immediately followed by the character ‘>’, the option may
be specified more than once with different values. In that case, the
option name must be repeated for every specification.
Flag Function
Compiler Architecture
The C compiler consists of several programs that work together to
translate your C source files to executable files and listings. cxstm8
controls the operation of these programs automatically, using the
options you specify, and runs the programs described below in the order
listed:
cgstm8 - the code generator. cgstm8 accepts the output of cpstm8 and
generates assembly language statements.
Predefined Symbol
The COSMIC compiler defines the __CSMC__ preprocessor symbol. It
expands to a numerical value whose each bit indicates if a specific
option has been activated:
Linking
clnk combines all the object modules that make up your program with
the appropriate modules from the C library. You can also build your
own libraries and have the linker select files from them as well. The
linker generates an executable file which, after further processing with
the chex utility, can be downloaded and run on your target system. If
you specify debugging options when you invoke cxstm8, the compiler
will generate a file that contains debugging information. You can then
use the COSMIC’s debugger to debug your code.
clib - build and maintain object module libraries. clib allows you to
collect related files into a single named library file for convenient stor-
age. You use it to build and maintain object module libraries in standard
library format.
Listings
Several options for listings are available. If you request no listings, then
error messages from the compiler are directed to your terminal, but no
additional information is provided. Each error is labelled with the C
source file name and line number where the error was detected.
If you request an assembly language and object code listing with inter-
spersed C source, the compiler merges the C source as comments
among the assembly language statements and lines of object code that it
generates. Unless you specify otherwise, the error messages are still
written to your terminal. Your listing is the listing output from the
assembler.
Optimizations
The C cross compiler performs a number of compile time and optimiza-
tions that help make your application smaller and faster:
NOTE
The basic routine to program an eeprom byte is located in the library file
eeprom.s and has been written using the default input/output address .
This file must be modified if using a different base address.
Memory Models
The STM8 compiler supports several memory models allowing you to
choose the best configuration for your processor and your application.
You can choose to use 2-bytes addressing (applications smaller than
64k bytes) or 3-bytes addressing. You can also specify where variables
are located in the memory space by default: inside or outside the zero
page (short addressing). For more information, please refer to Chapter
3.
Tutorial Introduction
This chapter will demonstrate, step by step, how to compile, assemble
and link the example program acia.c, which is included on your distri-
bution media. Although this tutorial cannot show all the topics relevant
to the COSMIC tools, it will demonstrate the basics of using the com-
piler for the most common applications.
/* Authorize interrupts.
*/
#define rim() _asm("rim")
/* Some variables
*/
char buffer[SIZE]; /* reception buffer */
char *ptlec; /* read pointer */
char *ptecr; /* write pointer */
/* Character reception.
* Loops until a character is received.
*/
char getch(void)
{
char c; /* character to be returned */
/* Main program.
* Sets up the SCI and starts an infinite loop
* of receive transmit.
*/
void main(void)
{
ptecr = ptlec = buffer; /* initialize pointers */
USART_BRR1 = 0xc9; /* parameter for baud rate */
USART_CR1 = 0x00; /* param. for word length */
USART_CR2 = 0x2c; /* parameters for interrupt */
rim(); /* authorize interrupts */
for (;;) /* loop */
outch(getch()); /* get and put a char */
}
According to the options you will use, the following files, recognized
by the COSMIC naming conventions, will be generated:
acia.c:
Step 1: Compiling
The first step consists in compiling the C source file and producing an
assembly language file named acia.s.
The -s option directs cxstm8 to stop after having produced the assembly
file acia.s. You can then edit this file with your favourite editor. You can
also visualize it with the appropriate system command (type, cat,
more,...). For example under MS/DOS you would type:
type acia.s
As you use the C compiler, you may find it useful to see the various
actions taken by the compiler and to verify the options you selected.
acia.c:
cpstm8 -o \2.cx1 -i\cxstm8\hstm8 -u -hmods.h acia.c
cgstm8 -o \2.cx2 \2.cx1
costm8 -o acia.s \2.cx2
Step 2: Assembler
The second step of the compilation is to assemble the code previously
produced. The relocatable object file produced is acia.o.
cxstm8 acia.s
or
castm8 -c -l acia.s
Step 3: Linking
This step consists in linking relocatable files, also referred to as object
modules, produced by the compiler or by the assembler (<files>.o) into
an absolute executable file: acia.sm8 in our example. Code and data
sections will be located at absolute memory addresses. The linker is
used with a command file (acia.lkf in this example).
An application that uses one or more object module(s) may require sev-
eral sections (code, data, interrupt vectors, etc.,...) located at different
addresses. Each object module contains several sections. The compiler
creates the following sections:
Type Description
.text code (or program) section (e.g. ROM)
.fconst large constant and literal data (e.g. ROM, see @far)
.const constant and literal data (e.g. ROM)
.data initialized data in long addressing range memory
(see @near in chapter 3) (e.g. RAM)
.bss all non initialized data in long range memory (e.g.
RAM)
.bsct initialized data in the first 256 bytes (see @tiny in
chapter 3), also called short range or short
addressing range.
.ubsct non initialized data in the short range
.fdata large variables (@far)
.eeprom any variable in eeprom (@eeprom)
.bit bit variables
In our example, and in the test file provided with the compiler, the
acia.lkf file contains the following information:
You can create your own link command file by modifying the one pro-
vided with the compiler.
lines 1 to 3: These are comment lines. Each line can include comments.
They must be prefixed by the “#” character.
line 9: acia.o, the file that constitutes your application. It follows the
startup routine for code and data
By default and in our example, the .bss segment follows the .data seg-
ment.
The crts.o file contains the runtime startup that performs the following
operations:
After you have modified the linker command file, you can link by typ-
ing:
or
In this example the linker will locate and merge crts.o, acia.o and
module1.o in a text segment at 0xf000, a data segment at 0x100 and a
bss segment, if needed at 0x200. short range variables will be located
at 0x0. The rest of the application, module2.o and module3.o and the
libraries will be located and merged in a new text segment at 0x2000
then the interrupt vectors file, vector.o in a vector segment at 0x8000.
All constants will be located after the first text segment.
For more information about the linker, see Chapter 6, “Using The
Linker”.
This is not an issue when your application contains code and read-only
data (such as string or const variables). All you have to do is burn a
PROM with the correct values and plug it into your application board.
The problem comes up when your application uses initial data values
that you have defined with initialized static data. These static data val-
ues must reside in RAM.
char var2;
There is one exception to the above rules when you declare data that
will be located in the external memory, using the @near type quali-
fier. In this case, the data is generated into the .data section if it is ini-
tialized or in the .bss section otherwise.
The first method to ensure that these values are correct consists in add-
ing code in your application that reinitializes them from a copy that you
have created and located in ROM, at each restart of the application.
1) that defines a symbol that will force the linker to create a copy of
the initialized RAM in ROM
The following link file demonstrates how to achieve automatic data ini-
tialization.
In case of multiple code and data segments, a link command file could
be:
or
In the first case, the initialized data will be located after the first code
segment. In the second case, the -it option instructs the linker to locate
the initialized data after the segment marked with this flag. The initial-
ized data will be located after the second code segment located at
address 0xf800.
The -v option instructs the compiler driver to echo the name and options
of each program it calls. The -l option instructs the compiler driver to
create a mixed listing of C code and assembly language code in the file
acia.ls.
When the compiler exits, the following files are left in your current
directory:
This command will compile the acia.c file, create a listing named
acia.ls in the \mylist directory and an object file named acia.o in the
\myobj directory.
cxstm8 allows you to compile more than one file. The input files can be
C source files or assembly source files. You can also mix all of these
files.
This command will assemble the start.s file, and compile the two C
source files.
Programming
Environments
This chapter explains how to use the COSMIC program development
system to perform special tasks required by various STM8 applications.
Introduction
This chapter provides details about:
• Bit Variables
• Performing Input/Output in C
• Redefining Sections
• Inline Function
• Register Usage
• Data Representation
The table thus created and the copy of the RAM are located in ROM by
the linker, and used to do the initialization. An example of how to do
this is provided in the crtsi.s file, located in the headers sub-directory.
crtsi.s performs the same function as described with the crts.s, but with
one additional step. Lines (marked in bold) in crtsi.s include code to
copy the contents of initialized static data, which has been placed in the
text section by the linker, to the desired location in RAM.
NOTE
When using a model for application smaller than 64K, you must use the
specific startup (name ending with ‘0’).
NOTE
When using a model for application smaller than 64K, you must link with
the specific set of libraries and startup (names ending with ‘0’).
Bit Variables
The C compiler implements bit variables using the _Bool type name as
defined by the new ANSI/ISO standard C99 (also referenced as C9X).
A _Bool variable is a boolean object which only contains the values
true and false. They are implemented on single bits with value 1 for
true and 0 for false. When assigning an expression to a _Bool variable,
the compiler compares the expression against zero and assigns the
boolean result to the boolean variable. So, any integer, real or pointer
expression can be assigned to a boolean variable. It is not possible to
declare arrays of booleans nor pointers to booleans, but booleans can be
used as structure or union fields. Consecutive _Bool fields will be
packed in bytes.
The compiler packs global _Bool variables in bytes using a bit section
named .bit. Local _Bool variables are also packed in bytes regardless of
the memory model. _Bool arguments are passed widened to a single
byte.
_Bool in_range;
_Bool p_valid;
char *ptr;
Volatile types are useful for declaring data objects that appear to be in
conventional storage but are actually represented in machine registers
with special properties. You use the type qualifier volatile to declare
memory mapped input/output control registers, shared data objects, and
data objects accessed by signal handlers. The compiler will not opti-
mize references to volatile data.
NOTE
The volatile keyword must be used for any data object (variables) that
can be modified outside of the normal flow of the function. Without the
volatile keyword, all data objects are subject to normal redundant code
removal optimizations. Volatile MUST be used for the following condi-
tions:
You use const to declare data objects whose stored values you do not
intend to alter during execution of your program. You can therefore
place data objects of const type in ROM or in write protected program
segments. The cross compiler generates an error message if it encoun-
ters an expression that alters the value stored in a const data object.
If you declare a static data object of const type at either file level or at
block level, you may specify its stored value by writing a data initial-
izer. The compiler determines its stored value from its data initializer
before program startup, and the stored value continues to exist
unchanged until program termination. If you specify no data initializer,
the stored value is zero. If you declare a data object of const type at
argument level, you tell the compiler that your program will not alter
the value stored in that argument in the related function. If you declare a
data object of const type and dynamic lifetime at block level, you must
specify its stored value by writing a data initializer. If you specify no
data initializer, the stored value is undefined.
The const keyword implies the @near memory space to allow such a
variable to be located in the code space. If a memory space modifier is
explicitly given on a declaration using the const keyword, the compiler
uses the given space instead of the default one, meaning that the object
may not be located in the code space depending on the memory space
given. In such a case, the const keyword still enforces the assignment
checking.
You may specify const and volatile together, in either order. A const
volatile data object could be a Read-only status register, or a status var-
iable whose value may be set by another program.
Performing Input/Output in C
You perform input and output in C by using the C library functions
getchar, gets, printf, putchar, puts and sprintf. They are described in
chapter 4.
The C source code for these and all other C library functions is included
with the distribution, so that you can modify them to meet your specific
needs. Note that all input/output performed by C library functions is
supported by underlying calls to getchar and putchar. These two func-
tions provide access to all input/output library functions. The library is
built in such a way so that you need only modify getchar and putchar,
the rest of the library is independent of the runtime environment.
char getchar(void);
char putchar(char c);
Such a declaration does not reserve any space in memory. The compiler
still creates a label, using an equate definition, in order to reference the
C object symbolically. This symbol is made public to allow external
usage from any other file.
char c;
c = MISCR1; /* to read from input port */
MISCR1 = c; /* to write to output port */
Note that COSMIC C does support the pointer and #define methods of
implementing I/O access.
struct acia
{
char status;
char data;
} acia @0x6000
#include <iostm8.h>
Note that the compiler will access to these registers as standard varia-
bles. In some case of reading or writing some “int” registers, you should
declare an union (with two char and one int) instead of using directly
the I/O register.
The run-time startup files, crtsi.s and crtsi.s, contain code which initial-
izes the bss section space to zero.
@tiny char c;
To place data objects into short range memory on a file basis, you can
use the #pragma directive of the compiler:
instructs the compiler to place all data objects of storage class extern or
static into short range memory for the current unit of compilation (usu-
ally a file). The section must end with a #pragma space extern []
@near to revert to the default compiler behaviour.
The compiler provides the ctat utility, which helps optimizing short
range allocation by automatically extracting the list of all variables
which can be efficiently moved to the short range area, by producing a
header file which must be used to rebuild the application. For more
information, see “The Ctat Utility” in Chapter 8.
NOTE
The code generator does not check for short range overflow.
where ## represents the size of the short range section in bytes. Note
that the size of the short range section can never exceed 256 bytes.
instructs the compiler to locate the variable ext in the long range mem-
ory.
To place data objects into long range memory on a file basis, if not yet
selected by the memory model, you can use the #pragma directive of
the compiler:
instructs the compiler to place all data objects of storage class extern or
static into Long Range memory for the current unit of compilation (usu-
ally a file).
The section must end with a #pragma space extern [] @tiny to revert
to the default compiler behaviour.
To place all data objects from a file into eeprom, you can use the
#pragma directive of the compiler:
instructs the compiler to treat all extern and static data in the current file
as eeprom locations. The @near modifier is necessary because the eep-
rom is located outside the short range.
The library routines are optimized to take advantage of the four byte
word programming feature wherever possible. The library routines are
also using a few external symbols to locate the command registers in
the I/O register space. When a standard header file provided with the
compiler is included in at least one source file of the application, these
symbols are automatically found. Otherwise, it is necessary to provide
these symbols either by extra C declarations:
+def _FLASH_IAPSR=0x505f
+def _FLASH_CR2=0x505b
+def _FLASH_NCR2=0x505c
The addresses provided must match the proper register addresses of the
target device.
NOTE
The code generator cannot check if data address will be eeprom
addresses after linkage.
Redefining Sections
The compiler uses by default predefined sections to output the various
component of a C program. The default sections are:
Section Description
.text executable code
.const text string and constants
.fconst large constant variables (@far)
.data initialized variables (@near)
.bss uninitialized variables (@near)
.bsct initialized variables in short range (@tiny by default)
.ubsct uninitialized variables in short range (@tiny by default)
.fdata large variables (@far)
.eeprom any variable in eeprom (@eeprom)
.bit bit variables
const
_Bool
@tiny
@near
@far
@eeprom
A section name is a plain C identifier which does not begin with a dot
character, and which is no longer than 13 characters. The compiler will
prefix automatically the section name with a dot character when passing
this information to the assembler. It is possible to switch back to the
default sections by omitting the section name in the <qualified_name>
sequence.
Note that {name} and [name] are equivalent for constant and eeprom
sections as they are all considered as initialized.
#pragma section ()
Directive Description
#pragma asm start assembler block
#pragma endasm end assembler block
The compiler also accepts shorter sequences with the same meaning:
Directive Description
#asm start assembler block
#endasm end assembler block
#pragma asm
xref asmvar
#pragma endasm
void func(void)
{
if (test)
#asm /* no need for { */
scf ; set carry bit
rlc asmvar; access assembler variable
#endasm
else
test = 1;
}
The “string constant” argument is the assembly code you want embed-
ded in your C program. “arguments” follow the standard C rules for
passing arguments. The string you specify follows standard C rules. For
example, carriage returns can be denoted by the ‘\n’ character.
ldw x,sp
callf f_main
The ‘\n’ character is used to separate the instructions when writing mul-
tiple instructions in the same line.
NOTE
The argument string must be shorter than 255 characters. If you wish to
insert longer assembly code strings you will have to split your input
among consecutive calls to _asm().
_asm() does not perform any checks on its argument string. Only the
assembler can detect errors in code passed as argument to an _asm()
call.
NOTE
With both methods, the assembler source is added as is to the code dur-
ing the compilation. The optimizer does not modify the specified instruc-
tions, unless the -a option is specified on the code generator. The
assembler input can use lowercase or uppercase mnemonics, and may
include assembler comments.
Inlining Labels
When labels are necessary in the inlined assembly code, the compiler
provides a special syntax allowing local labels to be created and han-
dled without interaction with other labels and the optimizer. The
sequence $N in the assembly source is replaced by a new label name
while the sequence $L is replaced by the label name created by the last
$N. Using this syntax, a simple wait loop may be entered as follow:
#asm
ld a,#7
$N:
dec a
jrne $L ; loop on the previous label
#endasm
When you define an @interrupt function, the compiler uses the “iret”
instruction for the return sequence, and saves, if necessary, the memory
bytes used by the compiler for its internal usage. Those areas are c_x (3
bytes), c_y (3 bytes) and c_lreg (4 bytes). Those bytes will be saved
and restored if the interrupt function uses them directly. If the interrupt
function does not uses these areas directly, but calls another C function,
the c_x and c_y areas will be automatically saved and restored, unless
using the type qualifier @nosvf on the interrupt function definition.
This qualifier can be used when the called functions are known not
using those areas, but the compiler does not perform any verification.
The c_lreg area is not saved implicitly in such a case, in order to keep
the interrupt function as efficient as possible. If any function called by
the interrupt function uses longs or floats, the c_lreg area can be saved
by using the type qualifier @svlreg on the interrupt function definition.
The linker checks c_lreg usage and produces an error message if an
interrupt routine uses that area and does not save it. Whatever the model
used is, these copies are made directly on the stack.
NOTE
The @interrupt modifier is an extension to the ANSI standard.
silicon bug (cf. STM8 errata sheet available on the ST web site). The
compiler detects if a function uses directly these instructions or calls a
machine library routine using these instructions. If an interrupt function
calls another C function, the compiler produces this sequence uncondi-
tionally unless the interrupt function has been declared with the type
qualifier @noprd and no direct usage has been detected. This auto-
matic process can be disabled by compiling with option -gdp. In such a
case, the programmer must add protecting sequences by inline assem-
bly code wherever it is necessary.
Refer to the vector.c file provided with the compiler example for a more
accurate implementation description.
where vector.o is the file which contains the vector table. This file is
provided in the compiler package.
Inline Function
The compiler is able to inline a function body instead of producing a
function call. This feature allows the program to run faster but produces
a larger code. A function to be inlined has to be defined with the
@inline modifier. Such a function is kept by the compiler and does not
produced any code yet. Each time this function is called in the same
source file, the call is replaced by the full body of the inlined function.
Because inlined functions are in fact local to a source file, they should
be defined in a header file if they have to be used by several source
files. To allow the arguments to be passed properly, inlined functions
must be defined with prototypes.
NOTE
Inline functions cannot declare static local variables and cannot call
themselves either directly or indirectly.
carry the carry function is used to test or get the carry bit from
the condition register. If the carry function is used in a
test, the compiler produces a jnrc or jrc instruction. If
the carry function is used in any other expression, the
compiler produces a code sequence setting the a regis-
ter to 0 or 1 depending on the carry bit value.
irq the irq function is used to test the interrupt line level
using the jrih or jril instruction. The irq function can be
used only in a test
imask the imask function is used to test the interrupt mask bit
in the condition register using the jrm or jrnm instruc-
tion. The imask function can be used only in a test.
The compiler places function code in the .text section. Function code is
not to be altered or read as data. External function names are published
via xdef declarations.
Compiler literals, containing text strings, float and long constants, and
switch tables, are generated by default into the .const section. An
option on the code generator allows such constants to be produced in
the .text section. In any case, these literals must be linked in the @near
space.
The compiler generates initialized data declared with the @near modi-
fier into the .data section. Such external data names are published via
xref declarations. Data you declare to be of “const” type by adding the
type qualifier const to its base type is generated by default into the
.const section. Const variables declared with the @far modifier are
published in the .fconst section. Initialized data declared with the
@tiny space modifier will be generated into the .bsct section. Such
external data names are published via xref.b declarations. Uninitialized
data are normally generated into the .bss section for @near variables or
the .ubsct section for @tiny variables, unless forced to the .data or
.bsct section by the compiler option +nobss. Variables declared with
the @far modifier are published in the .fdata section. _Bool data is
generated in the .bit section and external names are published via xbit.b
declarations.
Register Usage
Except for the return value, the registers a, x, y and the condition codes
are undefined on return from a function call. The return value is in a if it
is of type char, @tiny pointer or a one byte structure, x if it is of type
short, integer, @near pointer or a two byte structure. The return value
is in the memory located at symbol c_lreg if it is of type long or float.
The return value is in the memory location c_x (upper byte) and the x
register (lower word) if it is of type @far pointer.
The first argument may be hold in register, and will be stored at the
function entry. Such a function declaration:
Stack pointer
_sbreak will return a NULL pointer if this move is not possible (usually
this is because the heap would overlap the stack). Therefore it is possi-
ble to change the heap default location by rewriting the _sbreak func-
tion.
If the new top is outside the authorized limits defined by the address of
the two objects _startmem and _endmem, the function returns a
NULL pointer, otherwise, it returns the start of the new allocated area.
Note that the top variable _brk is a static variable initialized to zero
(NULL pointer). It is set to the heap start on the first call. It is also pos-
sible to initialize it directly within the declaration, but in this case, we
create an initialized variable in the data segment which needs to be ini-
tialized by the startup. The current code avoids such a requirement by
initializing the variable to zero (in the bss segment), which is simply
done by the standard startup sequence.
The heap area is declared as an array of char simply named heap. The
algorithm is mainly the same, and once the new top is computed, it is
compared with the array limits. Note that the array is declared as a static
local variable. It is possible to have it declared as a static global varia-
ble. If you want it to be global, be careful on the selected name. You
should start it with a ‘_’ character to avoid any conflict with the applica-
tion variables.
If you need to place the heap array at a specific location, you need to
locate this module at a specific address using the linker options. In the
above example, the heap array will be located in the .bss segment, thus,
complicating the startup code which would need to zero two bss sec-
tions instead of one. Compiling this function, with the +nobss option,
will force allocation of the heap, in the data segment and you can locate
it easily with linker directives as:
It is also possible to handle the heap area outside of any C object, just
by redefining the heap start and end values using the linker +def direc-
tives:
NOTE
Since the initial content of the area may be undefined, the -ib option
should be specified to exclude the segment in the automatic RAM initiali-
zation.
Data Representation
Data objects of type char are stored as one byte. A plain char is
defaulted to type unsigned char.
Data objects of type short int and int are stored as two bytes, more sig-
nificant byte first.
15 8 7 0
Data objects of type long int are stored as four bytes, in descending
order of significance.
31 24 23 16 15 8 7 0
@tiny pointers (short range) are stored as one byte. @near pointers
(long range) are stored as two bytes. @far pointers are stored as three
bytes, in descending order of significance.
23 16 15 8 7 0
Data objects of type float are represented as for the proposed IEEE
Floating Point Standard; four bytes stored in descending order of signif-
icance. The IEEE representation is: most significant bit is one for nega-
tive numbers, and zero otherwise; the next eight bits are the
characteristic, biased such that the binary exponent of the number is the
characteristic minus 126; the remaining bits are the fraction, starting
with the weighted bit. If the characteristic is zero, the entire number is
taken as zero, and should be all zeros to avoid confusing some routines
that do not process the entire number. Otherwise there is an assumed
0.5 (assertion of the weighted bit) added to all fractions to put them in
the interval [0.5, 1.0). The value of the number is the fraction, multi-
plied by -1 if the sign bit is set, multiplied by 2 raised to the exponent.
31 30 23 22 0
• Generating Listings
• C Library Support
cxstm8 is the name of the compiler. The option list is optional. You
must include the name of at least one input file <file>. <file> can be a
C source file with the suffix ‘.c’, or an assembly language source file
with the suffix ‘.s’. You may specify multiple input files with any com-
bination of these suffixes in any order.
If you do not specify any command line options, cxstm8 will compile
your <files> with the default options. It will also write the name of each
file as it is processed. It writes any error messages to STDERR.
compiles and assembles the acia.c C program, using the Stack Short
model, creating the relocatable program acia.o.
The example command above does not specify any compiler options. In
this case, the compiler will use only default options to compile and
assemble your program. You can change the operation of the compiler
by specifying the options you want when you run the compiler.
-ex use the compiler driver’s path as prefix to quickly locate the
executable passes. Default is to use the path variable envi-
ronment. This method is faster than the default behavior but
reduces the command line length.
-f* specify * as the name of a configuration file. This file con-
tains a list of options, which will be automatically used by
the compiler. If no file name is specified, then the compiler
looks for a default configuration file named cxstm8.cxf in the
compiler directory as specified in the installation process.
For more information, see Appendix B, “The Configuration
File”.
Note that some compiler options are specified to a default value in the
configuration file, cxstm8.cxf, and cannot be modified without modiy-
ing the configuration file itself (see Appendix B, “Modifying Compiler
Operation”). These options are -pu (char is unsigned by default) and
-ppb (pack local bit variables). Take special care if you remove the -pu
option: as libraries expect unsigned chars as argument, it is now the
user responsibility to manually declare the relevant variables as
unsigned char. If you forget this, run time errors may occur.
Generating Listings
You can generate listings of the output of any (or all) the compiler
passes by specifying the -l option to cxstm8. You can locate the listing
file in a different directory by using the -cl option.
The example program provided in the package shows the listing pro-
duced by compiling the C source file acia.c with the -l option:
The error file name is obtained from the source filename by replacing
the .c suffix by the .err suffix.
Return Status
cxstm8 returns success if it can process all files successfully. It prints a
message to STDERR and returns failure if there are errors in at least
one processed file.
Examples
To echo the names of each program that the compiler runs:
To save the intermediate files created by the code generator and halt
before the assembler:
C Library Support
This section describes the facilities provided by the C library. The C
cross compiler for STM8 includes all useful functions for programmers
writing applications for ROM-based systems.
NOTE
When using a model for application smaller than 64K, you must link with
the specific set of libraries (names ending with ‘0’).
#include <header_name>
The names of the header files packaged with the C library and the func-
tions declared in each header are listed below.
<float.h> - Header file for limit constants for floating point values.
<stdbool.h> - Header file for type bool and values true, false.
<stdlib.h> - Header file for general utilities: abs, abort, atof, atoi, atol,
div, exit, labs, ldiv, rand, srand, strtod, strtol and strtoul.
Functions returning int - C library functions that return int and can
therefore be called without any header file are: isalnum, isalpha, iscntrl,
isgraph, isprint, ispunct, isspace, isxdigit, isdigit, isupper, islower,
sbreak, tolower and toupper.
The syntax field describes the function prototype with the return type
and the expected arguments, and if any, the header file name where this
function has been declared.
_asm
Description
Generate inline assembly code
Syntax
_asm(“string constant”, arguments...)
Function
_asm() generates inline assembly code by copying <string constant>
and quoting it into the output assembly code stream. <arguments> are
first evaluated following the usual rules for passing arguments. The first
argument is kept in the a register or the x:a register pair whenever pos-
sible, and all other arguments are pushed onto the stack. After the
<string constant> code is output, arguments pushed to the stack are
removed before to continue.
Return Value
Nothing, unless _asm() is used in an expression. In that case, standard
return conventions must be followed. See “Register Usage” in Chapter
3.
Example
The sequence inc x; call _main, may be generated by the following call:
Note that the string-quoting syntax matches the familiar printf() func-
tion.
Notes
_asm() is not packaged in any library. It is recognized by the compiler
itself.
abort
Description
Abort program execution
Syntax
#include <stdlib.h>
void abort(void)
Function
abort stops the program execution by calling the exit function which is
placed by the startup module just after the call to the main function.
Return Value
abort never returns.
Example
To abort in case of error:
if (fatal_error)
abort();
See Also
exit
Notes
abort is a macro equivalent to the function name exit.
abs
Description
Find absolute value
Syntax
#include <stdlib.h>
int abs(int i)
Function
abs obtains the absolute value of i. No check is made to see that the
result can be properly represented.
Return Value
abs returns the absolute value of i, expressed as an int.
Example
To print out a debit or credit balance:
See Also
labs, fabs
Notes
abs is packaged in the integer library, and may be implemented as a
macro.
acos
Description
Arccosine
Syntax
#include <math.h>
double acos(double x)
Function
acos computes the angle in radians the cosine of which is x, to full dou-
ble precision.
Return Value
acos returns the closest internal representation to acos(x), expressed as
a double floating value in the range [0, pi]. If x is outside the range
[-1, 1], acos returns zero.
Example
To find the arccosine of x:
theta = acos(x);
See Also
asin, atan, atan2
Notes
acos is packaged in the floating point library.
asin
Description
Arcsine
Syntax
#include <math.h>
double asin(double x)
Function
asin computes the angle in radians the sine of which is x, to full double
precision.
Return Value
asin returns the nearest internal representation to asin(x), expressed as a
double floating value in the range [-pi/2, pi/2]. If x is outside the range
[-1, 1], asin returns zero.
Example
To compute the arcsine of y:
theta = asin(y);
See Also
acos, atan, atan2
Notes
asin is packaged in the floating point library.
atan
Description
Arctangent
Syntax
#include <math.h>
double atan(double x)
Function
atan computes the angle in radians; the tangent of which is x, atan
computes the angle in radians; the tangent of which is x, to full double
precision.
Return Value
atan returns the nearest internal representation to atan(x), expressed as
a double floating value in the range [-pi/2, pi/2].
Example
To find the phase angle of a vector in degrees:
See Also
acos, asin, atan2
Notes
atan is packaged in the floating point library.
atan2
Description
Arctangent of y/x
Syntax
#include <math.h>
double atan2(double y, double x)
Function
atan2 computes the angle in radians the tangent of which is y/x to full
double precision. If y is negative, the result is negative. If x is negative,
the magnitude of the result is greater than pi/2.
Return Value
atan2 returns the closest internal representation to atan(y/x), expressed
as a double floating value in the range [-pi, pi]. If both input arguments
are zero, atan2 returns zero.
Example
To find the phase angle of a vector in degrees:
See Also
acos, asin, atan
Notes
atan2 is packaged in the floating point library.
atof
Description
Convert buffer to double
Syntax
#include <stdlib.h>
double atof(char *nptr)
Function
atof converts the string at nptr into a double. The string is taken as the
text representation of a decimal number, with an optional fraction and
exponent. Leading whitespace is skipped and an optional sign is permit-
ted; conversion stops on the first unrecognizable character. Acceptable
inputs match the pattern:
[+|-]d*[.d*][e[+|-]dd*]
where d is any decimal digit and e is the character ‘e’ or ‘E’. No checks
are made against overflow, underflow, or invalid character strings.
Return Value
atof returns the converted double value. If the string has no recogniza-
ble characters, it returns zero.
Example
To read a string from STDIN and convert it to a double at d:
gets(buf);
d = atof(buf);
See Also
atoi, atol, strtol, strtod
Notes
atof is packaged in the floating point library.
atoi
Description
Convert buffer to integer
Syntax
#include <stdlib.h>
int atoi(char *nptr)
Function
atoi converts the string at nptr into an integer. The string is taken as the
text representation of a decimal number. Leading whitespace is skipped
and an optional sign is permitted; conversion stops on the first unrecog-
nizable character. Acceptable characters are the decimal digits. If the
stop character is l or L, it is skipped over.
Return Value
atoi returns the converted integer value. If the string has no recogniza-
ble characters, zero is returned.
Example
To read a string from STDIN and convert it to an int at i:
gets(buf);
i = atoi(buf);
See Also
atof, atol, strtol, strtod
Notes
atoi is packaged in the integer library.
atol
Description
Convert buffer to long
Syntax
#include <stdlib.h>
long atol(char *nptr)
Function
atol converts the string at nptr into a long integer. The string is taken as
the text representation of a decimal number. Leading whitespace is
skipped and an optional sign is permitted; conversion stops on the first
unrecognizable character. Acceptable characters are the decimal digits.
If the stop character is l or L it is skipped over.
Return Value
atol returns the converted long integer. If the string has no recognizable
characters, zero is returned.
Example
To read a string from STDIN and convert it to a long l:
gets(buf);
l = atol(buf);
See Also
atof, atoi, strtol, strtod
Notes
atol is packaged in the integer library.
carry
Description
Test or get the carry bit
Syntax
#include <processor.h>
@inline char carry(void)
Function
carry is an inline function allowing to test or get the value of the carry
bit. When used in an if construct, this function expands directly to a bcc
or bcs instruction. When used in an expression, it expands in order to
build in the a register the value 0 or 1 depending on the carry bit value.
Return Value
carry returns 0 or 1 in the a register if such a value is needed.
Example
low <<= 1; produces sll _low
if (carry()) jruge L1
++high; inc _high
L1:
Notes
carry is an inline function and then is not defined in any library. It is
therefore not possible to take its address. For more information, see
“Inline Function” in Chapter 3.
ceil
Description
Round to next higher integer
Syntax
#include <math.h>
double ceil(double x)
Function
ceil computes the smallest integer greater than or equal to x.
Return Value
ceil returns the smallest integer greater than or equal to x, expressed as
a double floating value.
Example
x ceil(x)
5.1 6.0
5.0 5.0
0.0 0.0
-5.0 -5.0
-5.1 -5.0
See Also
floor
Notes
ceil is packaged in the floating point library.
_checkcrc16
Description
Verify the recorded checksum
Syntax
int _checkcrc16()
Function
_checkcrc16 scans the descriptor built by the linker and controls at the
end that the computed CCITT 16 bit checksum is equal to the one
expected. For more infomation, see “Checksum Computation” in Chap-
ter 6.
Return Value
_checkcrc16 returns 0 if the checksum is correct, or a value different of
0 otherwise.
Example
if (_checkcrc16())
abort();
Notes
The descriptor is built by the linker only if the _checkcrc16 function is
called by the application, even if there are segments marked with the
-ck option.
See Also
_checkcrc16x
_checkcrc16x
Description
Verify the recorded checksum
Syntax
int _checkcrc16x()
Function
_checkcrc16x scans the descriptor built by the linker and controls at the
end that the computed CCITT 16 bit checksum is equal to the one
expected. For more infomation, see “Checksum Computation” in Chap-
ter 6.
Return Value
_checkcrc16x returns 0 if all the checksums are correct, or a value dif-
ferent of 0 otherwise.
Example
if (_checkcrc16x())
abort();
Notes
The descriptor is built by the linker only if the _checkcrc16x function is
called by the application, even if there are segments marked with the
-ck option.
See Also
_checkcrc16
_checksum
Description
Verify the recorded checksum
Syntax
int _checksum()
Function
_checksum scans the descriptor built by the linker and controls that the
computed checksum is equal to the one expected. For more infomation,
see “Checksum Computation” in Chapter 6.
Return Value
_checksum returns 0 if the checksum is correct, or a value different of 0
otherwise.
Example
if (_checksum())
abort();
Notes
The descriptor is built by the linker only if the _checksum function is
called by the application, even if there are segments marked with the
-ck option.
See Also
_checksumx, _checksum16, _checksum16x
_checksumx
Description
Verify the recorded checksum
Syntax
int _checksumx()
Function
_checksumx scans the descriptor built by the linker and controls at the
end that the computed 8 bit checksum is equal to the one expected. For
more infomation, see “Checksum Computation” in Chapter 6.
Return Value
_checksumx returns 0 if all the checksums are correct, or a value differ-
ent of 0 otherwise.
Example
if (_checksumx())
abort();
Notes
The descriptor is built by the linker only if the _checksumx function is
called by the application, even if there are segments marked with the
-ck option.
See Also
_checksum, _checksum16, _checksum16x
_checksum16
Description
Verify the recorded checksum
Syntax
int _checksum16()
Function
_checksum16 scans the descriptor built by the linker and controls at the
end that the computed 16 bit checksum is equal to the one expected. For
more infomation, see “Checksum Computation” in Chapter 6.
Return Value
_checksum16 returns 0 if the checksum is correct, or a value different of
0 otherwise.
Example
if (_checksum16())
abort();
Notes
The descriptor is built by the linker only if the _checksum16 function is
called by the application, even if there are segments marked with the
-ck option.
See Also
_checksum, _checksumx, _checksum16x
_checksum16x
Description
Verify the recorded checksum
Syntax
int _checksum16x()
Function
_checksum16x scans the descriptor built by the linker and controls at
the end that the computed 16 bit checksum is equal to the one expected.
For more infomation, see “Checksum Computation” in Chapter 6.
Return Value
_checksum16x returns 0 if all the checksums are correct, or a value dif-
ferent of 0 otherwise.
Example
if (_checksum16x())
abort();
Notes
The descriptor is built by the linker only if the _checksum16x function
is called by the application, even if there are segments marked with the
-ck option.
See Also
_checksum, _checksumx, _checksum16
cos
Description
Cosine
Syntax
#include <math.h>
double cos(double x)
Function
cos computes the cosine of x, expressed in radians, to full double preci-
sion. If the magnitude of x is too large to contain a fractional quadrant
part, the value of cos is 1.
Return Value
cos returns the nearest internal representation to cos(x) in the range [0,
pi], expressed as a double floating value. A large argument may return a
meaningless value.
Example
To rotate a vector through the angle theta:
See Also
sin, tan
Notes
cos is packaged in the floating point library.
cosh
Description
Hyperbolic cosine
Syntax
#include <math.h>
double cosh(double x)
Function
cosh computes the hyperbolic cosine of x to full double precision.
Return Value
cosh returns the nearest internal representation to cosh(x) expressed as a
double floating value. If the result is too large to be properly repre-
sented, cosh returns zero.
Example
To use the Moivre's theorem to compute (cosh x + sinh x) to the nth
power:
See Also
exp, sinh, tanh
Notes
cosh is packaged in the floating point library.
div
Description
Divide with quotient and remainder
Syntax
#include <stdlib.h>
div_t div(int numer, int denom)
Function
div divides the integer numer by the integer denom and returns the quo-
tient and the remainder in a structure of type div_t. The field quot con-
tains the quotient and the field rem contains the remainder.
Return Value
div returns a structure of type div_t containing both quotient and
remainder.
Example
To get minutes and seconds from a delay in seconds:
div_t result;
result = div(time, 60);
min = result.quo;
sec = result.rem;
See Also
ldiv
Notes
div is packaged in the integer library.
eepcpy
Description
Copy a buffer to an eeprom buffer
Syntax
#include <string.h>
void *eepcpy(void *s1, void *s2, unsigned int n)
Function
eepcpy copies the first n characters starting at location s2 into the eep-
rom buffer beginning at s1.
Return Value
Nothing.
Example
To place “first string, second string” in eepbuf[]:
See Also
eepset, eepera
Notes
eepcpy is packaged in the integer library.
eepera
Description
Erase the eeprom space
Syntax
void eepera(void *s, unsigned int n)
Function
eepera erases the first n bytes starting at location s.
Return Value
Nothing.
Example
To erase the eeprom space:
See Also
eepcpy, eepset
Notes
eepera is a macro declared in the <string.h> header file, calling the
eepset function with argument 0.
eepset
Description
Propagate fill character throughout eeprom buffer
Syntax
#include <string.h>
void eepset(void *s, char c, unsigned int n)
Function
eepset floods the n character buffer starting at eeprom location s with
fill character c. The function waits for all bytes to be programmed.
Return Value
Nothing.
Example
To flood a 512 byte eeprom buffer with NULs:
See Also
eepcpy, eepera
Notes
eepset is packaged in the integer library.
exit
Description
Exit program execution
Syntax
#include <stdlib.h>
void exit(int status)
Function
exit stops the execution of a program by switching to the startup mod-
ule just after the call to the main function. The status argument is not
used by the current implementation.
Return Value
exit never returns.
Example
To exit in case of error:
if (fatal_error)
exit();
See Also
abort
Notes
exit is in the startup module.
exp
Description
Exponential
Syntax
#include <math.h>
double exp(double x)
Function
exp computes the exponential of x to full double precision.
Return Value
exp returns the nearest internal representation to exp x, expressed as a
double floating value. If the result is too large to be properly repre-
sented, exp returns zero.
Example
To compute the hyperbolic sine of x:
See Also
log
Notes
exp is packaged in the floating point library.
fabs
Description
Find double absolute value
Syntax
#include <math.h>
double fabs(double x)
Function
fabs obtains the absolute value of x.
Return Value
fabs returns the absolute value of x, expressed as a double floating
value.
Example
x fabs(x)
5.0 5.0
0.0 0.0
-3.7 3.7
See Also
abs, labs
Notes
fabs is packaged in the floating point library.
_fctcpy
Description
Copy a moveable code segment in RAM
Syntax
int _fctcpy(char name);
Function
_fctcpy copies a moveable code segment in RAM from its storage loca-
tion in ROM. _fctcpy scans the descriptor built by the linker and looks
for a moveable segment whose flag byte matches the given argument. If
such a segment is found, it is entirely copied in RAM. Any function
defined in that segment may then be called directly. For more informa-
tion, see “Moveable Code” in Chapter 6.
Return Value
_fctcpy returns a non zero value if a segment has been found and cop-
ied. It returns 0 otherwise.
Example
if (_fctcpy(‘b’))
flash();
Notes
_fctcpy is packaged in the machine library.
floor
Description
Round to next lower integer
Syntax
#include <math.h>
double floor(double x)
Function
floor computes the largest integer less than or equal to x.
Return Value
floor returns the largest integer less than or equal to x, expressed as a
double floating value.
Example
x floor(x)
5.1 5.0
5.0 5.0
0.0 0.0
-5.0 -5.0
-5.1 -6.0
See Also
ceil
Notes
floor is packaged in the floating point library.
fmod
Description
Find double modulus
Syntax
#include <math.h>
double fmod(double x, double y)
Function
fmod computes the floating point remainder of x / y, to full double pre-
cision. The return value of f is determined using the formula:
f=x-i*y
where i is some integer, f is the same sign as x, and the absolute value
of f is less than the absolute value of y.
Return Value
fmod returns the value of f expressed as a double floating value. If y is
zero, fmod returns zero.
Example
x y fmod(x, y)
Notes
fmod is packaged in the floating point library.
frexp
Description
Extract fraction from exponent part
Syntax
#include <math.h>
double frexp(double val, int *exp)
Function
frexp partitions the double at val, which should be non-zero, into a frac-
tion in the interval [1/2, 1) times two raised to an integer power. It then
delivers the integer power to *exp, and returns the fractional portion as
the value of the function. The exponent is generally meaningless if val
is zero.
Return Value
frexp returns the power of two fraction of the double at val as the return
value of the function, and writes the exponent at *exp.
Example
To implement the sqrt(x) function:
double sqrt(double x)
{
extern double newton(double);
int n;
x = frexp(x, &n);
x = newton(x);
if (n & 1)
x *= SQRT2;
return (ldexp(x, n / 2));
}
See Also
ldexp
Notes
frexp is packaged in the floating point library.
getchar
Description
Get character from input stream
Syntax
#include <stdio.h>
int getchar(void)
Function
getchar obtains the next input character, if any, from the user supplied
input stream. This user must rewrite this function in C or in assembly
language to provide an interface to the input mechanism of the C
library.
Return Value
getchar returns the next character from the input stream. If end of file
(break) is encountered, or a read error occurs, getchar returns EOF.
Example
To copy characters from the input stream to the output stream:
See Also
putchar
Notes
getchar is packaged in the integer library, and is by default using the
first serial port SCI 1.
gets
Description
Get a text line from input stream
Syntax
#include <stdio.h>
char *gets(char *s)
Function
gets copies characters from the input stream to the buffer starting at s.
Characters are copied until a newline is reached or end of file is
reached. If a newline is reached, it is discarded and a NUL is written
immediately following the last character read into s.
Return Value
gets returns s if successful. If end of file is reached, gets returns NULL.
If a read error occurs, the array contents are indeterminate and gets
returns NULL.
Example
To copy input to output, line by line:
while (puts(gets(buf)))
;
See Also
puts
Notes
There is no assured limit on the size of the line read by gets.
imask
Description
Test the interrupt mask bit
Syntax
#include <processor.h>
@inline char imask(void)
Function
imask is an inline function allowing to test the interrupt mask bit. The
imask function can only be used in an if construct. This function
expands directly to a bms or bmc instruction.
Return Value
None.
Example
if (imask()) produces jrnm L3
++high; inc _high
L3:
Notes
imask is an inline function and then is not defined in any library. It is
therefore not possible to take its address. For more information, see
“Inline Function” in Chapter 3.
irq
Description
Test the interrupt line level
Syntax
#include <processor.h>
@inline char irq(void)
Function
irq is an inline function allowing to test the interrupt line level. The irq
function can only be used in an if construct. This function expands
directly to a bih or bil instruction.
Return Value
None.
Example
if (irq()) produces jril L3
++high; inc _high
L3:
Notes
irq is an inline function and then is not defined in any library. It is there-
fore not possible to take its address. For more information, see “Inline
Function” in Chapter 3.
isalnum
Description
Test for alphabetic or numeric character
Syntax
#include <ctype.h>
int isalnum(char c)
Function
isalnum tests whether c is an alphabetic character (either upper or
lower case), or a decimal digit.
Return Value
isalnum returns nonzero if the argument is an alphabetic or numeric
character; otherwise the value returned is zero.
Example
To test for a valid C identifier:
if (isalpha(*s) || *s == '_')
for (++s; isalnum(*s) || *s == '_'; ++s)
;
See Also
isalpha, isdigit, islower, isupper, isxdigit, tolower, toupper
Notes
If the argument is outside the range [-1, 255], the result is undefined.
isalpha
Description
Test for alphabetic character
Syntax
#include <ctype.h>
int isalpha(char c)
Function
isalpha tests whether c is an alphabetic character, either upper or lower
case.
Return Value
isalpha returns nonzero if the argument is an alphabetic character. Oth-
erwise the value returned is zero.
Example
To find the end points of an alphabetic string:
See Also
isalnum, isdigit, islower, isupper, isxdigit, tolower, toupper
Notes
If the argument is outside the range [-1, 255], the result is undefined.
iscntrl
Description
Test for control character
Syntax
#include <ctype.h>
int iscntrl(char c)
Function
iscntrl tests whether c is a delete character (0177 in ASCII), or an ordi-
nary control character (less than 040 in ASCII).
Return Value
iscntrl returns nonzero if c is a control character; otherwise the value is
zero.
Example
To map control characters to percent signs:
See Also
isgraph, isprint, ispunct, isspace
Notes
If the argument is outside the range [-1, 255], the result is undefined.
isdigit
Description
Test for digit
Syntax
#include <ctype.h>
int isdigit(char c)
Function
isdigit tests whether c is a decimal digit.
Return Value
isdigit returns nonzero if c is a decimal digit; otherwise the value
returned is zero.
Example
To convert a decimal digit string to a number:
See Also
isalnum, isalpha, islower, isupper, isxdigit, tolower, toupper
Notes
If the argument is outside the range [-1, 255], the result is undefined.
isgraph
Description
Test for graphic character
Syntax
#include <ctype.h>
int isgraph(char c)
Function
isgraph tests whether c is a graphic character; i.e. any printing charac-
ter except a space (040 in ASCII).
Return Value
isgraph returns nonzero if c is a graphic character. Otherwise the value
returned is zero.
Example
To output only graphic characters:
See Also
iscntrl, isprint, ispunct, isspace
Notes
If the argument is outside the range [-1, 255], the result is undefined.
islower
Description
Test for lowercase character
Syntax
#include <ctype.h>
int islower(char c)
Function
islower tests whether c is a lowercase alphabetic character.
Return Value
islower returns nonzero if c is a lowercase character; otherwise the
value returned is zero.
Example
To convert to uppercase:
if (islower(c))
c += 'A' - 'a'; /* also see toupper() */
See Also
isalnum, isalpha, isdigit, isupper, isxdigit, tolower, toupper
Notes
If the argument is outside the range [-1, 255], the result is undefined.
isprint
Description
Test for printing character
Syntax
#include <ctype.h>
int isprint(char c)
Function
isprint tests whether c is any printing character. Printing characters are
all characters between a space (040 in ASCII) and a tilde ‘~’ character
(0176 in ASCII).
Return Value
isprint returns nonzero if c is a printing character; otherwise the value
returned is zero.
Example
To output only printable characters:
See Also
iscntrl, isgraph, ispunct, isspace
Notes
If the argument is outside the range [-1, 255], the result is undefined.
ispunct
Description
Test for punctuation character
Syntax
#include <ctype.h>
int ispunct(char c)
Function
ispunct tests whether c is a punctuation character. Punctuation charac-
ters include any printing character except space, a digit, or a letter.
Return Value
ispunct returns nonzero if c is a punctuation character; otherwise the
value returned is zero.
Example
To collect all punctuation characters in a string into a buffer:
See Also
iscntrl, isgraph, isprint, isspace
Notes
If the argument is outside the range [-1, 255], the result is undefined.
isspace
Description
Test for whitespace character
Syntax
#include <ctype.h>
int isspace(char c)
Function
isspace tests whether c is a whitespace character. Whitespace charac-
ters are horizontal tab (‘\t’), newline (‘\n’), vertical tab (‘\v’), form feed
(‘\f’), carriage return (‘\r’), and space (‘ ’).
Return Value
isspace returns nonzero if c is a whitespace character; otherwise the
value returned is zero.
Example
To skip leading whitespace:
while (isspace(*s))
++s;
See Also
iscntrl, isgraph, isprint, ispunct
Notes
If the argument is outside the range [-1, 255], the result is undefined.
isupper
Description
Test for uppercase character
Syntax
int isupper(char c)
Function
isupper tests whether c is an uppercase alphabetic character.
Return Value
isupper returns nonzero if c is an uppercase character; otherwise the
value returned is zero.
Example
To convert to lowercase:
if (isupper(c))
c += 'a' - 'A'; /* also see tolower() */
See Also
isalnum, isalpha, isdigit, islower, isxdigit, tolower, toupper
Notes
If the argument is outside the range [-1, 255], the result is undefined.
isxdigit
Description
Test for hexadecimal digit
Syntax
#include <ctype.h>
int isxdigit(char c)
Function
isxdigit tests whether c is a hexadecimal digit, i.e. in the set
[0123456789abcdefABCDEF].
Return Value
isxdigit returns nonzero if c is a hexadecimal digit; otherwise the value
returned is zero.
Example
To accumulate a hexadecimal digit:
See Also
isalnum, isalpha, isdigit, islower, isupper, tolower, toupper
Notes
If the argument is outside the range [-1, 255], the result is undefined.
labs
Description
Find long absolute value
Syntax
#include <stdlib.h>
long labs(long l)
Function
labs obtains the absolute value of l. No check is made to see that the
result can be properly represented.
Return Value
labs returns the absolute value of l, expressed as an long int.
Example
To print out a debit or credit balance:
See Also
abs, fabs
Notes
labs is packaged in the integer library.
ldexp
Description
Scale double exponent
Syntax
#include <math.h>
double ldexp(double x, int exp)
Function
ldexp multiplies the double x by two raised to the integer power exp.
Return Value
ldexp returns the double result x * (1 << exp) expressed as a double
floating value. If a range error occurs, ldexp returns HUGE_VAL.
Example
x exp ldexp(x, exp)
1.0 1 2.0
1.0 0 1.0
1.0 -1 0.5
0.0 0 0.0
See Also
frexp, modf
Notes
ldexp is packaged in the floating point library.
ldiv
Description
Long divide with quotient and remainder
Syntax
#include <stdlib.h>
ldiv_t ldiv(long numer, long denom)
Function
ldiv divides the long integer numer by the long integer denom and
returns the quotient and the remainder in a structure of type ldiv_t. The
field quot contains the quotient and the field rem contains the remain-
der.
Return Value
ldiv returns a structure of type ldiv_t containing both quotient and
remainder.
Example
To get minutes and seconds from a delay in seconds:
ldiv_t result;
result = ldiv(time, 60L);
min = result.quo;
sec = result.rem;
See Also
div
Notes
ldiv is packaged in the integer library.
log
Description
Natural logarithm
Syntax
#include <math.h>
double log(double x)
Function
log computes the natural logarithm of x to full double precision.
Return Value
log returns the closest internal representation to log(x), expressed as a
double floating value. If the input argument is less than zero, or is too
large to be represented, log returns zero.
Example
To compute the hyperbolic arccosine of x:
See Also
exp
Notes
log is packaged in the floating point library.
log10
Description
Common logarithm
Syntax
#include <math.h>
double log10(double x)
Function
log10 computes the common log of x to full double precision by com-
puting the natural log of x divided by the natural log of 10. If the input
argument is less than zero, a domain error will occur. If the input argu-
ment is zero, a range error will occur.
Return Value
log10 returns the nearest internal representation to log10 x, expressed
as a double floating value. If the input argument is less than or equal to
zero, log10 returns zero.
Example
To determine the number of digits in x, where x is a positive integer
expressed as a double:
ndig = log10(x) + 1;
See Also
log
Notes
log10 is packaged in the floating point library.
max
Description
Test for maximum
Syntax
#include <stdlib.h>
max(a,b)
Function
max obtains the maximum of its two arguments, a and b. Since max is
implemented as a C preprocessor macro, its arguments can be any
numerical type, and type coercion occurs automatically.
Return Value
max is a numerical rvalue of the form ((a < b) ? b : a), suitably paren-
thesized.
Example
To set a new maximum level:
See Also
min
Notes
max is an extension to the proposed ANSI C standard.
max is a macro declared in the <stdlib.h> header file. You can use it by
including <stdlib.h> with your program. Because it is a macro, max
cannot be called from non-C programs, nor can its address be taken.
Arguments with side effects may be evaluated other than once.
memchr
Description
Scan buffer for character
Syntax
#include <string.h>
void *memchr(void *s, char c, unsigned char n)
Function
memchr looks for the first occurrence of a specific character c in an n
character buffer starting at s.
Return Value
memchr returns a pointer to the first character that matches c, or NULL
if no character matches.
Example
To map keybuf[] characters into subst[] characters:
See Also
strchr, strcspn, strpbrk, strrchr, strspn
Notes
memchr is packaged in the integer library.
memcmp
Description
Compare two buffers for lexical order
Syntax
#include <string.h>
int memcmp(void *s1, void *s2, unsigned char n)
Function
memcmp compares two text buffers, character by character, for lexical
order in the character collating sequence. The first buffer starts at s1,
the second at s2; both buffers are n characters long.
Return Value
memcmp returns a short integer greater than, equal to, or less than zero,
according to whether s1 is lexicographically greater than, equal to, or
less than s2.
Example
To look for the string “include” in name:
if (memcmp(name, “include”, 7) == 0)
doinclude();
See Also
strcmp, strncmp
Notes
memcmp is packaged in the integer library.
memcpy
Description
Copy one buffer to another
Syntax
#include <string.h>
void *memcpy(void *s1, void *s2, unsigned char n)
Function
memcpy copies the first n characters starting at location s2 into the
buffer beginning at s1.
Return Value
memcpy returns s1.
Example
To place “first string, second string” in buf[]:
See Also
strcpy, strncpy
Notes
memcpy is packaged in the integer library and may be implemented as
an inline function.
memmove
Description
Copy one buffer to another
Syntax
#include <string.h>
void *memmove(void *s1, void *s2, unsigned char n)
Function
memmove copies the first n characters starting at location s2 into the
buffer beginning at s1. If the two buffers overlap, the function performs
the copy in the appropriate sequence, so the copy is not corrupted.
Return Value
memmove returns s1.
Example
To shift an array of characters:
See Also
memcpy
Notes
memmove is packaged in the integer library.
memset
Description
Propagate fill character throughout buffer
Syntax
#include <string.h>
void *memset(void *s, char c, unsigned char n)
Function
memset floods the n character buffer starting at s with fill character c.
Return Value
memset returns s.
Example
To flood a 512-byte buffer with NULs:
memset(buf,'\0', BUFSIZ);
Notes
memset is packaged in the integer library and may be implemented as
an inline function.
min
Description
Test for minimum
Syntax
#include <stdlib.h>
min(a, b)
Function
min obtains the minimum of its two arguments, a and b. Since min is
implemented as a C preprocessor macro, its arguments can be any
numerical type, and type coercion occurs automatically.
Return Value
min is a numerical rvalue of the form ((a < b) ? a : b), suitably paren-
thesized.
Example
To set a new minimum level:
See Also
max
Notes
min is an extension to the ANSI C standard.
min is a macro declared in the <stdlib.h> header file. You can use it by
including <stdlib.h> with your program. Because it is a macro, min
cannot be called from non-C programs, nor can its address be taken.
Arguments with side effects may be evaluated more than once.
modf
Description
Extract fraction and integer from double
Syntax
#include <math.h>
double modf(double val, double *pd)
Function
modf partitions the double val into an integer portion, which is deliv-
ered to *pd, and a fractional portion, which is returned as the value of
the function. If the integer portion cannot be represented properly in an
int, the result is truncated on the left without complaint.
Return Value
modf returns the signed fractional portion of val as a double floating
value, and writes the integer portion at *pd.
Example
val *pd modf(val, *pd)
5.1 5 0.1
5.0 5 0.0
4.9 4 0.9
0.0 0 0.0
-1.4 -1 -0.4
See Also
frexp, ldexp
Notes
modf is packaged in the floating point library.
pow
Description
Raise x to the y power
Syntax
#include <math.h>
double pow(double x, double y)
Function
pow computes the value of x raised to the power of y.
Return Value
pow returns the value of x raised to the power of y, expressed as a dou-
ble floating value. If x is zero and y is less than or equal to zero, or if x
is negative and y is not an integer, pow returns zero.
Example
x y pow(x, y)
See Also
exp
Notes
pow is packaged in the floating point library.
printf
Description
Output formatted arguments to stdout
Syntax
#include <stdio.h>
int printf(@near char *fmt, ...)
Function
printf writes formatted output to the output stream using the format
string at fmt and the arguments specified by ..., as described below.
Format Specifiers
The format string at fmt consists of literal text to be output, interspersed
with conversion specifications that determine how the arguments are to
be interpreted and how they are to be converted for output. If there are
insufficient arguments for the format, the results are undefined. If the
format is exhausted while arguments remain, the excess arguments are
evaluated but otherwise ignored. printf returns when the end of the for-
mat string is encountered.
If the character after '%' is not a valid conversion character, the behav-
ior is undefined.
Return Value
printf returns the number of characters transmitted, or a negative
number if a write error occurs.
Notes
A call with more conversion specifiers than argument variables will
cause unpredictable results.
Example
To print arg, which is a double with the value 5100.53:
printf(“%8.2f\n”, arg);
printf(“%*.*f\n”, 8, 2, arg);
See Also
sprintf
Notes
printf is packaged in both the integer library and the floating point
library. The functionality of the integer only version of printf is a subset
of the functionality of the floating point version. The integer only ver-
sion cannot print or manipulate floating point numbers. If your pro-
grams call the integer only version of printf, the following conversion
specifiers are invalid: e, E, f, g and G. The L modifier is also invalid.
putchar
Description
Put a character to output stream
Syntax
#include <stdio.h>
int putchar(char c)
Function
putchar copies c to the user specified output stream.
Return Value
putchar returns c. If a write error occurs, putchar returns EOF.
Example
To copy input to output:
See Also
getchar
Notes
putchar is packaged in the integer library, and is by default using the
first serial port SCI 1.
puts
Description
Put a text line to output stream
Syntax
#include <stdio.h>
int puts(char *s)
Function
puts copies characters from the buffer starting at s to the output stream
and appends a newline character to the output stream.
puts uses putchar to output each character. The terminating NUL is not
copied.
Return Value
puts returns zero if successful, or else nonzero if a write error occurs.
Example
To copy input to output, line by line:
while (puts(gets(buf)))
;
See Also
gets
Notes
puts is packaged in the integer library.
rand
Description
Generate pseudo-random number
Syntax
#include <stdlib.h>
int rand(void)
Function
rand computes successive pseudo-random integers in the range
[0, 32767], using a linear multiplicative algorithm which has a period of
2 raised to the power of 32.
Example
int dice()
{
return (rand() % 6 + 1);
}
Return Value
rand returns a pseudo-random integer.
See Also
srand
Notes
rand is packaged in the integer library.
sin
Description
Sin
Syntax
#include <math.h>
double sin(double x)
Function
sin computes the sine of x, expressed in radians, to full double preci-
sion. If the magnitude of x is too large to contain a fractional quadrant
part, the value of sin is 0.
Return Value
sin returns the closest internal representation to sin(x) in the range
[-pi/2, pi/2], expressed as a double floating value. A large argument
may return a meaningless result.
Example
To rotate a vector through the angle theta:
See Also
cos, tan
Notes
sin is packaged in the floating point library.
sinh
Description
Hyperbolic sine
Syntax
#include <math.h>
double sinh(double x)
Function
sinh computes the hyperbolic sine of x to full double precision.
Return Value
sinh returns the closest internal representation to sinh(x), expressed as a
double floating value. If the result is too large to be properly repre-
sented, sinh returns zero.
Example
To obtain the hyperbolic sine of complex z:
typedef struct
{
double x, iy;
}complex;
complex z;
See Also
cosh, exp, tanh
Notes
sinh is packaged in the floating point library.
sprintf
Description
Output arguments formatted to buffer
Syntax
#include <stdio.h>
int sprintf(char *s, @near char fmt, ...)
Function
sprintf writes formatted to the buffer pointed at by s using the format
string at fmt and the arguments specified by ..., in exactly the same way
as printf. See the description of the printf function for information on
the format conversion specifiers. A NUL character is written after the
last character in the buffer.
Return Value
sprintf returns the numbers of characters written, not including the ter-
minating NUL character.
Example
To format a double at d into buf:
See Also
printf
Notes
sprintf is packaged in both the integer library and the floating point
library. The functionality of the integer only version of sprintf is a sub-
set of the functionality of the floating point version. The integer only
version cannot print or manipulate floating point numbers. If your pro-
grams call the integer only version of sprintf, the following conversion
specifiers are invalid: e, E, f, g and G. The L flag is also invalid.
sqrt
Description
Real square root
Syntax
#include <math.h>
double sqrt(double x)
Function
sqrt computes the square root of x to full double precision.
Return Value
sqrt returns the nearest internal representation to sqrt(x), expressed as a
double floating value. If x is negative, sqrt returns zero.
Example
To use sqrt to check whether n > 2 is a prime number:
Notes
sqrt is packaged in the floating point library.
srand
Description
Seed pseudo-random number generator
Syntax
#include <stdlib.h>
void srand(unsigned char nseed)
Function
srand uses nseed as a seed for a new sequence of pseudo-random num-
bers to be returned by subsequent calls to rand. If srand is called with
the same seed value, the sequence of pseudo-random numbers will be
repeated. The initial seed value used by rand and srand is 1.
Return Value
Nothing.
Example
To set up a new sequence of random numbers:
srand(103);
See Also
rand
Notes
srand is packaged in the integer library.
strcat
Description
Concatenate strings
Syntax
#include <string.h>
char *strcat(char *s1, char *s2)
Function
strcat appends a copy of the NUL terminated string at s2 to the end of
the NUL terminated string at s1. The first character of s2 overlaps the
NUL at the end of s1. A terminating NUL is always appended to s1.
Return Value
strcat returns s1.
Example
To place the strings “first string, second string” in buf[]:
buf[0] = '\0';
strcpy(buf, “first string”);
strcat(buf, “, second string”);
See Also
strncat
Notes
There is no way to specify the size of the destination area to prevent
storage overwrites.
strchr
Description
Scan string for first occurrence of character
Syntax
#include <string.h>
char *strchr(char *s1, char c)
Function
strchr looks for the first occurrence of a specific character c in a NUL
terminated target string s.
Return Value
strchr returns a pointer to the first character that matches c, or NULL if
none does.
Example
To map keystr[] characters into subst[] characters:
if (t = strchr(keystr, *s))
*s = subst[t - keystr];
See Also
memchr, strcspn, strpbrk, strrchr, strspn
Notes
strchr is packaged in the integer library.
strcmp
Description
Compare two strings for lexical order
Syntax
#include <string.h>
int strcmp(char *s1, char *s2)
Function
strcmp compares two text strings, character by character, for lexical
order in the character collating sequence. The first string starts at s1, the
second at s2. The strings must match, including their terminating NUL
characters, in order for them to be equal.
Return Value
strcmp returns an integer greater than, equal to, or less than zero,
according to whether s1 is lexicographically greater than, equal to, or
less than s2.
Example
To look for the string “include”:
if (strcmp(buf, “include”) == 0)
doinclude();
See Also
memcmp, strncmp
Notes
strcmp is packaged in the integer library.
strcpy
Description
Copy one string to another
Syntax
#include <string.h>
char *strcpy(char *s1, char *s2)
Function
strcpy copies the NUL terminated string at s2 to the buffer pointed at
by s1. The terminating NUL is also copied.
Return Value
strcpy returns s1.
Example
To make a copy of the string s2 in dest:
strcpy(dest, s2);
See Also
memcpy, strncpy
Notes
There is no way to specify the size of the destination area, to prevent
storage overwrites.
strcspn
Description
Find the end of a span of characters in a set
Syntax
#include <string.h>
unsigned int strcspn(char *s1, char *s2)
Function
strcspn scans the string starting at s1 for the first occurrence of a char-
acter in the string starting at s2. It computes a subscript i such that:
Return Value
strcspn returns the lowest possible value of i. s1[i] designates the termi-
nating null character if none of the characters in s1 are in s2.
Example
To find the start of a decimal constant in a text string:
See Also
memchr, strchr, strpbrk, strrchr, strspn
Notes
strcspn is packaged in the integer library.
strlen
Description
Find length of a string
Syntax
#include <string.h>
unsigned int strlen(char *s)
Function
strlen scans the text string starting at s to determine the number of char-
acters before the terminating NUL.
Return Value
The value returned is the number of characters in the string before the
NUL.
Notes
strlen is packaged in the integer library and may be implemented as an
inline function.
strncat
Description
Concatenate strings of length n
Syntax
#include <string.h>
char *strncat(char *s1, char *s2, unsigned char n)
Function
strncat appends a copy of the NUL terminated string at s2 to the end of
the NUL terminated string at s1. The first character of s2 overlaps the
NUL at the end of s1. n specifies the maximum number of characters to
be copied, unless the terminating NUL in s2 is encountered first. A ter-
minating NUL is always appended to s1.
Return Value
strncat returns s1.
Example
To concatenate the strings “day” and “light”:
strcpy(s, “day”);
strncat(s + 3, “light”, 5);
See Also
strcat
Notes
strncat is packaged in the integer library.
strncmp
Description
Compare two n length strings for lexical order
Syntax
#include <string.h>
int strncmp(char *s1, char *s2, unsigned char n)
Function
strncmp compares two text strings, character by character, for lexical
order in the character collating sequence. The first string starts at s1, the
second at s2. n specifies the maximum number of characters to be com-
pared, unless the terminating NUL in s1 or s2 is encountered first. The
strings must match, including their terminating NUL character, in order
for them to be equal.
Return Value
strncmp returns an integer greater than, equal to, or less than zero,
according to whether s1 is lexicographically greater than, equal to, or
less than s2.
Example
To check for a particular error message:
if (strncmp(errmsg,
“can't write output file”, 23) == 0)
cleanup(errmsg);
See Also
memcmp, strcmp
Notes
strncmp is packaged in the integer library.
strncpy
Description
Copy n length string
Syntax
#include <string.h>
char *strncpy(char *s1, char *s2, unsigned char n)
Function
strncpy copies the first n characters starting at location s2 into the
buffer beginning at s1. n specifies the maximum number of characters
to be copied, unless the terminating NUL in s2 is encountered first. In
that case, additional NUL padding is appended to s2 to copy a total of n
characters.
Return Value
strncpy returns s1.
Example
To make a copy of the string s2 in dest:
See Also
memcpy, strcpy
Notes
If the string s2 points at is longer than n characters, the result may not
be NUL-terminated.
strpbrk
Description
Find occurrence in string of character in set
Syntax
#include <string.h>
char *strpbrk(char *s1, char *s2)
Function
strpbrk scans the NUL terminated string starting at s1 for the first
occurrence of a character in the NUL terminated set s2.
Return Value
strpbrk returns a pointer to the first character in s1 that is also contained
in the set s2, or a NULL if none does.
Example
To replace unprintable characters (as for a 64 character terminal):
See Also
memchr, strchr, strcspn, strrchr, strspn
Notes
strpbrk is packaged in the integer library.
strrchr
Description
Scan string for last occurrence of character
Syntax
#include <string.h>
char *strrchr(char *s, char c)
Function
strrchr looks for the last occurrence of a specific character c in a NUL
terminated string starting at s.
Return Value
strrchr returns a pointer to the last character that matches c, or NULL if
none does.
Example
To find a filename within a directory pathname:
if (s = strrchr(“/usr/lib/libc.user”, '/')
++s;
See Also
memchr, strchr, strpbrk, strcspn, strspn
Notes
strrchr is packaged in the integer library.
strspn
Description
Find the end of a span of characters not in set
Syntax
#include <string.h>
unsigned int strspn(char *s1, char *s2)
Function
strspn scans the string starting at s1 for the first occurrence of a charac-
ter not in the string starting at s2. It computes a subscript i such that
Return Value
strspn returns the lowest possible value of i. s1[i] designates the termi-
nating null character if all of the characters in s1 are in s2.
Example
To check a string for characters other than decimal digits:
if (str[strspn(str, “0123456789”)])
printf(“invalid number\n”);
See Also
memchr, strcspn, strchr, strpbrk, strrchr
Notes
strspn is packaged in the integer library.
strstr
Description
Scan string for first occurrence of string
Syntax
#include <string.h>
char *strstr(char *s1, char *s2)
Function
strstr looks for the first occurrence of a specific string s2 not including
its terminating NUL, in a NUL terminated target string s1.
Return Value
strstr returns a pointer to the first character that matches c, or NULL if
none does.
Example
To look for a keyword in a string:
if (t = strstr(buf, “LIST”))
do_list(t);
See Also
memchr, strcspn, strpbrk, strrchr, strspn
Notes
strstr is packaged in the integer library.
strtod
Description
Convert buffer to double
Syntax
#include <stdlib.h>
double strtod(char *nptr, char **endptr)
Function
strtod converts the string at nptr into a double. The string is taken as
the text representation of a decimal number, with an optional fraction
and exponent. Leading whitespace is skipped and an optional sign is
permitted; conversion stops on the first unrecognizable character.
Acceptable inputs match the pattern:
[+|-]d*[.d*][e[+|-]dd*]
where d is any decimal digit and e is the character ‘e’ or ‘E’. If endptr is
not a null pointer, *endptr is set to the address of the first unconverted
character remaining in the string nptr. No checks are made against over-
flow, underflow, or invalid character strings.
Return Value
strtod returns the converted double value. If the string has no recogniz-
able characters, it returns zero.
Example
To read a string from STDIN and convert it to a double at d:
gets(buf);
d = strtod(buf, NULL);
See Also
atoi, atol, strtol, strtoul
Notes
strtod is packaged in the floating point library.
strtol
Description
Convert buffer to long
Syntax
#include <stdlib.h>
long strtol(char *nptr, char **endptr, char base)
Function
strtol converts the string at nptr into a long integer. Leading whitespace
is skipped and an optional sign is permitted; conversion stops on the
first unrecognizable character. If base is not zero, characters a-z or A-Z
represents digits in range 10-36. If base is zero, a leading “0x” or “0X”
in the string indicates hexadecimal, a leading “0” indicates octal, other-
wise the string is take as a decimal representation. If base is 16 and a
leading “0x” or “0X” is present, it is skipped before to convert. If
endptr is not a null pointer, *endptr is set to the address of the first
unconverted character in the string nptr.
Return Value
strtol returns the converted long integer. If the string has no recogniza-
ble characters, zero is returned.
Example
To read a string from STDIN and convert it to a long l:
gets(buf);
l = strtol(buf, NULL, 0);
See Also
atof, atoi, strtoul, strtod
Notes
strtol is packaged in the integer library.
strtoul
Description
Convert buffer to unsigned long
Syntax
#include <stdlib.h>
unsigned long strtoul(char *nptr, char **endptr,
char base)
Function
strtoul converts the string at nptr into a long integer. Leading
whitespace is skipped and an optional sign is permitted; conversion
stops on the first unrecognizable character. If base is not zero, charac-
ters a-z or A-Z represents digits in range 10-36. If base is zero, a lead-
ing “0x” or “0X” in the string indicates hexadecimal, a leading “0”
indicates octal, otherwise the string is take as a decimal representation.
If base is 16 and a leading “0x” or “0X” is present, it is skipped before
to convert. If endptr is not a null pointer, *endptr is set to the address of
the first unconverted character in the string nptr.
Return Value
strtoul returns the converted long integer. If the string has no recogniza-
ble characters, zero is returned.
Example
To read a string from STDIN and convert it to a long l:
gets(buf);
l = strtoul(buf, NULL, 0);
See Also
atof, atoi, strtol, strtod
Notes
strtoul is a macro redefined to strtol.
tan
Description
Tangent
Syntax
#include <math.h>
double tan(double x)
Function
tan computes the tangent of x, expressed in radians, to full double pre-
cision.
Return Value
tan returns the nearest internal representation to tan(x), in the range
[-pi/2, pi/2], expressed as a double floating value. If the number in x is
too large to be represented, tan returns zero. An argument with a large
size may return a meaningless value, i.e. when x/(2 * pi) has no fraction
bits.
Example
To compute the tangent of theta:
y = tan(theta);
See Also
cos, sin
Notes
tan is packaged in the floating point library.
tanh
Description
Hyperbolic tangent
Syntax
#include <math.h>
double tanh(double x)
Function
tanh computes the value of the hyperbolic tangent of x to double preci-
sion.
Return Value
tanh returns the nearest internal representation to tanh(x), expressed as
a double floating value. If the result is too large to be properly repre-
sented, tanh returns zero.
Example
To compute the hyperbolic tangent of x:
y = tanh(x);
See Also
cosh, exp, sinh
Notes
tanh is packaged in the floating point library.
tolower
Description
Convert character to lowercase if necessary
Syntax
#include <ctype.h>
int tolower(char c)
Function
tolower converts an uppercase letter to its lowercase equivalent, leav-
ing all other characters unmodified.
Return Value
tolower returns the corresponding lowercase letter, or the unchanged
character.
Example
To accumulate a hexadecimal digit:
See Also
toupper
Notes
tolower is packaged in the integer library.
toupper
Description
Convert character to uppercase if necessary
Syntax
#include <ctype.h>
int toupper(char c)
Function
toupper converts a lowercase letter to its uppercase equivalent, leaving
all other characters unmodified.
Return Value
toupper returns the corresponding uppercase letter, or the unchanged
character.
Example
To convert a character string to uppercase letters:
See Also
tolower
Notes
toupper is packaged in the integer library.
• Invoking castm8
• Object File
• Listings
• Branch Optimization
• Old Syntax
• C Style Directives
• Assembler Directives
Invoking castm8
castm8 accepts the following command line options, each of which is
described in detail below:
-o* write object code to the file *. If no file name is specified, the
output file name is derived from the input file name, by
replacing the rightmost extension in the input file name with
the character ‘o’. For example, if the input file name is
prog.s, the default output file name is prog.o.
-pe mark all symbols defined by an equ directive as public.
This option has the same effect than adding a xdef directive
for each of those symbols.
-pl put locals in the symbol table. They are not published as
externals and will be only displayed in the linker map file.
-p mark all defined symbols as public. This option has the
same effect than adding a xdef directive for each label.
-si suppress the .info. section produced automatically and
containing the object name, date and assembler options.
-u produce an error message in the listing file for all occur-
rence of an undefined symbol. This option enforces the -l
option.
-v display the name of each file which is processed.
Object File
The object file produced by the assembler is a relocatable object in a
format suitable for the linker clnk. This will normally consist of
machine code, initialized data and relocation information. The object
file also contains information about the sections used, a symbol table,
and a debug symbol table.
The object file contains by default a special section named .info. con-
taining text strings. The assembler produces the object name followed
by the current date and time, and the assembler name followed by the
specified options. The other compiler passes will complete this infor-
mation to add their own name and options. This section can be sup-
pressed for compatibility reason by using the -si option.
Listings
The listing stream contains the source code used as input to the assem-
bler, together with the hexadecimal representation of the corresponding
object code and the address for which it was generated. The contents of
the listing stream depends on the occurrence of the list, nolist, clist,
dlist and mlist directives in the source. The format of the output is as
follows:
Addresses in the listing output are the offsets from the start of the cur-
rent section. After the linker has been executed, the listing files may be
updated to contain absolute information by the clabs utility. Addresses
and code will be updated to reflect the actual values as built by the
linker.
where ‘:’ indicates the end of a label and ‘;’ defines the start of a com-
ment. The end of a line terminates a comment. The command field may
be an instruction, a directive or a macro call.
A source file must end with the end directive. All the following lines
will be ignored by the assembler. If an end directive is found in an
included file, it stops only the process for the included file.
Instructions
castm8 recognizes the following instructions:
rcf ; implicit
push y ; register
ld a,#1 ; immediate
and a,var ; short, long
ld a,(2,x) ; indexed
ld a,[var] ; indirect
ld a,([var.w],y) ; indirect indexed long
jrne loop ; relative
bset 2,#1 ; bit number
btjt 2,#1,loop ; bit test and branch
Labels
A source line may begin with a label. Some directives require a label on
the same line, otherwise this field is optional. A label must begin with
wait: macro
\@loop:btjf PORTA,#1,\@loop
endm
Temporary Labels
The assembler allows temporary labels to be defined when there is no
need to give them an explicit name. Such a label is composed by a dec-
imal number immediately followed by a ‘$’ character. Such a label is
valid until the next standard label or the local directive. Then the same
temporary label may be redefined without getting a multiply defined
error message.
1$: dec
jrne 1$
2$: dec
jrne 2$
Temporary labels do not appear in the symbol table or the cross refer-
ence list.
For example, to define 3 different local blocks and create and use 3 dif-
ferent local labels named 10$:
function1:
10$: ld a,var
jreq 10$
ld a,var2
local
10$: ld a,var2
jreq 10$
ld a,var
ret
function2:
10$: ld a,var2
sub a,var
jrne 10$
ret
Constants
The assembler accepts numeric constants and string constants.
Numeric constants are expressed in different bases depending on a
prefix character as follows:
Number Base
10 decimal (no prefix)
%1010 binary
@12 octal
$1F or 0x1F or 0X1F hexadecimal
Suffix Base
D, d or none decimal (no prefix)
B or b binary
Q or q octal
0AH or 0Ah hexadecimal
‘This is a string’
“This is also a string”
Expressions
An expression consists of a number of labels and constants connected
together by operators. Expressions are evaluated to 32-bit precision.
Note that operators have the same precedence than in the C language.
+ addition
- subtraction (negation)
* multiplication
/ division
% remainder (modulus)
& bitwise and
| bitwise or
^ bitwise exclusive or
~ bitwise complement
<< left shift
>> right shift
== equality
!= difference
< less than
<= less than or equal
> greater than
>= greater than or equal
&& logical and
|| logical or
! logical complement
label + constant
label - constant
label1 - label2
NOTE
The difference of two relocatable labels is valid only if both symbols are
not external symbols, and are defined in the same section.
Macro Instructions
A macro instruction is a list of assembler commands collected under a
unique name. This name becomes a new command for the following of
the program. A macro begins with a macro directive and ends with a
endm directive. All the lines between these two directives are recorded
and associated with the macro name specified with the macro directive.
This macro is named signex and contains the code needed to perform a
sign extension of a into x. Whenever needed, this macro can be
expanded just by using its name in place of a standard instruction:
The resulting code will be the same as if the following code had been
written:
And called:
name>[.<ext>] [<arguments>]
table: macro
dc.\0 1,2,3,4
endm
table.b
dc.b 1,2,3,4
table.w
dc.w 1,2,3,4
The directive mexit may be used at any time to stop the macro expan-
sion. It is generally used in conjunction with a conditional directive.
A macro call may be used within another macro definition, all macros
must then be defined before their first call. A macro definition cannot
contain another macro definition.
Conditional Directives
A conditional directive allows parts of the program to be assembled or
not depending on a specific condition expressed in an if directive. The
condition is an expression following the if command. The expression
cannot be relocatable, and shall evaluate to a numeric result. If the con-
dition is false (expression evaluated to zero), the lines following the if
directive are skipped until an endif or else directive. Otherwise, the
lines are normally assembled. If an else directive is encountered, the
condition status is reversed, and the conditional process continues until
the next endif directive.
if debug == 1
ld x,#message
call print
endif
If the symbol debug is equal to 1, the next two lines are assembled.
Otherwise they are skipped.
If the symbol offset is not one, the macro addptr is expanded with off-
set as argument, otherwise the aix instruction is directly assembled.
Sections
The assembler allows code and data to be splitted in sections. A section
is a set of code or data referenced by a section name, and providing a
contiguous block of relocatable information. A section is defined with a
section directive, which creates a new section and redirects the follow-
ing code and data thereto. The directive switch can be used to redirect
the following code and data to another section.
Section Description
.text executable code
.data initialized data
.bss uninitialized data
.bsct initialized data in short range
.ubsct non initialized data in short rang-
eshort range
The sections .bsct and .ubsct are used for locating data in the short
range of the processor. The short range is defined as the memory
addresses between 0x00 and 0xFF inclusive, i.e. the memory directly
addressable by a single byte. Several processors include special instruc-
tions and/or addressing modes that take advantage of this special
address range. The Cosmic assembler will automatically use the most
efficient addressing mode if the data objects are allocated in the .bsct,
.ubsct or a section with the same attributes. If short range data objects
are defined in another file then the directive xref.b must be used to
externally reference the data object. This directive specifies that the
address for these data object is only one byte and therefore the assem-
bler may use 8 bit addressing modes.
switch .bsct
zvar2: ds.b 1
switch .bss
var2: ds.b 1
switch .text
ld a,var
ld a,zvar
ld a,var2
ld a,var2
end
Bit Handling
The assembler allows symbols specifying bit addresses instead of byte
addresses. A bit address is obtained from a byte address and a bit
number by or’ing the bit number with the byte address 3-bit shifted to
the left. Such symbol can be defined either by an equate definition or as
member of a bit section. Such a section can be defined by using the sec-
tion directive with the bit attribute. In a bit section, any directive creat-
ing or reserving bytes can be used, but will create or reserve bits. Bit
symbols can be directly used by the bit instructions with a shortened
syntax, as a bit symbol is defining both a byte and a bit in this byte. Bit
symbols can be declared as external by using the xbit directive. Exter-
nal definitions for bit symbols located in the short range will used the
xbit.b directive.
Bit sections are located at link time either at specified bit addresses or
attached to any short range section. The linker is computing the proper
addresses when hooking bit sections to byte sections, or byte sections to
bit sections.
Includes
The include directive specifies a file to be included and assembled in
place of the include directive. The file name is written between double
quotes, and may be any character string describing a file on the host
system. If the file cannot be found using the given name, it is searched
from all the include paths defined by the -i options on the command
line, and from the paths defined by the environment symbol CXLIB, if
such a symbol has been defined before the assembler invocation. This
symbol may contain several paths separated by the usual path separator
of the host operating system (‘;’ for MSDOS and ‘:’ for UNIX).
The -h option can specify a file to be “included”. The file specified will
be included as if the program had an include directive at its very top.
The specified file will be included before any source file specified on
the command line.
Branch Optimization
Branch instructions are by default automatically optimized to produce
the shortest code possible. This behaviour may be disabled by the -b
option. This optimization operates on conditional branches, on jumps
and jumps to subroutine.
Old Syntax
The -m option allows the assembler to accept old constructs which are
now obsolete. The following features are added to the standard behav-
iour:
• a label starting in the first column does not need to be ended with
a ‘:’ character;
The comment separator at the end of an instruction is still the ‘;’ charac-
ter because the ‘*’ character is interpreted as the multiply operator.
C Style Directives
The assembler also supports C style directives matching the preproces-
sor directives of a C compiler. The following directives list shows the
equivalence with the standard directives:
NOTE
The #define directive does not implement all the text replacement fea-
tures provided by a C compiler. It can be used only to define a symbol
equal to a numerical value.
Assembler Directives
This section consists of quick reference descriptions for each of the
castm8 assembler directives.
align
Description
Align the next instruction on a given boundary
Syntax
align <expression>,[<fill_value>]
Function
The align directive forces the next instruction to start on a specific
boundary. The align directive is followed by a constant expression
which must be positive. The next instruction will start at the next
address which is a multiple of the specified value. If bytes are added in
the section, they are set to the value of the filling byte defined by the -f
option. If <fill_value> is specified, it will be used locally as the filling
byte, instead of the one specified by the -f option.
Example
align 3 ; next address is multiple of 3
ds.b 1
See Also
even
base
Description
Define the default base for numerical constants
Syntax
base <expression>
Function
The base directive sets the default base for numerical constants begin-
ning with a digit. The base directive is followed by a constant expres-
sion which value must be one of 2, 8, 10 or 16. The decimal base is used
by default. When another base is selected, it is no more possible to enter
decimal constants.
Example
base 8 ; select octal base
ld a,#377 ; load $FF
bsct
Description
Switch to the predefined .bsct section.
Syntax
bsct
Function
The bsct directive switches input to a section named .bsct, also known
as the short range section. The assembler will automatically select the
short addressing mode when referencing an object defined in the .bsct
section.
Example
bsct
c_x:
ds.b 1
Notes
The .bsct section is limited to 256 bytes, but the assembler does not
check the .bsct section size. This will be done by the linker.
See Also
section, switch
clist
Description
Turn listing of conditionally excluded code on or off.
Syntax
clist [on|off]
Function
The clist directive controls the output in the listing file of conditionally
excluded code. It is effective if and only if listings are requested; it is
ignored otherwise.
The parts of the program to be listed are the program lines which are not
assembled as a consequence of if, else and endif directives.
See Also
if, else, endif
dc
Description
Allocate constant(s)
Syntax
dc[.size] <expression>[,<expression>...]
Function
The dc directive allocates and initializes storage for constants. If
<expression> is a string constant, one byte is allocated for each charac-
ter of the string. Initialization can be specified for each item by giving a
series of values separated by commas or by using a repeat count.
The dc and dc.b directives will allocate one byte per <expression>.
The dc.l directive will allocate one long word per <expression>.
Example
digit: dc.b 10,'0123456789'
dc.w digit
Note
For compatibility with previous assemblers, the directive fcb is alias to
dc.b, and the directive fdb is alias to dc.w.
dcb
Description
Allocate constant block
Syntax
dcb.<size> <count>,<value>
Function
The dcb directive allocates a memory block and initializes storage for
constants. The size area is the number of the specified value <count> of
<size>. The memory area can be initialized with the <value> specified.
The dcb and dcb.b directives will allocate one byte per <count>.
The dcb.l directive will allocate one long word per <count>.
Example
digit: dcb.b 10,5 ; allocate 10 bytes,
; all initialized to 5
dlist
Description
Turn listing of debug directives on or off.
Syntax
dlist [on|off]
Function
The dlist directive controls the visibility of any debug directives in the
listing. It is effective if and only if listings are requested; it is ignored
otherwise.
ds
Description
Allocate variable(s)
Syntax
ds[.size] <space>
Function
The ds directive allocates storage space for variables. <space> must be
an absolute expression. Bytes created are set to the value of the filling
byte defined by the -f option.
Example
ptlec: ds.b 2
ptecr: ds.b 2
chrbuf: ds.w 128
Note
For compatibility with previous assemblers, the directive rmb is alias
to ds.b.
else
Description
Conditional assembly
Syntax
if <expression>
instructions
else
instructions
endc
Function
The else directive follows an if directive to define an alternative condi-
tional sequence. It reverts the condition status for the following instruc-
tions up to the next matching endif directive. An else directive applies
to the closest previous if directive.
Example
if offset != 1 ; if offset too large
addptr offset ; call a macro
else ; otherwise
inc x ; increment X register
endif
Note
The else and elsec directives are equivalent and may used without dis-
tinction. They are provided for compatibility with previous assemblers.
See Also
if, endif, clist
elsec
Description
Conditional assembly
Syntax
if <expression>
instructions
elsec
instructions
endc
Function
The elsec directive follows an if directive to define an alternative condi-
tional sequence. It reverts the condition status for the following instruc-
tions up to the next matching endc directive. An elsec directive applies
to the closest previous if directive.
Example
ifge offset-127 ; if offset too large
addptr offset ; call a macro
elsec ; otherwise
inc x ; increment X register
endc
Note
The elsec and else directives are equivalent and may used without dis-
tinction. They are provided for compatibility with previous assemblers.
See Also
if, endc, clist, else
end
Description
Stop the assembly
Syntax
end
Function
The end directive stops the assembly process. Any statements follow-
ing it are ignored. If the end directive is encountered in an included file,
it will stop the assembly process for the included file only.
endc
Description
End conditional assembly
Syntax
if<cc> <expression>
instructions
endc
Function
The endc directive closes an if<cc> or elsec conditional directive. The
conditional status reverts to the one existing before entering the if<cc>
directives. The endc directive applies to the closest previous if<cc> or
elsec directive.
Example
ifge offset-127 ; if offset too large
addptr offset ; call a macro
elsec ; otherwise
inc x ; increment X register
endc
Note
The endc and endif directives are equivalent and may used without dis-
tinction. They are provided for compatibility with previous assemblers.
See Also
if<cc>, elsec, clist, end
endif
Description
End conditional assembly
Syntax
if <expression>
instructions
endif
Function
The endif directive closes an if, or else conditional directive. The con-
ditional status reverts to the one existing before entering the if directive.
The endif directive applies to the closest previous if or else directive.
Example
if offset != 1 ; if offset too large
addptr offset ; call a macro
else ; otherwise
inc x ; increment X register
endif
Note
The endif and endc directives are equivalent and may used without dis-
tinction. They are provided for compatibility with previous assemblers.
See Also
if, else, clist
endm
Description
End macro definition
Syntax
label: macro
<macro_body>
endm
Function
The endm directive is used to terminate macro definitions.
Example
; define a macro that places the length of
; a string in a byte prior to the string
ltext: macro
ds.b \@2 - \@1
\@1:
ds.b \1
\@2:
endm
See Also
mexit, macro
endr
Description
End repeat section
Syntax
repeat
<repeat_body>
endr
Function
The endr directive is used to terminate repeat sections.
Example
; shift a value n times
asln: macro
repeat \1
sla
endr
endm
See Also
repeat, repeatl, rexit
equ
Description
Give a permanent value to a symbol
Syntax
label: equ <expression>
Function
The equ directive is used to associate a permanent value to a symbol
(label). Symbols declared with the equ directive may not subsequently
have their value altered otherwise the set directive should be used.
<expression> must be either a constant expression, or a relocatable
expression involving a symbol declared in the same section as the cur-
rent one.
The equ directive can also be used to define a bit symbol by suffixing
the defining expression with an absolute bit number. The expression
and the bit number are separated by a colon character ‘:’. The expres-
sion can be absolute or relocatable.
Example
false: equ 0 ; initialize these values
true: equ 1
tablen: equ tabfin - tabsta ;compute table length
nul: equ $0 ;define strings for ascii characters
soh: equ $1
stx: equ $2
etx: equ $3
eot: equ $4
enq: equ $5
PORTB: equ $1
PB2: equ PORTB:2
See Also
lit, set
even
Description
Assemble next byte at the next even address relative to the start of a
section.
Syntax
even [fill_<value>]
Function
The even directive forces the next assembled byte to the next even
address. If a byte is added to the section, it is set to the value of the fill-
ing byte defined by the -f option. If <fill_value> is specified, it will be
used locally as the filling byte, instead of the one specified by the -f
option.
Example
vowtab: dc.b 'aeiou'
even ; ensure aligned at even address
tentab: dc.w 1, 10, 100, 1000
fail
Description
Generate error message.
Syntax
fail "string"
Function
The fail directive outputs “string” as an error message. No output file is
produced as this directive creates an assembly error. fail is generally
used with conditional directives.
Example
Max: equ 512
ifge value - Max
fail “Value too large”
if
Description
Conditional assembly
Syntax
if <expression> or if <expression>
instructions instructions
endif else
instructions
endif
Function
The if, else and endif directives allow conditional assembly. The if
directive is followed by a constant expression. If the result of the
expression is not zero, the following instructions are assembled up to
the next matching endif or else directive; otherwise, the following
instructions up to the next matching endif or else directive are skipped.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
if offset != 1 ; if offset too large
addptr offset ; call a macro
else ; otherwise
inc x ; increment X register
endif
See Also
else, endif, clist
ifc
Description
Conditional assembly
Syntax
ifc <string1>,<string2> orifc <string1>,<string2>
instructions instructions
endc elsec
instructions
endc
Function
The ifc, else and endc directives allow conditional assembly. The ifc
directive is followed by a constant expression. If <string1> and
<string2> are equals, the following instructions are assembled up to the
next matching endc or elsec directive; otherwise, the following instruc-
tions up to the next matching endc or elsec directive are skipped.
If the ifc statement ends with an elsec directive, the expression result is
inverted and the same process applies to the following instructions up to
the next matching endc. So, if the ifc expression was not zero, the
instructions between elsec and endc are skipped; otherwise, the instruc-
tions between elsec and endc are assembled. An elsec directive applies
to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifc “hello”, \2 ; if “hello” equals argument
ld a,#45 ; load 45
elsec ; otherwise...
ld a,#0
endc
See Also
elsec, endc, clist
ifdef
Description
Conditional assembly
Syntax
ifdef <label> or ifdef <label>
instructions instructions
endc elsec
instructions
endc
Function
The ifdef, elsec and endc directives allow conditional assembly. The
ifdef directive is followed by a label <label>. If <label> is defined, the
following instructions are assembled up to the next matching endc or
elsec directive; otherwise, the following instructions up to the next
matching endc or elsec directive are skipped. <label> must be first
defined. It cannot be a forward reference.
If the ifdef statement ends with an elsec directive, the expression result
is inverted and the same process applies to the following instructions up
to the next matching endif. So, if the ifdef expression was not zero, the
instructions between elsec and endc are skipped; otherwise, the instruc-
tions between elsec and endc are assembled. An elsec directive applies
to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifdef offset1 ; if offset1 is defined
addptr offset1 ; call a macro
elsec ; otherwise
addptr offset2 ; call a macro
endif
See Also
ifndef, elsec, endc, clist
ifeq
Description
Conditional assembly
Syntax
ifeq <expression> or ifeq <expression>
instructions instructions
endc elsec
instructions
endc
Function
The ifeq, elsec and endc directives allow conditional assembly. The
ifeq directive is followed by a constant expression. If the result of the
expression is equal to zero, the following instructions are assembled up
to the next matching endc or elsec directive; otherwise, the following
instructions up to the next matching endc or elsec directive are skipped.
If the ifeq statement ends with an elsec directive, the expression result
is inverted and the same process applies to the following instructions up
to the next matching endc. So, if the ifeq expression is equal to zero,
the instructions between elsec and endc are skipped; otherwise, the
instructions between elsec and endc are assembled. An elsec directive
applies to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifeq offset ; if offset nul
tnz a ; just test it
elsec ; otherwise
add a,#offset ; add to accu
endc
See Also
elsec, endc, clist
ifge
Description
Conditional assembly
Syntax
ifge <expression> or ifge <expression>
instructions instructions
endc elsec
instructions
endc
Function
The ifge, elsec and endc directives allow conditional assembly. The
ifge directive is followed by a constant expression. If the result of the
expression is greater or equal to zero, the following instructions are
assembled up to the next matching endc or elsec directive; otherwise,
the following instructions up to the next matching endc or elsec direc-
tive are skipped.
If the ifge statement ends with an elsec directive, the expression result
is inverted and the same process applies to the following instructions up
to the next matching endc. So, if the ifge expression is greater or equal
to zero, the instructions between elsec and endc are skipped; otherwise,
the instructions between elsec and endc are assembled. An elsec direc-
tive applies to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifge offset-127 ; if offset too large
addptr offset ; call a macro
elsec ; otherwise
inc x ; increment X register
endc
See Also
elsec, endc, clist
ifgt
Description
Conditional assembly
Syntax
ifgt <expression> or ifgt <expression>
instructions instructions
endc elsec
instructions
endc
Function
The ifgt, elsec and endc directives allow conditional assembly. The ifgt
directive is followed by a constant expression. If the result of the
expression is greater than zero, the following instructions are assem-
bled up to the next matching endc or elsec directive; otherwise, the fol-
lowing instructions up to the next matching endc or elsec directive are
skipped.
If the ifgt statement ends with an elsec directive, the expression result is
inverted and the same process applies to the following instructions up to
the next matching endc. So, if the ifgt expression was greater than
zero, the instructions between elsec and endc are skipped; otherwise,
the instructions between elsec and endc are assembled. An elsec direc-
tive applies to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifgt offset-127 ; if offset too large
addptr offset ; call a macro
elsec ; otherwise
inc x ; increment X register
endc
See Also
elsec, endc, clist
ifle
Description
Conditional assembly
Syntax
ifle <expression> or ifle <expression>
instructions instructions
endc elsec
instructions
endc
Function
The ifle, elsec and endc directives allow conditional assembly. The ifle
directive is followed by a constant expression. If the result of the
expression is less or equal to zero, the following instructions are
assembled up to the next matching endc or elsec directive; otherwise,
the following instructions up to the next matching endc or elsec direc-
tive are skipped.
If the ifle statement ends with an elsec directive, the expression result is
inverted and the same process applies to the following instructions up to
the next matching endc. So, if the ifle expression was less or equal to
zero, the instructions between elsec and endc are skipped; otherwise,
the instructions between elsec and endc are assembled. An elsec direc-
tive applies to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifle offset-127 ; if offset small enough
inc x ; increment X register
elsec ; otherwise
addptr offset ; call a macro
endc
See Also
elsec, endc, clist
iflt
Description
Conditional assembly
Syntax
iflt <expression> or iflt <expression>
instructions instructions
endc elsec
instructions
endc
Function
The iflt, else and endc directives allow conditional assembly. The iflt
directive is followed by a constant expression. If the result of the
expression is less than zero, the following instructions are assembled
up to the next matching endc or elsec directive; otherwise, the follow-
ing instructions up to the next matching endc or elsec directive are
skipped.
If the iflt statement ends with an elsec directive, the expression result is
inverted and the same process applies to the following instructions up to
the next matching endc. So, if the iflt expression was less than zero,
the instructions between elsec and endc are skipped; otherwise, the
instructions between elsec and endc are assembled. An elsec directive
applies to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
iflt offset-127 ; if offset small enough
inc x ; increment X register
elsec ; otherwise
addptr offset ; call a macro
endc
See Also
elsec, endc, clist
ifndef
Description
Conditional assembly
Syntax
ifndef <label> or ifndef <label>
instructions instructions
endc elsec
instructions
endc
Function
The ifndef, else and endc directives allow conditional assembly. The
ifndef directive is followed by a label <label>. If <label> is not
defined, the following instructions are assembled up to the next match-
ing endc or elsec directive; otherwise, the following instructions up to
the next matching endc or elsec directive are skipped. <label> must be
first defined. It cannot be a forward reference.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifndef offset1 ; if offset1 is not defined
addptr offset2 ; call a macro
elsec ; otherwise
addptr offset1 ; call a macro
endif
See Also
ifdef, elsec, endc, clist
ifne
Description
Conditional assembly
Syntax
ifne <expression> or ifne <expression>
instructions instructions
endc elsec
instructions
endc
Function
The ifne, elsec and endc directives allow conditional assembly. The
ifne directive is followed by a constant expression. If the result of the
expression is not equal to zero, the following instructions are assem-
bled up to the next matching endc or elsec directive; otherwise, the fol-
lowing instructions up to the next matching endc or elsec directive are
skipped.
If the ifne statement ends with an elsec directive, the expression result
is inverted and the same process applies to the following instructions up
to the next matching endc. So, if the ifne expression was not equal to
zero, the instructions between elsec and endc are skipped; otherwise,
the instructions between elsec and endc are assembled. An elsec direc-
tive applies to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifne offset ; if offset not nul
add a,#offset ; add to accu
elsec ; otherwise
tnz a ; just test it
endc
See Also
elsec, endc, clist
ifnc
Description
Conditional assembly
Syntax
ifnc <string1>,string2> or ifnc <string1><string2>
instructions instructions
endc elsec
instructions
endc
Function
The ifnc, elsec and endc directives allow conditional assembly. The
ifnc directive is followed by a constant expression. If <string1> and
<string2> are different, the following instructions are assembled up to
the next matching endc or elsec directive; otherwise, the following
instructions up to the next matching endc or elsec directive are skipped.
If the ifnc statement ends with an elsec directive, the expression result
is inverted and the same process applies to the following instructions up
to the next matching endc. So, if the ifnc expression was not zero, the
instructions between elsec and endc are skipped; otherwise, the instruc-
tions between elsec and endc are assembled. An elsec directive applies
to the closest previous if directive.
The if directives may be nested. The skipped lines may or may not be in
the listing depending on the clist directive status.
Example
ifnc “hello”, \2
addptr offset ; call a macro
else ; otherwise
inc x ; increment X register
endif
See Also
elsec, endc, clist
include
Description
Include text from another text file
Syntax
include "filename"
Function
The include directive causes the assembler to switch its input to the
specified filename until end of file is reached, at which point the assem-
bler resumes input from the line following the include directive in the
current file. The directive is followed by a string which gives the name
of the file to be included. This string must match exactly the name and
extension of the file to be included; the host system convention for
uppercase/lowercase characters should be respected.
Example
include “datstr” ; use data structure library
include “bldstd” ; use current build standard
include “matmac” ; use maths macros
include “ports82” ; use ports definition
list
Description
Turn on listing during assembly.
Syntax
list
Function
The list directive controls the parts of the program which will be written
to the listing file. It is effective if and only if listings are requested; it is
ignored otherwise.
Example
list ; expand source code until end or nolist
dc.b 1,2,4,8,16
end
See Also
nolist
lit
Description
Give a text equivalent to a symbol
Syntax
label: lit “string”
Function
The lit directive is used to associate a text string to a symbol (label).
This symbol is replaced by the string content when parsed in any
assembler instruction or directive.
Example
nbr: lit “#5”
ld a,nbr ; expand as ‘ld a,#5’
See Also
equ, set
local
Description
Create a new local block
Syntax
local
Function
The local directive is used to create a new local block. When the local
directive is used, all temporary labels defined before the local directive
will be undefined after the local label. New local labels can then be
defined in the new local block. Local labels can only be referenced
within their own local block. A local label block is the area between
two standard labels or local directives or a combination of the two.
Example
var: ds.b 1
var2: ds.b 1
function1:
10$: ld a,var
jreq 10$
ld var2,a
local
10$: ld a,var2
jreq 10$
ld var,a
ret
macro
Description
Define a macro
Syntax
label: macro
<macro_body>
endm
Function
The macro directive is used to define a macro. The name may be any
previously unused name, a name already used as a macro, or an instruc-
tion mnemonic for the microprocessor.
Example
; define a macro that places the length of a string
; in a byte in front of the string using numbered syntax
;
ltext: macro
dc.b \@2-\@1
\@1:
dc.b \1 ; text given as first operand
\@2:
endm
See Also
endm, mexit
messg
Description
Send a message out to STDOUT
Syntax
messg “<text>”
messg ‘<text>’
Function
The messg directive is used to send a message out to the host system’s
standard output (STDOUT).
Example
messg “Test code for debug”
ld a,_#2
ld _SCR,a
See Also
title
mexit
Description
Terminate a macro definition
Syntax
mexit
Function
The mexit directive is used to exit from a macro definition before the
endm directive is reached. mexit is usually placed after a conditional
assembly directive.
Example
ctrace:macro
if tflag == 0
mexit
endif
jp \1
endm
See Also
endm, macro
mlist
Description
Turn on or off listing of macro expansion.
Syntax
mlist [on|off]
Function
The mlist directive controls the parts of the program which will be writ-
ten to the listing file produced by a macro expansion. It is effective if
and only if listings are requested; it is ignored otherwise.
The parts of the program to be listed are the lines which are assembled
in a macro expansion.
See Also
macro
nolist
Description
Turn off listing.
Syntax
nolist
Function
The nolist directive controls the parts of the program which will be not
written to the listing file until an end or a list directive is encountered. It
is effective if and only if listings are requested; it is ignored otherwise.
See Also
list
Note
For compatibility with previous assemblers, the directive nol is alias to
nolist.
nopage
Description
Disable pagination in the listing file
Syntax
nopage
Function
The nopage directive stops the pagination mechanism in the listing out-
put. It is ignored if no listing has been required.
Example
xref mult, div
nopage
ds.b charin, charout
ds.w a, b, sum
See Also
plen, title
offset
Description
Creates absolute symbols
Syntax
offset <expresion>
Function
The offset directive starts an absolute section which will only be used to
define symbols, and not to produce any code or data. This section starts
at the address specified by <expression>, and remains active while no
directive or instructions producing code or data is entered. This abso-
lute section is then destroyed and the current section is restored to the
one which was active when the offset directive has been entered. All the
labels defined is this section become absolute symbols.
Example
offset 0
next:
ds.b 2
buffer:
ds.b 80
switch .text
size:
ld x,next ; ends the offset section
org
Description
Sets the location counter to an offset from the beginning of a section.
Syntax
org <expresion>
Function
<expression> must be a valid absolute expression. It must not contain
any forward or external references.
For an absolute section, the first org before any code or data defines the
starting address.
Any gap created by an org directive is filled with the byte defined by
the -f option.
page
Description
Start a new page in the listing file
Syntax
page
Function
The page directive causes a formfeed to be inserted in the listing output
if pagination is enabled by either a title directive or the -ft option.
Example
xref mult, div
page
ds.b charin, charout
ds.w a, b, sum
See Also
plen, title
plen
Description
Specify the number of lines per pages in the listing file
Syntax
plen <page_length>
Function
The plen directive causes <page_length> lines to be output per page in
the listing output if pagination is enabled by either a title directive or
the -ft option. If the number of lines already output on the current page
is less than <page_length>, then the new page length becomes effec-
tive with <page_length>. If the number of lines already output on the
current page is greater than or equal to <page_length>, a new page will
be started and the new page length is set to <page_length>.
Example
plen 58
See Also
page, title
repeat
Description
Repeat a list of lines a number of times
Syntax
repeat <expression>
repeat_body
endr
Function
The repeat directive is used to cause the assembler to repeat the follow-
ing list of source line up to the next endr directive. The number of times
the source lines will be repeated is specified by the expression operand.
The repeat directive is equivalent to a macro definition followed by the
same number of calls on that macro.
Example
; shift a value n times
asln: macro
repeat \1
sla (x)
endr
endm
See Also
endr, repeatl, rexit
repeatl
Description
Repeat a list of lines a number of times
Syntax
repeatl <arguments>
repeat_body
endr
Function
The repeatl directive is used to cause the assembler to repeat the fol-
lowing list of source line up to the next endr directive. The number of
times the source lines will be repeated is specified by the number of
arguments, separated with commas (with a maximum of 36 arguments)
and executed each time with the value of an argument. The repeatl
directive is equivalent to a macro definition followed by the same
number of calls on that macro with each time a different argument. The
repeat argument is denoted \1 unless the argument list is starting by a
name prefixed by a \ character. In such a case, the repeat argument is
specified by its name prefixed by a \ character.
Example
; test a value using the numbered syntax
repeatl 1,2,3
add a,#\1 ; add to accu
endr
end
or
2 ; test a value
9 0000 ab01 add a,#1 ; add to accu
9 0002 ab02 add a,#2 ; add to accu
9 0004 ab03 add a,#3 ; add to accu
10 end
See Also
endr, repeat, rexit
restore
Description
Restore saved section
Syntax
restore
Function
The restore directive is used to restore the last saved section. This is
equivalent to a switch to the saved section.
Example
switch .bss
var: ds.b 1
var2: ds.b 1
save
switch .text
function1:
10$: ld a,var
jreq 10$
ld var2,a
function2:
10$: ld a,var2
sub a,var
jrne 10$
ret
restore
var3: ds.b 1
var4: ds.b 1
switch .text
ld a,var3
ld var4,a
end
See Also
save, section
rexit
Description
Terminate a repeat definition
Syntax
rexit
Function
The rexit directive is used to exit from a repeat definition before the
endr directive is reached. rexit is usually placed after a conditional
assembly directive.
Example
; shift a value n times
asln: macro
repeat \1
if \1 == 0
rexit
endif
sla
endr
endm
See Also
endr, repeat, repeatl
save
Description
Save section
Syntax
save
Function
The save directive is used to save the current section so it may be
restored later in the source file.
Example
switch .bss
var: ds.b 1
var2: ds.b 1
save
switch .text
function1:
10$: ld a,var
jreq 10$
ld var2,a
function2:
10$: ld a,var2
sub a,var
jrne 10$
ret
restore
var3: ds.b 1
var4: ds.b 1
switch .text
ld a,var3
ld var4,a
end
See Also
restore, section
scross
Description
Turn on or off section crossing
Syntax
scross [on|off]
Function
The scross directive controls the branch instructions optimization and
forces the usage of jpf instruction if scross is set (on) or jp instruction
otherwise. The assembler starts with scross on by default.
section
Description
Define a new section
Syntax
<section_name>: section [<attributes>]
Function
The section directive defines a new section, and indicates that the fol-
lowing program is to be assembled into a section named
<section_name>. The section directive cannot be used to redefine an
already existing section. If no name and no attributes are specified to
the section, the default is to defined the section as a text section with its
same attributes. It is possible to associate <attributes> to the new sec-
tion. An attribute is either the name of an existing section or an attribute
keyword. Attributes may be added if prefixed by a ‘+’ character or not
prefixed, or deleted if prefixed by a ‘-’ character. Several attributes may
be specified separated by commas. Attribute keywords are:
Example
CODE: section .text ; section of text
lab1: ds.b 5
DATA: section .data ; section of data
lab2: ds.b 6
switch CODE
lab3: ds.b 7
switch DATA
lab4: ds.b 8
This will place lab1 and then lab3 into consecutive locations in sec-
tion CODE and lab2 and lab4 in consecutive locations in section
DATA.
The .frame section is declared with same attributes than the .bsct sec-
tion and with the even attribute.
The .bit section is declared using 8 bit relocation, with an even align-
ment and storing data with an ascending order of significance.
When the -m option is used, the section directive also accepts a number
as operand. In that case, a labelled directive is considered as a section
definition, and an unlabelled directive is considered as a section open-
ing (switch).
See Also
switch, bsct
set
Description
Give a resetable value to a symbol
Syntax
label: set <expression>
Function
The set directive allows a value to be associated with a symbol. Sym-
bols declared with set may be altered by a subsequent set. The equ
directive should be used for symbols that will have a constant value.
<expression> must be fully defined at the time the equ directive is
assembled.
Example
OFST: set 10
See Also
equ, lit
spc
Description
Insert a number of blank lines before the next statement in the listing
file.
Syntax
spc <num_lines>
Function
The spc directive causes <num_lines> blank lines to be inserted in the
listing output before the next statement.
Example
spc 5
title “new file”
If listing is requested, 5 blank lines will be inserted, then the title will be
output.
See Also
title
switch
Description
Place code into a section.
Syntax
switch <section_name>
Function
The switch directive switches output to the section defined with the
section directive. <section_name> is the name of the target section,
and has to be already defined. All code and data following the switch
directive up to the next section, switch, bsct or end directive are placed
in the section <section_name>.
Example
switch .bss
buffer: ds.b 512
xdef buffer
See Also
section, bsct
tabs
Description
Specify the number of spaces for a tab character in the listing file
Syntax
tabs <tab_size>
Function
The tabs directive sets the number of spaces to be substituted to the tab
character in the listing output. The minimum value of <tab_size> is 0
and the maximum value is 128.
Example
tabs 6
title
Description
Define default header
Syntax
title "name"
Function
The title directive is used to enable the listing pagination and set the
default page header used when a new page is written to the listing out-
put.
Example
title “My Application”
See Also
page, plen
Note
For compatibility with previous assemblers, the directive ttl is alias to
title.
xbit
Description
Declare bit symbol as being defined elsewhere
Syntax
xbit[.b] identifier[,identifier...]
Function
Visibility of bit symbols between modules is controlled by the xref and
xbit directives. Symbols which are defined in other modules must be
declared as xbit. A symbol may be declared both xdef and xbit in the
same module, to allow for usage of common headers.
The directive xbit.b declares external symbols located in the .bsct sec-
tion.
Example
xbit otherprog
xbit.b zpage ; is in .bsct section
See Also
xdef, xref
xdef
Description
Declare a variable to be visible
Syntax
xdef identifier[,identifier...]
Function
Visibility of symbols between modules is controlled by the xdef and
xref directives. A symbol may only be declared as xdef in one module.
A symbol may be declared both xdef and xref in the same module, to
allow for usage of common headers.
Example
xdef sqrt ; allow sqrt to be called
; from another module
sqrt: ; routine to return a square root
; of a number >= zero
See Also
xbit, xref
xref
Description
Declare symbol as being defined elsewhere
Syntax
xref[.b] identifier[,identifier...]
Function
Visibility of symbols between modules is controlled by the xref and
xdef directives. Symbols which are defined in other modules must be
declared as xref. A symbol may be declared both xdef and xref in the
same module, to allow for usage of common headers.
The directive xref.b declares external symbols located in the .bsct sec-
tion.
Example
xref otherprog
xref.b zpage ; is in .bsct section
See Also
xbit, xdef
wdef
Description
Declare a symbol as a default definition
Syntax
wdef identifier[,identifier...]
Function
The wdef directive allows declaring a symbol as public with a weak
definition, meaning that another definition of the same symbol in an
other file using an xdef directive, will silently overwrite the wdef defini-
tion.
A symbol may be declared both wdef and xref in the same module, to
allow for usage of common headers.
Example
wdef it_irq ; default irq handler
it_irq:
b it_irq ; stay here
See Also
xdef
• Introduction
• Overview
• Linker Options
• Section Relocation
• Linking Objects
• Moveable Code
• Checksum Computation
• Special Topics
Introduction
The linker combines relocatable object files, selectively loading from
libraries of such files made with clib, to create an executable image for
standalone execution or for input to other binary reformatters.
clnk will also allow the object image that it creates to have local symbol
regions, so the same library can be loaded multiple times for different
segments, and so that more control is provided over which symbols are
exposed. On microcontroller architectures this feature is useful if your
executable image must be loaded into several noncontiguous areas in
memory.
NOTE
The terms “segment” and “section” refer to different entities and are
carefully kept distinct throughout this chapter. A “section” is a contigu-
ous subcomponent of an object module that the linker treats as indivisi-
ble.
For most applications, the “sections” in an object module that the linker
accepts as input are equivalent to the “segments” of the executable
image that the linker generates as output.
Overview
You use the linker to build your executable program from a variety of
modules. These modules can be the output of the C cross compiler, or
can be generated from handwritten assembly language code. Some
modules can be linked unconditionally, while others can be selected
only as needed from function libraries. All input to the linker, regard-
less of its source, must be reduced to object modules, which are then
combined to produce the program file.
In most cases, the final program file created by clnk is structurally iden-
tical to the object module input to clnk. The only difference is that the
executable file is complete and contains everything that it needs to run.
There are a variety of utilities which will take the executable file and
convert it to a form required for execution in specific microcontroller
environments. The linker itself can perform some conversions, if all
that is required is for certain portions of the executable file to be
stripped off and for segments to be relocated in a particular way. You
can therefore create executable programs using the linker that can be
passed directly to a PROM programmer.
• The final output of the linker is a header, followed by all the seg-
ments and the symbol table. There may also be an additional
debug symbol table, which contains information used for debug-
ging purposes.
Group 1
(+seg <section>) controls the creation of new segments and has
parameters which are selected from the set of local flags.
Group 2
(+inc*) is used to include files
Group 3
(+new, +pub and +pri) controls name regions and takes no parame-
ters.
Group 4
(+def <symbol>) is used to define symbols and aliases and takes one
required parameter, a string of the form ident1=ident2, a string of the
form ident1=constant, or a string of the form ident1=@segment.
Group 5
(+spc <segment>) is used to reserve space in a particular <segment>
and has a required parameter
The manner in which the linker relocates the various sections is control-
led by the +seg option and its parameters. If the size of a current seg-
ment is zero when a command to start a new segment of the same name
is encountered, it is discarded. Several different sections can be redi-
rected directly to the same segment by using the +grp option.
Linker Options
The linker accepts the following options, each of which is described in
detail below.
The output file name and the link command file must be present on
the command line. The options are described in terms of the two groups
listed above; the global options that apply to the linker, and the segment
control options that apply only to specific segments.
-bs# set the window shift to #, which implies that the number of
bytes in a window is 2**#. The default value is . For more
information, see the section “Address Specification” on page
279.
-e* log errors in the text file * instead of displaying the messages
on the terminal screen.
-ge produce error messages directly compatible with the Eclipse
environment
-l*> specify library path. You can specify up to 128 different
paths. Each path is a directory name, not terminated by any
directory separator character.
-m* produce map information for the program being built to file *.
-o* write output to the file *. This option is required and has no
default value.
-p display symbols with physical address instead of logical
address in the map file.
-s create an output file containing only an absolute symbol
table, but still with an object file format. The resulting file can
then be used in another link to provide the symbol table of an
existing application.
-sa display symbols sort by address instead of alphabetic order
in the map file.
-si suppress the .info. segment content for compatibility with
tools not supporting this segment yet.
-sl output local symbols in the executable file.
-ck mark the segment you want to check. For more information,
see “Checksum Computation” on page 289.
-cs* define a count space name for the segment. The total
amount of bytes counted in all segments sharing the same
space name is displayed in the map file.
-ds# set the bank size for paged addresses calculation. This
option overwrites the global -bs option for that segment.
-e* set the physical end address of the segment to *. Option -b
or -a cannot be specified if -e has been specified.
-s* define a space name for the segment. This segment will be
verified for overlapping only against segments defined with
the same space name. See “Overlapping Control” on page
279.
-v do not verify overlapping for the segment.
-w* set the window size for banked applications, and activate
the automatic bank segment creation.
-x expandable segment. Allow a segment to spill in the next
segment of the same section type if its size exceeds the
value given by the -m option. The next segment must be
declared before the object causing the overflow. This
option has no effect if no -m option is specified for the
expendable segment. Option -e cannot be specified with
option -x.
+def START=0x1000
+def MAXSIZE=0x2000
+seg .text -bSTART+0x100 -mMAXSIZE-0x100
The first line defines the symbol START equals to the absolute value
1000 (hex value), the second line defines the symbol MAXSIZE equals
to the absolute value 2000 (hex value). The last line opens a .text seg-
ment located at 1100 (hex value) with a maximum size of 1f00 (hex
value). For more information, see the section “Symbol Definition
Option” on page 276.
Unless -b* is given to set the bss segment start address, the bss segment
will be made to follow the last data segment in the output file. Unless
-b* is given to set the data segment start address, the data segment will
be made to follow the last bsct segment in the output file. The bsct and
text segments are set to start at zero unless you specify otherwise by
using -b option. It is permissible for all segments to overlap, as far as
clnk is concerned; the target machine may or may not make sense of
this situation (as with separate instruction and data spaces).
NOTE
A new segment of the specified type will not actually be created if the last
segment of the same name has a size of zero. However, the new options
will be processed and will override the previous values.
Segment Grouping
Different sections can be redirected directly to the same segment with
the +grp directive:
NOTE
Whitespaces are not allowed aside the equal sign ‘=’ and the commas.
@1, @2,... include each individual object file at its positional location
on the command line and insert them at the respective
locations in the link file (@1 is the first object file, and so
on).
Example
Linking objects from the command line:
## Test.lkf:
+seg .text -b0x5000
+seg .data -b0x100
@1
+seg .text -b0x7000
@2
Is equivalent to
Include Option
Subparts of the link command file can be included from other files by
using the following option:
Example
Include the file “seg2.txt” in the link file “test.lkf”:
## Test.lkf:
+seg .text -b0x5000
+seg .data -b0x100
file1.o file2.o
+seg .text -b0x7000
+inc seg2.txt
## seg2.txt:
mod1.o mod2.o mod3.o
+def* define new symbols to the linker. The string * can use dif-
ferent syntaxes:
NOTE
Whitespaces are not allowed aside the equal sign ‘=’.
NOTE
Whitespaces are not allowed aside the equal sign ‘=’.
For more information about DEFs and REFs, refer to the section “DEFs
and REFs” on page 291.
NOTE
Whitespaces are not allowed aside the equal sign ‘=’.
Handle Dependencies
This directive allows creating or suppressing a dependency between
two functions using their assembly level symbol:
NOTE
Whitespaces are not allowed aside the + and - signs.
Section Relocation
The linker relocates the sections of the input files into the segments of
the output file.
Address Specification
The two most important parameters describing a segment are its bias
and its offset, respectively its physical and logical start addresses. In
nonsegmented architectures there is no distinction between bias and off-
set. The bias is the address of the location in memory where the seg-
ment is relocated to run. The offset of a segment will be equal to the
bias. In this case you must set only the bias. The linker sets the offset
automatically.
Overlapping Control
The linker is verifying that a segment does not overlap any other one,
by checking the physical addresses (bias). This control can be locally
disabled for one segment by using the -v option. For targets implement-
ing separated address spaces (such as bank switching), the linker allows
several segments to be isolated from the other ones, by giving them a
space name with the -s option. In such a case, a segment in a named
space is checked only against the other segments of the same space. The
unnamed segments are checked together.
starting at bit 0, and converts a bit address to a byte address when leav-
ing a bit segment to a byte segment, starting from next available byte.
Bit addresses are displayed in the map file using the combined syntax.
If the bit segment contains initialized variables, the code must be linked
with an appropriate startup file and the bit segment must be declared
with option -id in the linker command file. Otherwise, the bit segment
must be declared with option -c to suppress it from the output file.
Linking Objects
A new segment is built by concatenating the corresponding sections of
the input object modules in the order the linker encounters them. As
each input section is added to the output segment, it is adjusted to be
relocated relative to the end portion of the output segment so far con-
structed. The first input object module encountered is relocated relative
to a value that can be specified to the linker. The size of the output bss
segment is the sum of the sizes of the input bss sections.
NOTE
When using a model for application smaller than 64K, you must link with
the specific set of libraries (names ending with ‘0’).
NOTE
When using a model for application smaller than 64K, you must link with
the specific set of libraries (names ending with ‘0’).
Library Order
You should link your application with the libraries in the following
orders:
C>set CXLIB=C:\COSMIC\LIB
Then, clnk looks in the executable file for initialized segments. All the
segments .data and .bsct are selected by default, unless disabled explic-
itly by the -ib option. Otherwise, renamed segments may also be
selected by using the -id option. The -id option cannot be specified on a
bss segment, default or renamed. Once all the selected segments are
located, clnk builds a descriptor containing the starting address and
length of each such segment, and moves the descriptor and the selected
segments to the end of the host segment, without relocating the content
of the selected segments.
Descriptor Format
The created descriptor has the following format:
The flag byte is used to detect the end of the descriptor, and also to
specify a type for the data segment. The actual value is equal to the
code of the first significant letter in the segment name.
The end address in PROM of one segment gives also the starting
address in prom of the following segment, if any.
If the host segment has been opened with a -m option giving a maxi-
mum size, clnk will check that there is enough space to move all the
selected segments.
Moveable Code
The linker allows a code segment to be stored in the ROM part, but
linked at another address which is supposed to be located in RAM. This
feature is specially designed to allow an application to run FLASH pro-
gramming routines or bootloader from the RAM space. This feature is
sharing the same global mechanism than initialized data, and the com-
mon descriptor built by the linker contains both record types. The flag
byte is used to qualify each entry. In order to implement such a feature,
the link command file should contain a dedicated code segment marked
with the -ic option:
The function contained in the object flash.o is now linked at the RAM
address 0x100 but stored somewhere in the code space along with any
other initialized data. It is not necessary to link the application with the
startup routine crtsi.s if the application does not contain initialized data
but the descriptor will be built as soon as a moveable function is used
by the application, but if the crts.s startup is used, moveable code seg-
ments are not copied in RAM at the application start up.
if (_fctcpy(‘b’))
flash();
The code built and expected to run at 0x3000 will be stored in the
.image segment wherever it is located, and will not be loaded at its
execution location in the resulting application code. It is then possible
to use memcpy() when the code must be copied to its execution location
(0x3000 in this case). You can define the following linker symbols in
your linker command file for the execution start address (copy to), the
image location address (copy from) and the image size.
+def _ramcode=start(ramcode)
+def _image=start(image)
+def _isize=size(image)
The linker symbol assignments are treated like addresses so the copy
code would be the following:
Checksum Computation
This feature is activated by the detection of the symbol __ckdesc__ as
an undefined symbol. This is practically done by calling one of the pro-
vided checksum functions, which uses that symbol and returns 0 if the
checksum is correct. These functions are provided in the integer library
and are the following:
The two last functions are computing a 16-bit CCITT checksum while
the other ones compute a simpler byte based checksum which is much
faster.
You then have to update the link command file in two ways:
will be also checked. Note also that if you are using the automatic
initialization mechanism, and if the code segment hosting the init
descriptor (-it) is also marked with -ck, the init segment and ALL
the initialization copy segments will also be checked.
Here is an example of link command file showing how to use -ck and
-ik:
The end address is always one pointer. The last entry is always fol-
lowed by a nul byte (seen as an ending flag), and immediately followed
by the expected CRC if functions _checksum() or _checksum16() are
called. The linker compresses the list of entries by creating only one
entry for contiguous segments (as long as they are in the same space (-
s* option) and in the same bank/page).
The current linker implements only one algorithm. Starting with zero,
the CRC byte/word is first rotated one bit left (a true bit rotation), then
xor'ed with the code byte. The CRC values stored in the checksum
descriptor are the one’s complement value of the expected CRC.
The linker also builds a debug symbol table based on the debug symbol
tables in any of the input object modules. It builds the debug symbol
table by concatenating the debug symbol tables of each input object
module in the order it encounters them. If debugging is not enabled for
any of input object module, the debug symbol table will be of zero
length.
The executable file created by the linker must have no REFs in its sym-
bol table. Otherwise, the linker emits the error message “undefined sym-
bol” and returns failure.
Special Topics
This section explains some special linker capabilities that may have
limited applicability for building most kinds of microcontroller applica-
tions.
Any symbols defined in <public files> are known outside this private
name region. Any symbols defined in <private libraries> are known
only within this region; hence they may safely be redefined as private to
other regions as well.
NOTE
All symbols defined in a private region are local symbols and will not
appear in the symbol table of the output file.
Renaming Symbols
At times it may be desirable to provide a symbol with an alias and to
hide the original name (i.e., to prevent its definition from being used by
the linker as a DEF which satisfies REFs to that symbol name). As an
example, suppose that the function func in the C library provided with
the compiler does not do everything that is desired of it for some special
application. There are three methods of handling this situation (we will
ignore the alternative of trying to live with the existing function’s defi-
ciencies).
The first method is to write a new version of the function that performs
as required and link it into the program being built before linking in the
libraries. This will cause the new definition of func to satisfy any refer-
ences to that function, so the linker does not include the version from
the library because it is not needed. This method has two major draw-
backs: first, a new function must be written and debugged to provide
something which basically already exists; second, the details of exactly
what the function must do and how it must do it may not be available,
thus preventing a proper implementation of the function.
The third approach is to use the aliasing capabilities of the linker. Like
the second method, a new function will be written which performs the
new behavior and then calls the old function. The twist is to give the old
function a new name and hide its old name. Then the new function is
given the old function’s name and, when it calls the old function, it uses
the new name, or alias, for that function. The following linker script
provides a specific example of this technique for the function func:
NOTE
The function name func as referenced here is the name as seen by the C
programmer. The name which is used in the linker for purposes of alias-
ing is the name as seen at the object module level. For more information
on this transformation, see the section “Interfacing C to Assembly Lan-
guage” in Chapter 3.
The main thing to note here is that func.o and new_func.o both define a
(different) function named func. The second function func defined in
newfunc.o calls the old func function by its alias oldfunc.
Name regions provide limited scope control for symbol names. The
+new command starts a new name region, which will be in effect until
the next +new command. Within a region there are public and private
name spaces. These are entered by the +pub and +pri commands; by
default, +new starts in the public name space.
Lines 1,2 are the basic linker commands for setting up a separate I/D
program. Note that there may be other options required here, either by
the system itself or by the user.
Line 4 specifies the startup code for the system being used.
Line 5 establishes the symbol _oldfunc as an alias for the symbol _func.
The symbol _oldfunc is entered in the symbol table as a public defini-
tion. The symbol _func is entered as a private reference in the current
region.
Line 6 switches to the private name space in the current region. Then
func.o is linked and provides a definition (private, of course) which sat-
isfies the reference to _func.
Line 7 starts a new name region, which is in the public name space by
default. Now no reference to the symbol _func can reach the definition
created on Line 6. That definition can only be reached now by using the
symbol _oldfunc, which is publicly defined as an alias for it.
Line 8 links the user program and the module newfunc.o, which pro-
vides a new (and public) definition of _func. In this module the old ver-
sion is accessed by its alias. This new version will satisfy all references
to _func made in prog.o and the libraries.
The rules governing which name space a symbol belongs to are as fol-
lows:
• Any new reference is associated with the region in which the ref-
erence is made. It can be satisfied by a private definition in that
region, or by a public definition. A previous definition of that
symbol will satisfy the reference if that definition is public, or if
the definition is private and the reference is made in the same
region as the definition.
The first link builds the application itself using the appli.lkf command
file. The second link uses the same command file and creates an object
file containing only an absolute symbol table. This file can then be used
as an input object file in any other link command file.
Counts List the total amount of bytes produced in each count space
defined in the linker command file. If no count space is
defined, this section is not displayed.
Modules List all the modules which compose the application, giving
for each the description of all the defined sections with the
same format as in the Segment section. If an object has
been assembled with the -pl option, local symbols are dis-
played just after the module description.
Stack Usage Describe the amount of memory needed for the stack.
Each function of the application is listed by its name, fol-
lowed by a ‘>’ character indicating that this function is not
called by any other one (the main function, interrupt func-
tions, task entries...). The first number is the total size of
the stack used by the function including all the internal
calls. The second number between braces shows the stack
need for that function alone. The entry may be flagged by
the keyword “Recursive” meaning that this function is
itself recursive or is calling directly or indirectly a recur-
sive function, and that the total stack space displayed is not
accurate. The linker may detect potential but not actual
recursive functions when such functions are called by
Call Tree List all the functions sorted alphabetically followed by all
the functions called inside. The display goes on recursively
unless a function has already been listed. In such a case,
the name is followed by the line number where the func-
tion is expanded. If a line becomes too long, the process is
suspended and the line ends with a ... sequence indicating
that this function is listed later. Functions called by pointer
are listed between parenthesis, or between square brackets
if called from an array of pointers.
Return Value
clnk returns success if no error messages are printed to STDOUT; that
is, if no undefined symbols remain and if all reads and writes succeed.
Otherwise it returns failure.
A linker command file consists of linker options, input and output file,
and libraries. The options and files are read from a command file by the
linker. For example, to create an STM8 file from file.o you can type at
the system prompt:
Debugging Support
This chapter describes the debugging support available with the cross
compiler targeting the STM8. There are two levels of debugging sup-
port available, so you can use either the COSMIC’s Zap C source level
cross debugger or your own debugger or in-circuit emulator to debug
your application. This chapter includes the following sections:
2 information about the name, type, storage class and address (abso-
lute or relative to a stack offset) of program static data objects, func-
tion arguments, and automatic data objects that functions declare.
Information about what source files produced which relocatable or
executable files. This information may be localized by address
(where the output file resides in memory). It may be written to a file,
sorted by address or alphabetical order, or it may be output to a
printer in paginated or unpaginated format.
cprd may be used to extract the debugging information from files com-
piled with the +debug option, as described below.
where <file> is an object file compiled from C source with the com-
piler command line option +debug set.
Examples
The following example show sample output generated by running the
cprd utility on an object file created by compiling the program acia.c
with the compiler option +debug set.
cprd acia.sm8
To use clst efficiently, its argument files must have been compiled with
the +debug option.
is equivalent to:
clst acia.sm8>acia.lst
-r 0xe000:0xe200
Programming Support
This chapter describes each of the programming support utilities pack-
aged with the C cross compiler targeting the STM8. The following util-
ities are available:
Utility Description
The description of each utility tells you what tasks it can perform, the
command line options it accepts, and how you use it to perform some
commonly required operations. At the end of the chapter are a series of
examples that show you how to combine the programming support util-
ities to perform more complex operations.
Option Description
Option Description
Option Description
Return Status
chex returns success if no error messages are printed; that is, if all
records are valid and all reads and writes succeed. Otherwise it returns
failure.
Examples
The file hello.c, consisting of:
chex hello.o
S00A000068656C6C6F2E6F44
S1110000020068656C6C6F20776F726C640090
S9030000FC
clabs decodes an executable file to retrieve the list of all the files which
have been used to create the executable. For each of these files, clabs
looks for a matching listing file produced by the compiler (“.ls” file). If
such a file exists, clabs creates a new listing file (“.la” file) with abso-
lute addresses and code, extracted from the executable file.
To be able to produce any results, the compiler must have been used
with the ‘-l’ option.
Option Description
Option Description
Return Status
clabs returns success if no error messages are printed; that is, if all reads
and writes succeed. An error message is output if no relocatable listing
files are found. Otherwise it returns failure.
Examples
The following command line:
clabs -v acia.sm8
will output:
crts.ls
acia.ls
vector.ls
will generate:
crts.lx
acia.lx
vector.lx
Option Description
-i* take object files from a list *. You can put several files per
line or put one file per line. Each lines can include com-
ments. They must be prefixed by the ‘#’ character. If the
command line contains <files>, then <files> will be also
added to the library.
Option Description
-l when a library is built with this flag set, all the modules of
the library will be loaded at link time. By default, the linker
only loads modules necessary for the application.
-p do not prefix module names in library with any path. This
option is only meaningfull with option -c.
-r in an existing library, replace the zero or more files in
<files>. If no library <library> exists, create a library contain-
ing <files>. The files in <files> not present in the library are
added to it.
-s list the symbols defined in the library with the module name
to which they belong.
-t list the files in the library.
-v be verbose
-x extract the files in <files> that are present in the library into
discrete files with the same names. If no <files> are speci-
fied, all files in the library are extracted.
At most one of the options -[c r t x] may be specified at the same time.
If none of these is specified, the -t option is assumed.
Return Status
clib returns success if no problems are encountered. Otherwise it
returns failure. After most failures, an error message is printed to
STDERR and the library file is not modified. Output from the -t, -s
options, and verbose remarks, are written to STDOUT.
Examples
To build a library and check its contents:
will output:
one.o
two.o
three.o
Option Description
Return Status
cobj returns success if no diagnostics are produced (i.e. if all reads are
successful and all file formats are valid).
Examples
For example, to get the symbol table:
cobj -s acia.o
symbols:
The information for each symbol is: name, address, section to which it
belongs and attribute.
Option Description
-cl* specify a path for the listing files. By default, listings are in the
same directory than the source files.
-f* specify an input header file.
-v be “verbose”.
This utility scans the debug information to build a list of global varia-
bles not already defined in a dedicated space and the listing files to cre-
ate a count usage of these variables. If a header file is entered with the
option -f containing a list of variables described using the same syntax
than the output file, the specified variables will be ignored for the allo-
cation.
The most used variables are then allocated in the short range section by
producing a specific header file containing a list of #pragma
attribute directives. The maximum available space in the short
range section is defaulted to 256 bytes minus the space already used by
the provided application. The maximum space can be modified by
using the -m option.
The created header file can then be included by recompiling the appli-
cation sources with the option -ph followed by the header file name.
Return Status
ctat returns success if no problems are encountered. Otherwise it
returns failure.
Examples
The following command:
will generate zpage.h as the result file from the application test.sm8.
The application must be recompiled by adding to the already specified
options:
Option Description
-bs# set the window shift to #, which implies that the number of
bytes in a window is 2**#.
Option Description
Option Description
-so add stack offset. This option has to be selected when using
debuggers using the SP value directly.
Return Status
cvdwarf returns success if no problems are encountered. Otherwise it
returns failure.
Examples
Under MS/DOS, the command could be:
cvdwarf C:\test\acia.sm8
cvdwarf /test/acia.sm8
Compiler Error
Messages
This appendix lists the error messages that the compiler may generate in
response to errors in your program, or in response to problems in your
host system environment, such as inadequate space for temporary inter-
mediate files that the compiler creates.
The first pass of the compiler generally produces all user diagnostics.
This pass deals with # control lines and lexical analysis, and then with
everything else having to do with semantics. Only machine-dependent
extensions are diagnosed in the code generator pass. If a pass produces
diagnostics, later passes will not be run.
_asm string too long - the string constant passed to _asm is larger than
255 characters
array size unknown - the sizeof operator has been applied to an array
of unknown size
bad #else - a #else occurs without a previous #if, #ifdef, #ifndef or #elif
bad #endif - a #endif occurs without a previous #if, #ifdef, #ifndef, #elif
or #else
bad #ifdef syntax - extra characters are found after the symbol name
bad #ifndef syntax - extra characters are found after the symbol name
bad #include syntax - extra characters are found after the file name
bad #pragma section directive - syntax for the #pragma section direc-
tive is incorrect
bad #pragma space directive - syntax for the #pragma space directive
is incorrect
bad #pragma unroll directive - syntax for the #pragma unroll direc-
tive is incorrect
bad _asm() argument type - the first argument passed to _asm is miss-
ing or is not a character string
bad structure for return - the structure for return is not compatible
with that of the function
bad void argument - the type void has not been used alone in a proto-
typed function declaration
duplicate case - two case labels have been defined with the same value
in the same switch statement
duplicate default - a default label has been specified more than once in
a switch statement
file too large for label information - the source file is producing too
many labels in the code and debug parts for the coding restrictions
float value too large for integer cast - a float constant is too large to
be casted in an integer (+strict)
invalid address operand - the “address of” operator has been applied
to a register variable
invalid address type - the “address of” operator has been applied to a
bitfield
invalid binary number - the syntax for a binary constant is not valid
invalid bitfield size - a bitfield has been declared with a size larger than
its type size
invalid bitfield type - a type other than int, unsigned int, char,
unsigned char has been used in a bitfield.
invalid break - a break may be used only in while, for, do, or switch
statements
invalid case - a case label has been specified outside of a switch state-
ment
invalid cast type - a cast has been applied to an object that cannot be
coerced to a specific type
invalid function type - the function call operator () has been applied to
an object which is not a function or a pointer to a function
invalid shift count type - the right expression of a shift operator is not
an integer
invalid sizeof operand type - the sizeof operator has been applied to a
function
invalid space for function - a function has been declared with a space
modifier incompatible with the function allocation
invalid space for local <name> - a local variable has been declared
with a space modifier incompatible with the stack allocation
missing _asm() argument - the _asm function needs at least one argu-
ment
missing local name - a local variable has been declared without a name
missing ; - a ‘;’ is expected and not found. The parser reports such an
error on the previous element as most of the time the ; is missing at the
end of the declaration. When this error occurs on top of a file or just
after a file include, the line number reported may not match the exact
location where the problem is detected.
repeated type specification - the same type modifier occurs more than
once in a type specification
shift count out of range - a constant shift count is larger than the
shifted object size (+strict)
too many spaces modifiers - too many different names for ‘@’ modifi-
ers are used
<name> used before set - a local variable has been used before beeing
initialized by any previous code (+strict)
bad @interrupt usage - the @interrupt type modifier can only be used
on functions.
invalid indirect call - a function has been called through a pointer with
more than one char or int argument, or is returning a structure.
redefined space - the version of cpstm8 you used to compile your pro-
gram is incompatible with cgstm8.
All other PANIC ! messages should never happen. If you get such a
message, please report it with the corresponding source program to
COSMIC.
bad else - an else directive has been found without a previous if direc-
tive
bad file name - the include directive operand is not a character string
bad string constant - a character constant does not end with a single or
double quote
can't create <name> - the file <name> cannot be opened for writing
can't open <name> - the file <name> cannot be opened for reading
section name <name> too long - a section name has more than 15
characters
string constant too long - a string constant is longer than 255 charac-
ters
symbol <name> not defined - a symbol has been used but not declared
too many arguments - a macro has been invoked with more than 9
arguments
value too large - an operand is too large for the instruction type
bad file format - an input file has not an object file format.
bad number in +def - the number provided in a +def directive does not
follow the standard C syntax.
bad processor type - an object file has not the same configuration
information than the others.
bad section name in +def - the name specified after the ‘@’ in a +def
directive is not the name of a segment.
can't locate shared segment - shared datas have been found but no
host segment has been specified.
file already linked - an input file has already been processed by the
linker.
missing '=' in +spc <segment> - the +spc directive syntax is not cor-
rect.
shared segment not empty - the host segment for shared data is not
empty and cannot be used for allocation.
Modifying Compiler
Operation
This chapter tells you how to modify compiler operation by making
changes to the standard configuration file. It also explains how to create
your own programmable options” which you can use to modify com-
piler operation from the cxstm8.cxf.
cxstm8 hello.c
name:popt,gopt,oopt,aopt,exclude...
The first field defines the option name and must be ended by a colon
character ‘:’. The four next fields describe the effect of this option on
the four passes of the compiler, respectively the parser, the generator,
the optimizer and the assembler. These fields are separated by a comma
character ‘,’. If no specific option is needed on a pass, the field has to be
specified empty. The remaining fields, if specified, describe a exclusive
relationship with other defined options. If two exclusive options are
specified on the command line, the compiler will stop with an error
message. You may define up to 128 programmable options. At least one
field has to be specified. Empty fields need to be specified only if a use-
ful field has to be entered after.
the two options dl1 and dl2 are defined. If the option +dl1 is specified
on the compiler command line, the specific option -l will be used for the
parser and the specific option -dl1 will be used for the code generator.
No specific option will be used for the optimizer and for the assembler.
The option dl1 is also declared to be exclusive with the option dl2,
meaning that dl1 and dl2 will not be allowed together on the compiler
command line. The option dl2 is defined in the same way.
Example
The following command line
• longs and floats in the four byte memory location c_lreg, (“float
register” or “long register” depending on context).
The library functions using a pointer to far memory have a name begin-
ning with the ‘f’ letter, and the pointer is located in the pair composed
by the x register for the lower word, and the memory location c_x for
the upper byte. The following describes only the function handling data
in near memory. Their equivalent functions have the same description
except for the pointer location and size.
c_bitfw
Description
Update an int bitfield in near memory
Syntax
; bitfield address in y
; mask in c_x and c_x+1
; value in a and xl
call c_bitfw
Function
c_bitfw is used to update a 16 bits bitfield located in extended memory
by a new value located in the a and xl register pair. The value loaded
from extended memory is first and’ed with the mask located in the c_x
memory location. It is then or’ed with the value in the a and xl register
pair and stored back in memory.
Return Value
None.
c_bmulx
Description
Integer multiplication by char
Syntax
; left in x
; right in a
call c_bmulx
; result in x
Function
c_bmulx multiplies the two byte unsigned integer in the x register, by
the one byte unsigned integer in the a register. No check is made for
overflow.
Return Value
The resulting value is in x. Flags have no meaningful value upon return
See Also
c_bmuly
c_bmuly
Description
Integer multiplication by char
Syntax
; left in y
; right in a
call c_bmuly
; result in y
Function
c_bmuly multiplies the two byte unsigned integer in the y register, by
the one byte unsigned integer in the a register. No check is made for
overflow.
Return Value
The resulting value is in y. Flags have no meaningful value upon return
See Also
c_bmulx
c_cmulx
Description
Integer multiplication by char with long result
Syntax
; left in x
; right in a
call c_cmulx
; result in long register
Function
c_cmulx multiplies the two byte unsigned integer in the x register, by
the one byte unsigned integer in the a register, producing an unsigned
long result.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return
See Also
c_cmuly
c_cmuly
Description
Integer multiplication by char with long result
Syntax
; left in y
; right in a
call c_cmuly
; result in long register
Function
c_cmuly multiplies the two byte unsigned integer in the y register, by
the one byte unsigned integer in the a register, producing an unsigned
long result.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return
See Also
c_cmulx
c_eewbf
Description
Eeprom char bit field update
Syntax
; value in x
; address in c_x and extension
; mask in a
call c_eewbfb
Function
c_eewbf updates a char bit field (8 bits sized) located in eeprom with a
new value. The new value is in register x and is right justified. The byte
address in eeprom is in c_x and c_x+1, and the mask, giving the bit
field size and location, is in register a. The function waits for the time
necessary to program the new value.
See Also
c_eewstr
c_eewrc
Description
Write a char in eeprom
Syntax
; value in a
; address in x
call c_eewrc
Function
c_eewrc writes a byte in eeprom. The new byte value is in the a register
and its address in eeprom is in x. The function tests if the erasure is nec-
essary, and do it only in that case. Then if the new value is different
from one in eeprom, the new byte is programmed. The function waits
for the time necessary to program correctly the byte. The function does
not test if the byte address is in the address range corresponding to the
existing eeprom.
See Also
c_eewrl, c_eewrw
c_eewrl
Description
Write a long int in eeprom
Syntax
; value in c_lreg
; address in x
call c_eewrl
Function
c_eewrl writes a long int in eeprom. The new value is in the long regis-
ter, and its address in eeprom is in x. Each byte is programmed inde-
pendently by the c_eewrc function.
See Also
c_eewrc, c_eewrw
c_eewrw
Description
Write a short int in eeprom
Syntax
; value on the stack
; address in x
call c_eewrw
Function
c_eewrw writes a short int in eeprom. The new value is on the stack,
and its address in eeprom is in x. Each byte is programmed independ-
ently by the c_eewrc function.
See Also
c_eewrc, c_eewrl
c_eewstr
Description
Move a structure in eeprom
Syntax
; source address in y
; destination address in x
; size in a
call c_eewstr
Function
c_eewstr moves a structure into an eeprom memory location. Pointer to
source is in y, and pointer to destination is in x. The structure size is in
register a. Each byte is programmed independently by the c_eewrc
function.
See Also
c_eewbfb, c_eewrc
c_fadd
Description
Add float to float
Syntax
; left in float register
; pointer to right in x register
call c_fadd
; result in float register
Function
c_fadd adds the float in float register to the float indicated by the x reg-
ister. No check is made for overflow.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return.
See Also
c_fsub
c_fcmp
Description
Compare floats
Syntax
; left in float register
; pointer to right in x register
call c_fcmp
; result in flags
Function
c_fcmp compares the float in float register with the float pointered at by
the x register.
Return Value
The N and Z flags are set to reflect the value (left-right).
c_fdiv
Description
Divide float by float
Syntax
; left in float register
; pointer to right in x register
call c_fdiv
; result in float register
Function
c_fdiv divides the float in float register by the float pointered at by the x
register.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return.
c_fgadd
Description
Add float to float in memory
Syntax
; pointer to left in x register
; right in float register
call c_fgadd
; result in memory
Function
c_fgadd adds the float in the float pointered at by the x register to the
float register.
Return Value
The resulting value is stored at the location pointered at by the x regis-
ter, meaning that the left operand is updated. Flags have no meaningful
value upon return.
See Also
c_fgsub
c_fgmul
Description
Multiply float by float in memory
Syntax
; pointer to left in x register
; right in float register
call c_fgmul
; result in memory
Function
c_fgmul multiplies the float in float register by the float pointered at by
the x register.
Return Value
The resulting value is stored at the location pointered at by x. Flags
have no meaningful value upon return.
c_fgsub
Description
Subtract float from float in memory
Syntax
; pointer to left in x register
; right in float register
call c_fgsub
; result in memory
Function
c_fgsub subtracts the float pointered at by the x register from the float in
float register. No check is made for overflow.
Return Value
The resulting value is stored at the location pointered at by x. Flags
have no meaningful value upon return.
See Also
c_fgadd
c_fmul
Description
Multiply float by float
Syntax
; left in float register
; pointer to right in x register
call c_fmul
; result in float register
Function
c_fmul multiplies the float in float register by the float pointered at by
the x register.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return
c_fneg
Description
Negate a float
Syntax
; operand in float register
call c_fneg
; result in operand
Function
c_fneg negates the float pointered at by the float register.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return.
c_fsub
Description
Subtract float from float
Syntax
; left in float register
; pointer to right in x register
call c_fsub
; result in float register
Function
c_fsub subtracts the float pointed to by the x register from the float in
float register. No check is made for overflow.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return.
See Also
c_fadd
c_ftoi
Description
Convert float to integer
Syntax
; float in float register
call c_ftoi
; result in register x
Function
c_ftoi converts the float in float register to a two byte integer in the x
register. No check is made for overflow.
Return Value
The resulting value is in x. Flags have no meaningful value upon return.
See Also
c_ftol, c_itof, c_itol, c_ltof
c_ftol
Description
Convert float into long integer
Syntax
; float in float register
call c_ftol
;result in long register
Function
c_ftol converts the float in float register to a four byte integer in long
register. No check is made for overflow.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return.
See Also
c_ftoi, c_itof, c_itol, c_ltof
c_fzmp
Description
Compare a float in memory to zero
Syntax
; pointer to operand in x register
call c_fzmp
; result in flags
Function
c_fzmp compares the float pointered by the x register against zero.
Return Value
The N and Z flags are set to reflect the operand value.
c_getlx
Description
Get a long word from memory
Syntax
; long address in x
call c_getlx
; result in long register
Function
c_getlx gets a long integer from memory using a pointer loaded in x.
The result is left in the long register.
Return Value
The byte is loaded in the long register. Flags have no meaningful value
upon return.
See Also
c_getly, c_getwfx, c_getwfy
c_getly
Description
Get a long word from memory
Syntax
; long address in y
call c_gety
; result in long register
Function
c_getly gets a long integer from memory using a pointer loaded in y.
The result is left in the long register.
Return Value
The byte is loaded in the long register. Flags have no meaningful value
upon return.
See Also
c_getlx, c_getwfx, c_getwfy
c_getwfx
Description
Get a word from far memory
Syntax
; word address in x and c_x
call c_getwfx
; result in a and xl
Function
c_getwfx gets a word from far memory using a pointer loaded in x and
c_x. The result is left in the a and xl registers.
Return Value
The word is loaded in the a and xl registers. Flags have no meaningful
value upon return.
See Also
c_getlx, c_getly, c_getwfy
c_getwfy
Description
Get a word from far memory
Syntax
; word address in y and c_y
call c_getwfy
; result in a and xl
Function
c_getwfy gets a word from far memory using a pointer loaded in y and
c_y. The result is left in the a and xl registers.
Return Value
The word is loaded in the a and xl registers. Flags have no meaningful
value upon return.
See Also
c_getlx, c_getly, c_getwfx
c_getxfx
Description
Get a word from far memory
Syntax
; word address in x and c_x
call c_getxfx
; result in x
Function
c_getxfx gets a word from far memory using a pointer loaded in x and
c_x. The result is left in the x register.
Return Value
The word is loaded in the x register. Flags have no meaningful value
upon return.
See Also
c_getlx, c_getly, c_getwfy
c_getxfy
Description
Get a word from far memory
Syntax
; word address in y and c_y
call c_getxfy
; result in x
Function
c_getxfy gets a word from far memory using a pointer loaded in y and
c_y. The result is left in the x register.
Return Value
The word is loaded in the x register. Flags have no meaningful value
upon return.
See Also
c_getlx, c_getly, c_getwfy
c_getyfx
Description
Get a word from far memory
Syntax
; word address in x and c_x
call c_getyfx
; result in y
Function
c_getyfx gets a word from far memory using a pointer loaded in x and
c_x. The result is left in the y register.
Return Value
The word is loaded in the y register. Flags have no meaningful value
upon return.
See Also
c_getlx, c_getly, c_getwfy
c_getyfy
Description
Get a word from far memory
Syntax
; word address in y and c_y
call c_getyfy
; result in y
Function
c_getyfy gets a word from far memory using a pointer loaded in y and
c_y. The result is left in the y register.
Return Value
The word is loaded in the y register. Flags have no meaningful value
upon return.
See Also
c_getlx, c_getly, c_getwfy
c_idiv
Description
Quotient of integer division
Syntax
; dividend in x
; divisor in y
call c_idiv
; quotient in x
Function
c_idiv divides the two byte integer in the x register, by the two byte
integer in the y register. Values are assumed to be signed. If division by
zero is attempted, the result is the unchanged dividend.
Return Value
The quotient is placed in x. Flags have no meaningful value upon
return.
See Also
c_udiv
c_imul
Description
Integer multiplication
Syntax
; left in x
; right in y
call c_imul
; result in x
Function
c_imul multiplies the two byte integer in the x register, by the two byte
integer in the y register. No check is made for overflow.
Return Value
The resulting value is in x. Flags have no meaningful value upon return
c_itof
Description
Convert integer into float
Syntax
; operand in x
call c_itof
; result in float register
Function
c_itof converts the two byte integer in the x register, to a float stored in
float register.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return.
See Also
c_ltof, c_ultof, c_xtof, c_uitof, c_uxtof
c_itol
Description
Convert integer into long
Syntax
; operand in a and xl
call c_itol
; result in long register
Function
c_itol converts the two byte integer in the a and xl register pair, to a
long integer stored in long register.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return.
See Also
c_xtol, c_uitol, c_uxtol
c_itolx
Description
Convert integer into long
Syntax
; operand in x
call c_itolx
; result in long register
Function
c_itolx converts the two byte integer in the x register, to a long integer
stored in long register.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return.
See Also
c_xtol, c_uitol, c_uxtol
c_itoly
Description
Convert integer into long
Syntax
; operand in y
call c_itoly
; result in long register
Function
c_itoly converts the two byte integer in the y register, to a long integer
stored in long register.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return.
See Also
c_xtol, c_uitol, c_uxtol
c_jctab
Description
Perform C switch statement on char
Syntax
; value in a
; table address after the call
call c_jctab
Function
c_jctab is called to switch to the proper code segment, depending on a
value in the a register and an address table found just after the call
instruction, and consisting in a list of two bytes signed offsets.
Return Value
c_jctab jumps to the proper code. It never returns.
See Also
c_jstab, c_jltab
c_jltab
Description
Perform C switch statement on long
Syntax
; value in long register
; table address in x
jp c_jltab
Function
c_jltab is called to switch to the proper code segment, depending on a
value and an address table. The top of the table is found in the x regis-
ter, and consists of a count followed by a list of pairs. A pair consists of
a value followed by an address. The pair list is ended by the default
address. All values are four byte integers. All addresses and the count
are two byte integers.
Return Value
c_jltab jumps to the proper code. It never returns.
See Also
c_jctab, c_jstab
c_jstab
Description
Perform C switch statement on integer
Syntax
; value in x
; table address after the call
call c_jstab
Function
c_jstab is called to switch to the proper code segment, depending on a
value in the x register and an address table found just after the call
instruction, and consisting in a list of two bytes signed offsets.
Return Value
c_jstab jumps to the proper code. It never returns.
See Also
c_jctab, c_jltab
c_ladc
Description
Long integer addition
Syntax
; left in long register
; right in a register
call c_ladc
; result in long register
Function
c_ladc adds the four byte integer in long register and the unsigned char
in the a register.
Return Value
The result is in long register. Flags are not meaningful upon return.
See Also
c_ladd
c_ladd
Description
Long integer addition
Syntax
; left in long register
; pointer to right in x register
call c_ladd
; result in long register
Function
c_ladd adds the four byte integer in long register and the four byte inte-
ger pointered at by the x register.
Return Value
The result is in long register. Flags are not meaningful upon return.
See Also
c_lcmp, c_lsub
c_land
Description
Bitwise AND for long integers
Syntax
; left in long register
; pointer to right in x register
call c_land
; result in long register
Function
c_land operates a bitwise AND between the operands. Each operand is
taken to be a four byte integer.
Return Value
The result is in long register. Flags are not meaningful upon return.
See Also
c_lor, c_lxor
c_lcmp
Description
Long integer compare
Syntax
; left in long register
; pointer to right in x register
call c_lcmp
; result in long flags
Function
c_lcmp compares the four byte integer in long register to the four byte
integer pointered by the x register.
Return Value
Flags are set accordingly.
See Also
c_ladd, c_lsub, c_lsmp
c_ldiv
Description
Quotient of long integer division
Syntax
; dividend in long register
; pointer to divisor in x register
call c_ldiv
;quotient in long register
Function
c_ldiv divides the four byte integer in long register by the four byte
integer pointered by the x register. Values are assumed to be signed. If
division by zero is attempted, the result is the unchanged dividend.
Return Value
The quotient is in long register and the flags are not meaningful upon
return.
See Also
c_ludv, c_lmod, c_lumd
c_lgadc
Description
Long addition
Syntax
; pointer to left in x register
; right in a register
call c_lgadc
; result in left
Function
c_lgadc performs the long addition of the unsigned char value in the a
register and the long value pointed at by the x register.
Return Value
The result is stored at the location in the x register. Flags are not mean-
ingful upon return.
See Also
c_lgadd, c_pgadc
c_lgadd
Description
Long addition
Syntax
; pointer to left in x register
; right in long register
call c_lgadd
; result in left
Function
c_lgadd performs the long addition of the value pointered by the x reg-
ister and the value in long register.
Return Value
The result is stored at the location pointered by the x register. Flags are
not meaningful upon return.
See Also
c_lgadc
c_lgand
Description
Long bitwise AND
Syntax
; left in long register
; pointer to right in x register
call c_lgand
; result in left
Function
c_lgand performs the long bitwise AND of the value in long register
and the value pointered by the x register.
Return Value
The result is stored in long register. Flags are not meaningful upon
return.
c_lglsh
Description
Long shift left
Syntax
; pointer to long in x register
; shift count in a register
call c_lglsh
; result in memory
Function
c_lglsh performs the long left shift of the value pointered by the x regis-
ter by the bit count in the a register. No check is done against silly
counts.
Return Value
The result is stored in the location pointered by x. Flags are not mean-
ingful upon return.
c_lgmul
Description
Long multiplication in memory
Syntax
; pointer to left in x register
; right in long register
call c_lgmul
; result in left
Function
c_lgmul performs the long multiplication of the value pointered by the x
register, by the value in long register.
Return Value
The result is stored in the location pointered by x. Flags are not mean-
ingful upon return.
See Also
c_lmul
c_lgneg
Description
Negate a long integer in memory
Syntax
; pointer to operand in x register
call c_lneg
; result in memory
Function
c_lgneg negates the four byte integer pointered by the x register.
Return Value
The result is in the location pointered by x. The flags are not meaning-
ful upon return.
See Also
c_lneg
c_lgor
Description
Long bitwise OR
Syntax
; pointer to left in x register
; right in long register
call c_lgor
; result in left
Function
c_lgor performs the long bitwise OR of the value in long register and
the value pointered by the x register.
Return Value
The result is stored in long register. Flags are not meaningful upon
return.
c_lgrsh
Description
Signed long shift right
Syntax
; pointer to long in x register
; shift count in a register
call c_lgrsh
; result in memory
Function
c_lgrsh performs the signed long right shift of the value pointered by
the x register and the value in long register. No check is done against
silly counts. Because the value is signed, arithmetic shift instructions
are used.
Return Value
The result is stored in the location pointered by x. Flags are not mean-
ingful upon return.
c_lgsbc
Description
Long subtraction
Syntax
; pointer to left in x register
; right in a register
call c_lgsbc
; result in left
Function
c_lgsbc evaluates the (long) difference between the value pointered by
the x register and the unsigned char value in the a register.
Return Value
The result is stored in the location pointered by x. Flags are not mean-
ingful upon return.
See Also
c_lgsub
c_lgsub
Description
Long subtraction
Syntax
; pointer to left in x register
; right in long register
call c_lgsub
; result in left
Function
c_lgsub evaluates the (long) difference between the value pointered by
the x register and the value in long register.
Return Value
The result is stored in the location pointered by x. Flags are not mean-
ingful upon return.
See Also
c_lgsbc
c_lgursh
Description
Unsigned long shift right
Syntax
; pointer to long in x register
; shift count in a register
call c_lgursh
; result in memory
Function
c_lgursh performs the unsigned long right shift of the value pointered
by the x register and the value in long register. No check is done against
silly counts. Because the value is unsigned, logical shift instructions are
used.
Return Value
The result is stored in the location pointered by x. Flags are not mean-
ingful upon return.
c_lgxor
Description
Long bitwise exclusive OR
Syntax
; pointer to right in x register
; left in long register
call c_lgxor
; result in left
Function
c_lgxor performs the long bitwise Exclusive OR of the value in long
register and the value pointered by the x register.
Return Value
The result is stored in long register. Flags are not meaningful upon
return.
c_llsh
Description
Long integer shift left
Syntax
; operand in long register
; shift count in a register
call c_llsh
; result in long register
Function
c_llsh shifts left four byte integer in long register by the number of
places specified by the a register. A zero count leaves the long register
unchanged. No check is made for invalid counts.
Return Value
The resulting value is in long register. Flags are not meaningful upon
return.
See Also
c_lrsh, c_lursh
c_lmod
Description
Remainder of long integer division
Syntax
; left in long register
; pointer to right in x register
call c_lmod
; remainder in long register
Function
c_lmod divides the four byte integer in long register by the four byte
integer pointered by the x register. Values are assumed to be signed.
The dividend is returned if a division by zero is attempted.
Return Value
The remainder is stored in long register. Flags are not meaningful upon
return.
See Also
c_lumd, c_ldiv, c_udiv
c_lmul
Description
Multiply long integer by long integer
Syntax
; left in long register
; pointer to right in x register
call c_lmul
; result in long register
Function
c_lmul multiplies the four byte integer in long register by the four byte
integer pointered by the x register. No check is made for overflow.
Return Value
The resulting value is in long register. Flags are not meaningful upon
return.
See Also
c_lgmul
c_lneg
Description
Negate a long integer
Syntax
; operand in long register
call c_lneg
; result in long register
Function
c_lneg negates the four byte integer in long register.
Return Value
The result is in long register. The flags are not meaningful upon return.
See Also
c_lgneg
c_lor
Description
Bitwise OR with long integers
Syntax
; left in long register
; pointer to right in x register
call c_lor
; result in long register
Function
c_lor operates a bitwise OR between the contents of long register and
the long pointered by the x register. Each operand is taken to be a four
byte integer.
Return Value
The result is in long register. The flags are not meaningful upon return.
See Also
c_land, c_lxor
c_lrsh
Description
Long integer right shift
Syntax
; operand in long register
; shift count in a register
call c_lrsh
; result in long register
Function
c_lrsh right shifts the four byte integer in long register by the number of
bits specified by the a register. A zero count leaves the long register
unchanged. No check is made for invalid counts. The value is assumed
to be signed, so a negative value will stay negative as by an arithmetic
shift.
Return Value
The resulting value stays in long register. Flags are not meaningful
upon return.
See Also
c_llsh, c_lursh
c_lrzmp
Description
Long test against zero
Syntax
; operand in long register
call c_lrzmp
; result in the flags
Function
c_lrzmp tests the value in the long register and updates the sign and
zero flags.
Return Value
Nothing, but the flags.
See Also
c_lzmp
c_lsbc
Description
Long integer subtraction
Syntax
; left in long register
; right in a register
call c_lsbc
; result in long register
Function
c_lsbc subtracts the unsigned char in the a register from the four byte
integer in long register.
Return Value
The result is in long register. Flags are not meaningful upon return.
See Also
c_lsub
c_lsub
Description
Long integer subtraction
Syntax
; left in long register
; pointer to right in x register
call c_lsub
; result in long register
Function
c_lsub subtracts the four byte integer pointered by the x register from
the four byte integer in long register.
Return Value
The result is in long register. Flags are not meaningful upon return.
See Also
c_ladd, c_lcmp
c_lsmp
Description
Long integer compare with overflow
Syntax
; left in long register
; pointer to right in x register
call c_lsmp
; result in long flags
Function
c_lsmp compares the four byte integer in long register to the four byte
integer pointered by the x register and updates the resulting flags in case
of overflow.
Return Value
Flags are set accordingly.
See Also
c_ladd, c_lsub, c_lcmp
c_ltof
Description
Convert long integer into float
Syntax
; operand in float integer
call c_ltof
; result in float register
Function
c_ltof converts the four byte integer in float register to a float.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return.
See Also
c_ftoi, c_ftol, c_itof, c_itol
c_ltor
Description
Load memory into long register
Syntax
; pointer to operand in x register
call c_ltor
; result in float register
Function
c_ltor loads the four byte integer pointered by the x register into the
long register.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return.
See Also
c_rtol
c_ludv
Description
Quotient of unsigned long integer division
Syntax
; left in long register
; pointer to right in x register
call c_ludv
; quotient in long register
Function
c_ludv divides the four byte integer in long register by the four byte
integer pointered by the x register. Values are assumed to be unsigned.
The dividend is returned if a division by zero is attempted.
Return Value
The quotient is in long register. Flags are not meaningful upon return.
See Also
c_ldiv, c_lmod, c_lumd
c_lumd
Description
Remainder of unsigned long integer division
Syntax
; left in long register
; pointer to right in x register
call c_lumd
; remainder in long register
Function
c_lumd divides the four byte integer in long register by the four byte
integer pointered by the x register. Values are assumed to be unsigned.
The dividend is returned if a division by zero is attempted.
Return Value
The remainder is in long register. Flags are not meaningful upon return.
See Also
c_lmod, c_ldiv, c_ludv
c_lursh
Description
Unsigned long integer shift right
Syntax
; operand in long register
; shift count in a register
call c_lursh
; result in long register
Function
c_lursh right shifts the four byte integer in long register by the number
of bits specified by the a register. A zero count leaves the long register
unchanged. No check is made for invalid counts. The value is assumed
to be unsigned. The shift instruction used is therefore a logical shift.
Return Value
The resulting value is in long register. Flags are not meaningful upon
return.
See Also
c_llsh, c_lrsh
c_lxor
Description
Bitwise exclusive OR with long integers
Syntax
; left in long integer
; pointer to right in x register
call c_lxor
; result in long register
Function
c_lxor operates a bitwise Exclusive OR between the contents of long
register and the long pointered by the x register. Each operand is taken
to be a four byte integer.
Return Value
The result is in long register. The flags are not meaningful upon return.
See Also
c_land, c_lor
c_lzmp
Description
Compare a long integer to zero
Syntax
; pointer to operand in x register
call c_lzmp
; result in the flags
Function
c_lzmp compares the four byte integer pointered by the x register to
zero.
Return Value
Nothing, but the flags.
See Also
c_lrzmp
c_pgadc
Description
Far pointer addition
Syntax
; pointer to left in x register
; right in a register
call c_pgadc
; result in left
Function
c_pgadc performs the long addition of the unsigned char value in the a
register and the far pointer pointed at by the x register.
Return Value
The result is stored at the location in the x register. Flags are not mean-
ingful upon return.
See Also
c_lgadd, c_lgadc
c_pgadd
Description
Far pointer addition
Syntax
; pointer to left in x register
; right in long register
call c_pgadd
; result in left
Function
c_pgadd performs the long addition of the value in long register and the
far pointer pointed at by the x register.
Return Value
The result is stored at the location in the x register. Flags are not mean-
ingful upon return.
See Also
c_lgadd, c_lgadc
c_putlx
Description
Put a long integer in memory
Syntax
; long address in x
; value in long register
call c_putlx
Function
c_putlx puts the value in long register into memory using a pointer
loaded in x.
Return Value
None.
See Also
c_getlx, c_getwx, c_putly, c_putw
c_putly
Description
Put a long integer in memory
Syntax
; long address in y
; value in long register
call c_putly
Function
c_putly puts the value in long register into memory using a pointer
loaded in y.
Return Value
None.
See Also
c_getly, c_getwy, c_putlx, c_putw
c_putwf
Description
Put a word in far memory
Syntax
; word address in y and c_y
; value in a and xl
call c_putwf
Function
c_putwf puts the value in a and xl registers into far memory using a
pointer loaded in y and c_y.
Return Value
None.
See Also
c_getlx, c_getly, c_getw, c_putlx, c_putly
c_pxtox
Description
Get a far pointer from far memory
Syntax
; far pointer address in x and c_x
call c_pxtox
; result in x and c_x
Function
c_pxtox gets a far pointer from far memory using a pointer loaded in x
and c_x. The result is left in the x and c_x.
Return Value
The far pointer is loaded in the x register and the c_x memory location.
Flags have no meaningful value upon return.
See Also
c_pxtoy, c_pytox, c_pytoy
c_pxtoy
Description
Get a far pointer from far memory
Syntax
; far pointer address in x and c_x
call c_pxtoy
; result in y and c_y
Function
c_pxtoy gets a far pointer from far memory using a pointer loaded in x
and c_x. The result is left in the y and c_y.
Return Value
The far pointer is loaded in the y register and the c_y memory location.
Flags have no meaningful value upon return.
See Also
c_pxtox, c_pytox, c_pytoy
c_pytox
Description
Get a far pointer from far memory
Syntax
; far pointer address in y and c_y
call c_pytox
; result in x and c_x
Function
c_pytox gets a far pointer from far memory using a pointer loaded in y
and c_y. The result is left in the x and c_x.
Return Value
The far pointer is loaded in the x register and the c_x memory location.
Flags have no meaningful value upon return.
See Also
c_pxtox, c_pxtoy, c_pytoy
c_pytoy
Description
Get a far pointer from far memory
Syntax
; far pointer address in y and c_y
call c_pytoy
; result in y and c_y
Function
c_pytoy gets a far pointer from far memory using a pointer loaded in y
and c_y. The result is left in the y and c_y.
Return Value
The far pointer is loaded in the y register and the c_y memory location.
Flags have no meaningful value upon return.
See Also
c_pxtox, c_pxtoy, c_pytox
c_rtofl
Description
Store long register in far memory
Syntax
; pointer to destination in x register and c_x
; operand in long integer
call c_rtofl
Function
c_rtofl store the four byte integer in long register into the memory loca-
tion pointered by the x register and c_x.
Return Value
The resulting value is in the memory location pointered by x and c_x.
Flags have no meaningful value upon return.
See Also
c_fltor
c_rtol
Description
Store long register in memory
Syntax
; pointer to destination in x register
; operand in long integer
call c_rtol
Function
c_rtol store the four byte integer in long register into the memory loca-
tion pointered by the x register.
Return Value
The resulting value is in the memory location pointered by x. Flags
have no meaningful value upon return.
See Also
c_ltor
c_sdivx
Description
Quotient of signed char division
Syntax
; dividend in x register
; divisor in a register
call c_sdivx
; quotient in x
Function
c_sdivx divides the signed integer in x by the signed byte in the a regis-
ter. Values are assumed to be signed. If division by zero is attempted,
the result is the unchanged dividend.
Return Value
The quotient is in x. Flags are not meaningful upon return.
See Also
c_cdivx, c_cdivy, c_sdivy
c_sdivy
Description
Quotient of signed char division
Syntax
; dividend in y register
; divisor in a register
call c_sdivy
; quotient in y
Function
c_sdivy divides the signed integer in y by the signed byte in the a regis-
ter. Values are assumed to be signed. If division by zero is attempted,
the result is the unchanged dividend.
Return Value
The quotient is in y. Flags are not meaningful upon return.
See Also
c_cdivx, c_cdivy, c_sdivy
c_smodx
Description
Remainder of signed char division
Syntax
; dividend in x register
; divisor in a register
call c_smodx
; remainder in x
Function
c_smodx divides the signed integer in x by the signed byte in the a reg-
ister. Values are assumed to be signed. If division by zero is attempted,
the result is the unchanged dividend.
Return Value
The remainder is in x. Flags are not meaningful upon return.
See Also
c_smody
c_smody
Description
Remainder of signed char division
Syntax
; dividend in y register
; divisor in a register
call c_smody
; remainder in y
Function
c_smody divides the signed integer in y by the signed byte in the a reg-
ister. Values are assumed to be signed. If division by zero is attempted,
the result is the unchanged dividend.
Return Value
The remainder is in y. Flags are not meaningful upon return.
See Also
c_smodx
c_smul
Description
Multiply long integer by unsigned byte
Syntax
; left in long register
; right byte in a register
call c_smul
; result in long register
Function
c_smul multiplies the four byte integer in long register by the unsigned
byte in the a register. No check is made for overflow.
Return Value
The resulting value is in long register. Flags are not meaningful upon
return.
See Also
c_lgmul
c_uitof
Description
Convert unsigned integer into float
Syntax
; operand in x
call c_uitof
; result in float register
Function
c_uitof converts the two byte unsigned integer in the x register to a float
stored in float register.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return.
See Also
c_itof, c_ltof, c_ultof, c_xtof, c_uxtof
c_uitol
Description
Convert unsigned integer into long
Syntax
; operand in a and xl
call c_uitol
; result in long register
Function
c_uitol converts the two byte unsigned integer in the a and xl register
pair, to a long integer stored in long register.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return.
See Also
c_itol, c_xtol, c_uxtol
c_uitolx
Description
Convert unsigned integer into long
Syntax
; operand in x
call c_uitolx
; result in long register
Function
c_uitolx converts the two byte unsigned integer in the x register, to a
long integer stored in long register.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return.
See Also
c_itol, c_xtol, c_uxtol
c_uitoly
Description
Convert unsigned integer into long
Syntax
; operand in y
call c_uitoly
; result in long register
Function
c_uitoly converts the two byte unsigned integer in the y register, to a
long integer stored in long register.
Return Value
The resulting value is in long register. Flags have no meaningful value
upon return.
See Also
c_itol, c_xtol, c_uxtol
c_ultof
Description
Convert unsigned long integer into float
Syntax
; long in long register
call c_ultof
; result in float register
Function
c_ultof converts the four unsigned byte integer in long register to a
float.
Return Value
The resulting value is in float register. Flags have no meaningful value
upon return.
See Also
c_itof, c_ltof, c_xtof, c_uitof, c_uxtof
c_umul
Description
Multiply unsigned integers with long result
Syntax
; left in x register
; right in y register
call c_umul
; result in long register
Function
c_umul multiplies the two byte unsigned integer in the x register by the
two byte unsigned integer in the y register.
Return Value
The resulting value is in long register. Flags are not meaningful upon
return.
See Also
c_vmul
c_vmul
Description
Multiply signed integers with long result
Syntax
; left in x register
; right in y register
call c_vmul
; result in long register
Function
c_vmul multiplies the two byte signed integer in the x register by the
two byte signed integer in the y register.
Return Value
The resulting value is in long register. Flags are not meaningful upon
return.
See Also
c_umul
c_xtopy
Description
Store a far pointer into far memory
Syntax
; value in x and c_x
; far pointer address in y and c_y
call c_xtopy
Function
c_xtopy stores the far pointer in x and c_x into far memory using a
pointer loaded in y and c_y.
Return Value
Flags have no meaningful value upon return.
See Also
c_ytopx
c_xymov
Description
Copy a structure into another
Syntax
; pointer to source in y
; pointer to destination in x
; size in a register
call c_xymov
Function
c_xymov copy the source structure pointed by the memory location y
into the structure pointed by the x register. The structure size is located
in the a register.
Return Value
None.
See Also
c_xymov, c_yxmov, c_xymvx, c_yxmvx
c_xymvf
Description
Copy a structure in far memory
Syntax
; pointer to source in y and c_y
; pointer to destination in x and c_x
; size in a
call c_xymvf
Function
c_xymvf copy the source structure pointed by the y register and the
memory location pointed by c_y into the structure pointed by the x reg-
ister and the memory location pointed by c_x. The structure size is in
the a register.
Return Value
None.
See Also
c_xymov, c_yxmov, c_xymvy
c_xymvfl
Description
Copy a large structure in far memory
Syntax
; pointer to source in y and c_y
; pointer to destination in c_x
; size in x
call c_xymvfl
Function
c_xymvfl copy the source structure pointed by the y register and the
memory location pointed by c_y into the structure pointed by the mem-
ory location pointed by c_x. The structure size is in the x register.
Return Value
None.
See Also
c_xymov, c_yxmov, c_xymvy
c_xymvx
Description
Copy a structure into another
Syntax
; pointer to source in y
; pointer to destination in x
; size in a register
call c_xymvx
Function
c_xymvx copy the source structure pointed by the memory location y
into the structure pointed by the x register. The structure size is located
in the a register.
Return Value
None.
See Also
c_xymov, c_yxmov, c_xymvx, c_yxmvx
c_xymvxl
Description
Copy a large structure into another
Syntax
; pointer to source in y
; pointer to destination in c_x
; size in x register
call c_xymvxl
Function
c_xymvxl copy the source structure pointed by the memory location y
into the structure pointed by the c_x memory location. The structure
size is located in the x register.
Return Value
None.
See Also
c_xymov, c_yxmov, c_xymvx, c_yxmvx
c_ytopx
Description
Store a far pointer into far memory
Syntax
; value in y and c_y
; far pointer address in x and c_x
call c_ytopx
Function
c_ytopx stores the far pointer in y and c_y into far memory using a
pointer loaded in x and c_x.
Return Value
Flags have no meaningful value upon return.
See Also
c_xtopy
c_yxmov
Description
Copy a structure into another
Syntax
; pointer to source in x
; pointer to destination in y
; size in a
call c_yxmov
Function
c_yxmov copy the source structure pointed by the x register into the
structure pointed by the y register. The structure size is in the a register.
Return Value
None.
See Also
c_xymov, c_xymvx, c_yxmvx
c_yxmvf
Description
Copy a structure in far memory
Syntax
; pointer to source in x and c_x
; pointer to destination in y and c_y
; size in a
call c_yxmvf
Function
c_yxmvf copy the source structure pointed by the x register and the
memory location pointed by c_x into the structure pointed by the y reg-
ister and the memory location pointed by c_y. The structure size is in
the a register.
Return Value
None.
See Also
c_xymov, c_yxmov, c_xymvy
c_yxmvfl
Description
Copy a large structure in far memory
Syntax
; pointer to source c_x
; pointer to destination in y and c_y
; size in x
call c_yxmvfl
Function
c_yxmvfl copy the source structure pointed by the memory location
pointed by c_x into the structure pointed by the y register and the mem-
ory location pointed by c_y. The structure size is in the x register.
Return Value
None.
See Also
c_xymov, c_yxmov, c_xymvy
c_yxmvx
Description
Copy a structure into another
Syntax
; pointer to source in x
; pointer to destination in y
; size in a
call c_yxmvx
Function
c_yxmvx copy the source structure pointed by the x register into the
structure pointed by the y register. The structure size is in the a register.
Return Value
None.
See Also
c_xymov, c_xymvx, c_yxmvx
c_yxmvxl
Description
Copy a large structure into another
Syntax
; pointer to source in c_x
; pointer to destination in y
; size in x
call c_yxmvxl
Function
c_yxmvxl copy the source structure pointed by the c_x memory location
into the structure pointed by the y register. The structure size is in the x
register.
Return Value
None.
See Also
c_xymov, c_xymvx, c_yxmvx
Compiler Passes
The information contained in this appendix is of interest to those users
who want to modify the default operation of the cross compiler by
changing the configuration file that the cxstm8 compiler uses to control
the compilation process.
+e* log errors in the text file * instead of displaying the mes-
sages on the terminal screen.
-ge produce error messages directly compatible with the
Eclipse environment
-h*> include files before to start the compiler process. You can
specify up to 128 files.
0x10 @tiny
0x20 @near
0x30 @far
0x01 @pack
0x04 @nostack
Note that all the combinations are not significant for all the
target processors.
-nb do not pack bitfields. By default, trailing unused bits in the
last bitfield of a structure are removed if this saves at least
one byte.
Warning Levels
The option enabling warnings also allows to define a minimum level
which reduces the amount of warning produced. They are grouped on 7
levels depending on their effects on the resulting code from the smallest
(1) to the highest (7). The +warn compiler option activates warning
from level 1. To activate warnings from a different level, the -pw#
option can be used, where # is a starting level.
The list of warning messages is shared with the extra verifications ones
described in the next paragraph along with their associated level dis-
played between parenthesis.
Extra verifications
This paragraph describes the checkings done by the -ck parser option
(+strict compiler option) or when warnings are enabled (+warn or
-pw# compiler option) according to the error message produced.
float value too large for integer cast (level 1) - a float constant is cast
to an integer or a long but is larger than the maximum value of the cast
type.
shift count out of range (level 2) - a shift count is larger than the bit
size of the shifted expression.
<variable> used before set (level 7) - a local variable has been used
before beeing initialized by an explicit assignment.
Return Status
cpstm8 returns success if it produces no error diagnostics.
Example
cpstm8 is usually invoked before cgstm8 the code generator, as in:
-na do not produce an xdef directive for the equate names cre-
ated for each C object declared with an absolute address.
-nc do not allow functions to cross a section boundary.
-o* write the output to the file * and write error messages to
STDOUT. The default is STDOUT for output and STDERR
for error messages.
-sf produce each function in a different section, thus allowing
the linker to suppress a function if it is not used by the appli-
cation. By default, all the functions are packed in a single
section.
-v When this option is set, each function name is send to
STDERR when cgstm8 starts processing it.
Return Status
cgstm8 returns success if it produces no diagnostics.
Example
cgstm8 usually follows cpstm8 as follows:
Disabling Optimization
When using the optimizer with the -c option, lines which are changed or
removed are kept in the assembly source as comment, followed by a
code composed with a letter and a digit, identifying the internal func-
tion which performs the optimization. If an optimization appears to do
something wrong, it is possible to disable selectively that function by
specifying its code with the -d option. Several functions can be disabled
by specifying a list of codes without any whitespaces. The code letter
can be enter both lower or uppercase.
Return Status
costm8 returns success if it produces no diagnostics.
Example
costm8 is usually invoked after cgstm8 as follows:
Symbols @interrupt
#asm function 59
directive 474 qualifier 59
#asm directive 55 @near
#endasm .data,.bss sections 53
directive 474 function 41
#endasm directive 55 modifier 50, 62
#pragma modifier,mods 39
asm directive 55 modifier,mods0 39
directive for inlining 55 pointer,size 39
endasm directive 55 variable 62
space directive 49 @near type qualifier 25
+dep @noprd qualifier 60
linker dependency directive 278 @nosvf qualifier 59
+grp directive 273 @svlreg qualifier 59
+modsl memory model 17 @tiny
+seg option 269 .bsct,.ubsct sections 53
.bsct section 183 modifier 49
.const modifier,modsl 40
output section 481 modifier,modsl0 39
segment 280 space modifier 62
@eeprom variable 62
type qualifier 12, 51 @vector modifier 60
@far __ckdesc__l 289
.fconst section 41 __CSMC__ 191
.fdata section 41, 53 __idesc__ 285, 286
function 41, 62 _asm
modifier 39, 62 argument string length 57
pointer,size 39 argument string size 57
@inline assembly sequence 56
functions 61 code optimization 480
modifier 61 in expression 57
Index 1
lowercase mnemonics 57 symbol in library 319
return type 57 symbol table 267
uppercase mnemonics 57 symbol tables 296
_asm() symbol,flagged 296
function 84 absolute section 238, 248
inserting assembler function 80 acos function 87
_Bool address
assign expression to 42 default format 313, 317
consecutive fields 42 logical end 271
data 62 logical start segment 279
pack local variable 476 logical start set 271
packed variables 42 paged format 313, 317
referencing absolute address 46 physical 271
type name 42 physical end 269
variable 42 physical start 269
_checkcrc16 function 96 physical start segment 279
_checkcrc16x function 97 set logical 271
_checksum function 98 align directive 197
_checksum16 function 100 allocate memory block 202
_checksum16x function 101 allocate storage for constants 201
_checksumx function 99 application
_fctcpy function 111 embedded 262
_sbreak function 65 non-banked 314
system bootstrap 262
Numerics Arccosine 87
8-bit precision,operation 11 Arcsine 88
Arctangent 89
A Arctangent of y/x 90
abort function 85 argument
abs function 86 formatted output to buffer 154
absolute formatted output to stdout 144
address 304 asin function 88
address in listing 316 assembler
full path name 477 branch shortening 194
hex file generator 10 C style directives 196
listing file 316 code inline 56
listing utility 10 conditional branch range 194
map section 178 conditional directive 191
path name 477 create listing file 179
reference address 46 debug information
section relocation 279 add line 180
symbol 272 label 180
2 Index
endm directive 188 address 193
expression 186 address value 280
filling byte 179, 197 allocated section 194
include directive 194 attribute section 193
label 183 define aliases 276
listing process 316 number 280
listing stream 181 segment 280
macro bit segment
instruction 188 initialization 281
macro argument 188 bitfield
macro directive 188 compiler reverse option 77
macro parameter 188 default order 476
old syntax 195 filling 476
operator set 186 filling order 77
preprocessing 74 reverse order 476
section name 192 sign check 474
section predefinition 192 bootloader 286
sections 192 boundary
special parameter \# 189 round up 271
special parameter \* 190 bsct directive 199
special parameter \0 190 buffer
switch directive 192 convert to double 91, 170
xbit directive 255 convert to integer 92
assembly language convert to long 93, 171
code optimizer 483 convert to unsigned long 172
atan function 89 copy from one to another 138, 139
atan2 function 90 copy to eeprom 105
atof function 91
atoi function 92 C
atol function 93 C interface
extra character for far function 62
B underscore character prefix 62
bank C interface to assembly language 62
automatic segment creation 272 C library
default mode 328 floating point functions 81
size setting 269 integer functions 80
switched system 279 macro functions 81
base directive 198 package 80
bias C source
segment parameter 279 lines merging 481
setting 280 c_ prefix 361
bit c_lreg
Index 3
memory byte 59 assembler option specification 74
c_x C preprocessor and language parser 8
memory byte 59 code generation option specification
c_y 75
memory byte 59 code generator 9
call code optimization 11
instruction 481 code optimizer 9
callf combination of options 358
instruction 481 command line option 72
carry function 94 configuration file 356
casting 474 configuration file specification 74
ceil function 95 configuration file,predefined option
char 76
signed 477 create assembler file only 75
unsigned 477 debug information,produce 76
character default behavior 72
fill throughout eeprom buffer 107 default configuration file 74
underscore,start 67 default file names 78
checksum default operations 471
-ck option 289 default options 72, 356
crc 290 driver 4
functions 289 error files path specification 74
-ik option 290 error message 72
clabs utility 316 exclusive options 358
clib utillity 319 flags 6
clist directive 200, 215, 217, 218, 219, generate error 331
220, 221, 222, 223, 224, 225 generate error file 79
clst utility 308 generate listing 79
cobj utility 322 header files 82
code include path definition 75
factorization 76, 483 invoke 72
smaller 76 listing file 75
code generator listing file path specification 74
compiler pass 480 log error file 74
error log file 481 name 72
code optimizer object file path specification 74
compiler pass 483 optimizer option specification 75
code/data, no output 269 options 72
compare for lexical order 164 options request 72
compiler parser option specification 75
ANSI checking 477 predefined option selection 76
assembler 9 preprocessed file only 75
4 Index
produce assembly file 19 @near modifier 21
produce listing file 19 @near pointer representation 69
programmable option 356, 358 @tiny modifier 21
specific options 4 @tiny pointer representation 69
specify options 73 automatic initialization 36
stack long model option 76 char representation 69
stack short model option 76 float representation 69
temporary files path 75 initalized 48
type checking 77, 474 initialization 25
user-defined preprocessor symbol 74 int representation 69
verbose mode 20, 75 long int representation 69
compute 173 short int representation 69
const data object
@near memory space 44 automatic 306
data 43 scope 304
qualifier 43 type 304
constant dc directive 201
in .text section 481 dcb directive 202
numeric 185 debug information
prefix character 185 adding 477
string 185 debug symbol
string character 186 build table 291
suffix character 185 in object file 181
convert table 304
ELF/DWARF format 326 debugging
hex format 312 data 304
copy 150 support tools 303
cos function 102 debugging information
cosh function 103 data object 304
count space name extract 306
definition 269 generate 304, 477
cprd utility 306 line number 304
cross-reference print file 306
information 179 print function 306
table in listing 182 default base for numerical constants 198
ctat utility 324 default placement
cvdwarf utility 326 .bit segment 280
.bsct segment 280
D .bss segment 280
d_ prefix 361 .data segment 280
data .text segment 280
@far modifier 21 definition 291
@far pointer representation 69 DEFs 291
Index 5
dependency message list 331
between function 278 multiply defined symbol 184, 295
descriptor undefined symbol 292
host to 270 undefined symbol in listing 180
div function 104 error message 214
dlist directive 203 even directive 213
ds directive 204 executable image 312
exit 108
E exp function 109
Eclipse expression
error messages 74, 179, 267, 474, defined 187
481 evaluation 187
eepcpy function 105 high 187
eepera function 106 low 187
Eeprom page 187
STM8L library 283
eeprom F
@near modifier 51 fabs function 110
erase 106 fail directive 214
location 12, 51 faster code
eeprom support production 481
STM8L 52 file length restriction 304
eepset function 107 filling byte 204, 213, 238
ELF/DWARF float
format converter 10 single precision library 282
else directive 205, 206, 209, 215, 217, floating point library
223 link 80
end directive 207 Floating Point Library Functions 81
end5 directive 211 floor function 112
endc directive 217, 223 fmod function 113
endif directive 205, 208, 209, 215 format
endm directive 210, 230, 233, 245 ELF/DWARF 326
endr 241, 242 frexp function 114
enum function
size optimization 476 @inline modifier 61
environment symbol 194 arguments 306
equ directive 212, 250 enforce prototype declaration 77,
error 476
assembler log file 179 in separate section 77
file name 79 prototype declaration 77, 476
log file 267 recursive 297
message 11 returning int 83
6 Index
suppress 482 ifdef directive 217
suppress unused 77 ifeq directive 218
function arguments 306 ifge directive 219
Functions Implemented as Macros 81 ifgt directive 220
ifle directive 221
G iflt directive 222
generate ifnc directive 225
.bsct section 62 ifndef directive 223
hex record 271 ifne directive 224
in .bit section 62 imask function 117
in .bss section 62 include
in .const section 62 directory names list 75, 179, 475
in .data section 62 file 274
in .fconst section 62 file before 474
in .fdata section 62 module 282
in .text section 62 object file 274
in .ubsct section 62 path specification 475
listing file 181 specify path 475
object file 181 include directive 226
getchar function 115 initialization
gets function 116 automatic 285
group define option 270
option 264 descriptor 285
descriptor address 286
H descriptor format 285
heap first segment 285
allocation 65 initialized segments 285
location 67 marker 270
name 65 startup routine 286
pointer 65 initialize storage for constants 201
size 65 inline
stack 65 assembly code 55, 56
start 65 block inside a function 55
top 65 block outside a function 55
-help option 7 carry function 61
function 61
header function 82
I imask function 61
IEEE
irq function 61
Floating Point Standard 69
machine library calls 76, 481
if directive 205, 209, 215
produce faster code 76
if directive 208
with _asm function 56, 57
ifc directive 216
Index 7
with pragma sequences 55 machine 80
input and output 45 path specification 267
input to output 150 replace file 320
input/output 46 scanned 265
integer single precision 282
library 282 Standard ANSI 282
interrupt version 282
function 60 line number
function in map 297 information 481
handler 59 link
hardware 59 command file 266
software 59 user command file 22
vectors table 60 linker
irq function 118 # character prefix,comment 265
isalnum function 119 build freestanding program 262
isalpha function 120 clnk 9
iscntrl function 121 command file 264
isdigit function 122 command file example 300
isgraph function 123 command item 264
islower function 124 comment 265
isprint function 125 global command line options 267
ispunct function 126 output file 263
isspace function 127 physical memory 263
isupper function 128 list directive 227
isxdigit function 129 listing
cross reference 20
L file location 28
labs function 130 file path specification 316
ldexp function 131 interspersed C and assembly file 19
ldiv function 132 lit directive 228
library literals
build and maintain 10 in @near space 62
building and maintaining 319 local
create 319 labels 58
delete file 319 local directive 184, 229
extract file 320 local variable
file 282 reorder 477
floating point 80 locate source file 309
integer 80, 282 log function 133
list file 320 log10 function 134
load all files 320 long multiplication 410
load modules 265
8 Index
M moveable code segment 111
macro
exit 190 N
expansion in listing 190 named syntax, example 231, 242
internal label 184 new
named syntax 189 segment control 264
numbered syntax 189 start region 275
macro directive 230 nolist directive 235
main nopage directive 236
function 297 numbered syntax, example 231, 242
main() routine 35
map O
call tree section 297 object
count section 297 file location 28
file description 297 image 261
modules section 297 module 262
produce information 267 module inspector 10
segment section 297 relocatable 322
stack usage section 297 relocatable file output 181
symbols section 297 relocatable file size 322
max function 135 size 322
memchr function 136 offset
memcmp function 137 segment parameter 279
memcpy function 138 setting 280
memmove function 139 offset directive 237
memory optimization
location 46 disable selectively 484
long range 50 keep line 484
mapped I/O 46 specific code 483
memory models 13, 39 option
memset function 140 global 266
messg directive 232 org directive 238
mexit directive 231, 233 output
min function 141 default format 313
mlist directive 234, 247 file name 266
modf function 142 listing line number 475
Motorola specify format 144
S-Records format 313 override
standard S-record,generating 23 data bias 312
moveable text bias 312
code section 286
function used 286
Index 9
P relative address 304
page repeat directive 241
address extension 187 repeatl directive 242
value 187, 314 restore directive 244
page directive 239 rexit directive 242, 245
page header 254 ROM 46
paginating output 309 runtime startup
parser modifying 34
behaviour 475
compiler pass 472 S
error log file 474 save directive 246
plen directive 240 section
pointer .bit 21, 42
narrow 476 .bsct 21, 49
pow function 143 .bss 21, 50
prefix .const 21
filename 477 .data 21, 50
modules 320 .eeprom 21, 51
preprocessor .fconst 21
#define 472 .fdata 21
#include 472 .info. 180, 181, 267, 322
run only 474 .text 21
printf function 144 .ubsct 21, 49
private name region assembler directive 248
use 292 crossing boundary 41
program curly braces,initialized data 53
stop execution of 108 definition 261
putchar function 149 name 54
puts function 150 parenthesis,code 53
pragma definition 53
R pragma directive 54
rand function 151 single 482
range specification 309 square brackets, uninitialized data 53
redirect output 309 unused 270
REFs 291 user defined 53
region sections
name 264 default 53
private 275 predefined 53
public 275 relocation 279
use of private name 292 segment
register .debug 298
input/output 48 .info. 299
10 Index
bsct start address 273 sqrt function 155
bss start address 273 srand function 156
build new 282 stack
control options 266, 269 amount of memory 297
data start address 273 check overflow 481
definition 261 need 297
fill 270 stack model
follow current 269 long 40, 50
maximum size 270 long,64K 39
name 271 short 39
overlap checking 272, 279 stack pointer 35
overlapping 282 standard ANSI libraries 282
overlapping control 272 startup file
root 270 crts.sm8 34
round up address 271 crtsi.s 38
section overlap 273 static data 306
space name 279 STM8
start,new 269 addressing mode 183
text start address 273 instruction set 183
zero size 265 ST-Microelectronics syntax 182
separated address space 279 strcat function 157
set directive 250 strchr function 158
share strcmp function 159
local variable 476 strcpy function 160
short addressing 13 strcspn function 161
short range strings 164
@tiny modifier 49 strlen function 162
section 199, 324, 325 strncat function 163
size 39, 40, 49 strncmp function 164
space 325 strncpy function 165
sin function 152 strpbrk function 166
sinh function 153 strrchr function 167
source files listing 308 strspn function 168
source listings 308 strstr function 169
space strtod function 170
for function 475 strtol function 171
for variable 475 strtoul function 172
space name suffix
definition 272 assembly file 72
spc directive 251 C file 72
special operator 187 input 317
sprintf function 154 output 317
Index 11
suffix letter 185 unreachable code
suppress pagination 309 eliminate 11
switch directive 252
symbol V
__endmem 65 variable
__startmem 65 reorder local 477
_endmem 66 -vers option 6
_startmem 66 volatile
alias 293 data 43
define 264 qualifier 43
define alias 276 using keyword 43
define new 276
definition 276 W
export 296 warnings 77, 477
initialization image start, equal 277 wdef directive 258
logical end value,equal 277 weak definition 258
logical start value,equal 277 window
physical end value,equal 277 set shift 267, 326
physical start value,equal 277 size 272
size value,equal 277
sort alphabetically 267
X
sort by address 267
xbit
user-defined 474
assembler directive 193
symbol table
xbit.b
add 276
assembler directive 193
information 322
xdef directive 256, 257
new 291
xref directive 255, 256, 257
T
tab character setting 253
tabs directive 253
tan function 173
tangent 173
tanh function 174
task entries 297
title directive 254
tolower function 175
toupper function 176
translate executable images 312
U
unknown #pragma directives 477
12 Index