C Cross Compiler User’s Guide For STM8 CXSTM8 Users

CXSTM8_UsersGuide

CXSTM8_UsersGuide

CXSTM8_UsersGuide

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 456

DownloadC Cross Compiler User’s Guide For STM8 CXSTM8 Users
Open PDF In BrowserView PDF
C

OSMIC
Soft ware

Version 4.2

C Cross Compiler User’s Guide
for ST Microelectronics STM8

Copyright © COSMIC Software 1995, 2007
All Trademarks are the property of their respective owners

Table of Contents
Preface
Organization of this Manual ....................................................... 1

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................................................... 9
Listings...................................................................................... 10
Optimizations............................................................................ 10
Support for ROMable Code...................................................... 11
Support for eeprom ................................................................... 12
Memory Models........................................................................ 12

Chapter 2
Tutorial Introduction
Acia.c, Example file.................................................................. 14
Default Compiler Operation ............................................... 15
Compiling and Linking............................................................. 17
Step 1: Compiling............................................................... 17
Step 2: Assembler............................................................... 18
Step 3: Linking ................................................................... 19
Step 4: Generating S-Records file ...................................... 21
Linking Your Application......................................................... 23
Generating Automatic Data Initialization................................. 24
Specifying Command Line Options ......................................... 27

Chapter 3
Programming Environments
Introduction............................................................................... 30
Modifying the Runtime Startup ................................................ 32
Description of Runtime Startup Code ................................ 33

(i)

Initializing data in RAM........................................................... 34
Memory Models for code smaller than 64K............................. 37
Memory Models for code larger than 64K ............................... 38
Handling Large Code and Constants ........................................ 39
Bit Variables ............................................................................. 40
The const and volatile Type Qualifiers..................................... 41
Performing Input/Output in C................................................... 43
Referencing Absolute Addresses.............................................. 44
Accessing Internal Registers .................................................... 46
Placing Data Objects in The Bss Section ................................. 47
Placing Data Objects in Short Range Memory......................... 48
Setting Zero Page Size ....................................................... 48
Placing Data Objects in Long Range Memory ......................... 49
Placing Data Objects in the EEPROM Space........................... 50
Redefining Sections.................................................................. 51
Inserting Inline Assembly Instructions..................................... 53
Inlining with pragmas......................................................... 53
Inlining with _asm.............................................................. 54
Inlining Labels.................................................................... 56
Writing Interrupt Handlers ....................................................... 57
Placing Addresses in Interrupt Vectors .................................... 59
Inline Function.......................................................................... 60
Interfacing C to Assembly Language ....................................... 62
Register Usage .......................................................................... 64
Data Representation.................................................................. 65

Chapter 4
Using The Compiler
Invoking the Compiler.............................................................. 68
Compiler Command Line Options ..................................... 69
File Naming Conventions......................................................... 74
Generating Listings................................................................... 75
Generating an Error File ........................................................... 75
Return Status............................................................................. 75
Examples .................................................................................. 75
C Library Support ..................................................................... 76
How C Library Functions are Packaged............................. 76
Inserting Assembler Code Directly .................................... 76
Linking Libraries with Your Program................................ 76
Integer Library Functions................................................... 76
Common Input/Output Functions....................................... 77
Functions Implemented as Macros..................................... 77

(ii)

Including Header Files ....................................................... 78
Descriptions of C Library Functions ........................................ 79
Generate inline assembly code ........................................... 80
Abort program execution.................................................... 81
Find absolute value............................................................. 82
Arccosine............................................................................ 83
Arcsine................................................................................ 84
Arctangent .......................................................................... 85
Arctangent of y/x................................................................ 86
Convert buffer to double .................................................... 87
Convert buffer to integer .................................................... 88
Convert buffer to long ........................................................ 89
Test or get the carry bit....................................................... 90
Round to next higher integer .............................................. 91
Verify the recorded checksum............................................ 92
Verify the recorded checksum............................................ 93
Verify the recorded checksum............................................ 94
Verify the recorded checksum............................................ 95
Cosine ................................................................................. 96
Hyperbolic cosine............................................................... 97
Divide with quotient and remainder ................................... 98
Erase the full eeprom space ................................................ 99
Exit program execution .................................................... 100
Exponential....................................................................... 101
Find double absolute value ............................................... 102
Copy a moveable code segment in RAM ......................... 103
Round to next lower integer ............................................. 104
Find double modulus ........................................................ 105
Extract fraction from exponent part ................................. 106
Get character from input stream ....................................... 107
Get a text line from input stream...................................... 108
Test the interrupt mask bit................................................ 109
Test the interrupt line level............................................... 110
Test for alphabetic or numeric character .......................... 111
Test for alphabetic character ............................................ 112
Test for control character.................................................. 113
Test for digit ..................................................................... 114
Test for graphic character ................................................. 115
Test for lowercase character ............................................. 116
Test for printing character ................................................ 117
Test for punctuation character .......................................... 118
Test for whitespace character ........................................... 119

(iii)

Test for uppercase character............................................. 120
Test for hexadecimal digit................................................ 121
Find long absolute value .................................................. 122
Scale double exponent...................................................... 123
Long divide with quotient and remainder ........................ 124
Natural logarithm ............................................................. 125
Common logarithm .......................................................... 126
Test for maximum ............................................................ 127
Scan buffer for character .................................................. 128
Compare two buffers for lexical order ............................. 129
Copy one buffer to another............................................... 130
Copy one buffer to another............................................... 131
Propagate fill character throughout buffer ....................... 132
Test for minimum............................................................. 133
Extract fraction and integer from double ......................... 134
Raise x to the y power ...................................................... 135
Output formatted arguments to stdout.............................. 136
Put a character to output stream ....................................... 141
Put a text line to output stream......................................... 142
Generate pseudo-random number .................................... 143
Sin..................................................................................... 144
Hyperbolic sine................................................................. 145
Output arguments formatted to buffer.............................. 146
Real square root................................................................ 147
Seed pseudo-random number generator ........................... 148
Concatenate strings........................................................... 149
Scan string for first occurrence of character .................... 150
Compare two strings for lexical order.............................. 151
Copy one string to another ............................................... 152
Find the end of a span of characters in a set..................... 153
Find length of a string ...................................................... 154
Concatenate strings of length n ........................................ 155
Compare two n length strings for lexical order................ 156
Copy n length string ......................................................... 157
Find occurrence in string of character in set .................... 158
Scan string for last occurrence of character ..................... 159
Find the end of a span of characters not in set ................. 160
Scan string for first occurrence of string .......................... 161
Convert buffer to double .................................................. 162
Convert buffer to long ...................................................... 163
Convert buffer to unsigned long....................................... 164
Tangent............................................................................. 165

(iv)

Hyperbolic tangent ........................................................... 166
Convert character to lowercase if necessary .................... 167
Convert character to uppercase if necessary .................... 168

Chapter 5
Using The Assembler
Invoking castm8...................................................................... 170
Object File............................................................................... 172
Listings.................................................................................... 173
Assembly Language Syntax.................................................... 174
Instructions ....................................................................... 174
Labels ............................................................................... 175
Temporary Labels............................................................. 176
Constants .......................................................................... 176
Expressions....................................................................... 178
Macro Instructions............................................................ 179
Conditional Directives...................................................... 182
Sections............................................................................. 183
Bit Handling ..................................................................... 184
Includes............................................................................. 185
Branch Optimization............................................................... 186
Old Syntax .............................................................................. 186
C Style Directives ................................................................... 187
Assembler Directives.............................................................. 187
Align the next instruction on a given boundary ............... 188
Define the default base for numerical constants............... 189
Switch to the predefined .bsct section. ............................. 190
Turn listing of conditionally excluded code on or off...... 191
Allocate constant(s) .......................................................... 192
Allocate constant block .................................................... 193
Turn listing of debug directives on or off......................... 194
Allocate variable(s) .......................................................... 195
Conditional assembly ....................................................... 196
Conditional assembly ....................................................... 197
Stop the assembly ............................................................. 198
End conditional assembly................................................. 199
End conditional assembly................................................. 200
End macro definition ........................................................ 201
End repeat section............................................................. 202
Give a permanent value to a symbol ................................ 203
Assemble next byte at the next even address relative to the
start of a section................................................................ 204

(v)

Generate error message. ................................................... 205
Conditional assembly ....................................................... 206
Conditional assembly ....................................................... 207
Conditional assembly ....................................................... 208
Conditional assembly ....................................................... 209
Conditional assembly ....................................................... 210
Conditional assembly ....................................................... 211
Conditional assembly ....................................................... 212
Conditional assembly ....................................................... 213
Conditional assembly ....................................................... 214
Conditional assembly ....................................................... 215
Conditional assembly ....................................................... 216
Include text from another text file.................................... 217
Turn on listing during assembly....................................... 218
Give a text equivalent to a symbol ................................... 219
Create a new local block .................................................. 220
Define a macro ................................................................. 221
Send a message out to STDOUT...................................... 223
Terminate a macro definition ........................................... 224
Turn on or off listing of macro expansion........................ 225
Turn off listing. ................................................................ 226
Disable pagination in the listing file ................................ 227
Creates absolute symbols ................................................. 228
Sets the location counter to an offset from the beginning of a
section............................................................................... 229
Start a new page in the listing file .................................... 230
Specify the number of lines per pages in the listing file .. 231
Repeat a list of lines a number of times ........................... 232
Repeat a list of lines a number of times ........................... 233
Restore saved section ....................................................... 235
Terminate a repeat definition ........................................... 236
Save section...................................................................... 237
Turn on or off section crossing......................................... 238
Define a new section ........................................................ 239
Give a resetable value to a symbol................................... 241
Insert a number of blank lines before the next statement in the
listing file.......................................................................... 242
Place code into a section. ................................................. 243
Specify the number of spaces for a tab character in the listing
file..................................................................................... 244
Define default header ....................................................... 245
Declare bit symbol as being defined elsewhere ............... 246
Declare a variable to be visible ........................................ 247

(vi)

Declare symbol as being defined elsewhere..................... 248

Chapter 6
Using The Linker
Introduction............................................................................. 251
Overview................................................................................. 252
Linker Command File Processing........................................... 254
Inserting comments in Linker commands ........................ 255
Linker Options ........................................................................ 256
Global Command Line Options........................................ 257
Segment Control Options ................................................. 258
Segment Grouping............................................................ 262
Linking Files on the Command line ................................. 262
Example............................................................................ 263
Include Option .................................................................. 263
Example............................................................................ 263
Private Region Options..................................................... 264
Symbol Definition Option ................................................ 265
Reserve Space Option....................................................... 267
Handle Dependencies ....................................................... 267
Section Relocation .................................................................. 268
Address Specification....................................................... 268
Overlapping Control......................................................... 268
Setting Bias and Offset ........................................................... 268
Setting the Bias................................................................. 269
Setting the Offset.............................................................. 269
Using Default Placement.................................................. 269
Bit Segment Handling ...................................................... 269
Linking Objects....................................................................... 270
Linking Library Objects.......................................................... 270
Library Order.................................................................... 271
Libraries Setup Search Paths ............................................ 271
Automatic Data Initialization.................................................. 272
Descriptor Format............................................................. 272
Moveable Code ....................................................................... 273
Checksum Computation.......................................................... 275
DEFs and REFs....................................................................... 277
Special Topics......................................................................... 278
Private Name Regions ...................................................... 278
Renaming Symbols........................................................... 278
Absolute Symbol Tables................................................... 282
Description of The Map File................................................... 283

(vii)

Return Value........................................................................... 284
Linker Command Line Examples........................................... 285

Chapter 7
Debugging Support
Generating Debugging Information........................................ 288
Generating Line Number Information.............................. 288
Generating Data Object Information................................ 288
The cprd Utility ...................................................................... 290
Command Line Options ................................................... 290
Examples .......................................................................... 291
The clst utility ......................................................................... 292
Command Line Options ................................................... 292

Chapter 8
Programming Support
The chex Utility ...................................................................... 296
Command Line Options ................................................... 296
Return Status .................................................................... 298
Examples .......................................................................... 298
The clabs Utility ..................................................................... 300
Command Line Options ................................................... 300
Return Status .................................................................... 301
Examples .......................................................................... 301
The clib Utility........................................................................ 303
Command Line Options ................................................... 303
Return Status .................................................................... 304
Examples .......................................................................... 304
The cobj Utility....................................................................... 306
Command Line Options ................................................... 306
Return Status .................................................................... 307
Examples .......................................................................... 307
The cv695 Utility.................................................................... 308
Command Line Options ................................................... 308
The cvdwarf Utility ................................................................ 312
Command Line Options ................................................... 312
Return Status .................................................................... 314
Examples .......................................................................... 314

Chapter A
Compiler Error Messages
Parser (cpstm8) Error Messages ............................................. 316

(viii)

Code Generator (cgstm8) Error Messages.............................. 330
Assembler (castm8) Error Messages ...................................... 331
Linker (clnk) Error Messages ................................................. 334

Chapter B
Modifying Compiler Operation
The Configuration File............................................................ 338
Changing the Default Options ................................................ 340
Creating Your Own Options............................................. 340
Example .................................................................................. 341

Chapter C
STM8 Machine Library
Update an int bitfield in external memory........................ 345
Quotient of unsigned char division................................... 346
Quotient of unsigned char division................................... 347
Eeprom char bit field update ............................................ 348
Write a char in eeprom ..................................................... 349
Write a long int in eeprom................................................ 350
Write a short int in eeprom............................................... 351
Move a structure in eeprom .............................................. 352
Add float to float .............................................................. 353
Compare floats.................................................................. 354
Divide float by float.......................................................... 355
Add float to float in memory ............................................ 356
Multiply float by float in memory .................................... 357
Subtract float from float in memory................................. 358
Multiply float by float ...................................................... 359
Negate a float.................................................................... 360
Subtract float from float ................................................... 361
Convert float to integer..................................................... 362
Convert float into long integer ......................................... 363
Compare a float in memory to zero .................................. 364
Get a long word from external memory ........................... 365
Get a long word from external memory ........................... 366
Get a word from external memory ................................... 367
Get a word from external memory ................................... 368
Quotient of integer division.............................................. 369
Integer multiplication ....................................................... 370
Convert integer into float.................................................. 371
Convert integer into long.................................................. 372
Perform C switch statement on long ................................ 373

(ix)

Long integer addition ....................................................... 374
Bitwise AND for long integers......................................... 375
Long integer compare....................................................... 376
Quotient of long integer division ..................................... 377
Long addition ................................................................... 378
Long bitwise AND ........................................................... 379
Long shift left ................................................................... 380
Long multiplication in memory........................................ 381
Negate a long integer in memory ..................................... 382
Long bitwise OR .............................................................. 383
Signed long shift right ...................................................... 384
Long subtraction............................................................... 385
Unsigned long shift right.................................................. 386
Long bitwise exclusive OR .............................................. 387
Long integer shift left ....................................................... 388
Remainder of long integer division .................................. 389
Multiply long integer by long integer .............................. 390
Negate a long integer........................................................ 391
Bitwise OR with long integers ......................................... 392
Long integer right shift..................................................... 393
Long test against zero....................................................... 394
Long integer subtraction................................................... 395
Convert long integer into float ......................................... 396
Load memory into long register ....................................... 397
Quotient of unsigned long integer division ...................... 398
Remainder of unsigned long integer division................... 399
Unsigned long integer shift right...................................... 400
Bitwise exclusive OR with long integers ......................... 401
Compare a long integer to zero ........................................ 402
Put a long integer in external memory ............................. 403
Put a long integer in external memory ............................. 404
Put a word in extended memory....................................... 405
Store long register in memory .......................................... 406
Store long register in external memory ............................ 407
Quotient of signed char division ...................................... 408
Quotient of signed char division ...................................... 409
Multiply long integer by unsigned byte ........................... 410
Quotient of unsigned integer division .............................. 411
Convert unsigned integer into float .................................. 412
Convert unsigned integer into long .................................. 413
Convert unsigned long integer into float.......................... 414
Copy a structure into another ........................................... 415

(x)

Copy a structure in external memory ............................... 416
Copy a structure into another ........................................... 417
Copy a structure in external memory ............................... 418

Chapter D
Compiler Passes
The cpstm8 Parser................................................................... 420
Command Line Options ................................................... 420
Return Status .................................................................... 424
Example............................................................................ 424
The cgstm8 Code Generator ................................................... 425
Command Line Options ................................................... 425
Return Status .................................................................... 427
Example............................................................................ 427
The costm8 Assembly Language Optimizer........................... 428
Command Line Options ................................................... 428
Disabling Optimization .................................................... 429
Return Status .................................................................... 429
Example............................................................................ 429

(xi)

Preface
T

he Cross Compiler User's Guide for STM8 is a reference guide for
programmers writing C programs for STM8 microcontroller environments. 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 manual assumes that you are familiar with your host operating system and
with your specific target environment.

Organization of this Manual
This manual is divided into eight chapters and four appendixes.
Chapter 1, “Introduction”, describes the basic organization of the C
compiler and programming support utilities.
Chapter 2, “Tutorial Introduction”, is a series of examples that demonstrates how to compile, assemble and link a simple C program.
Chapter 3, “Programming Environments”, explains how to use the features of C for STM8 to meet the requirements of your particular application. It explains how to create a runtime startup for your application,
and how to write C routines that perform special tasks such as: serial I/
O, direct references to hardware addresses, interrupt handling, and
assembly language calls.

© 2007 COSMIC Software

Preface

1

Organization of this Manual

Chapter 4, “Using The Compiler”, describes the compiler options. This
chapter also describes the functions in the C runtime library.
Chapter 5, “Using The Assembler”, describes the STM8 assembler and
its options. It explains the rules that your assembly language source
must follow, and it documents all the directives supported by the assembler.
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.
Chapter 7, “Debugging Support”, describes the support available for
COSMIC's C source level cross debugger and for other debuggers or incircuit emulators.
Chapter 8, “Programming Support”, describes the programming support utilities. Examples of how to use these utilities are also included.
Appendix A, “Compiler Error Messages”, is a list of compile time
error messages that the C compiler may generate.
Appendix B, “Modifying Compiler Operation”, describes the “configuration file” that serves as default behaviour to the C compiler.
Appendix C, “STM8 Machine Library”, describes the assembly language routines that provide support for the C runtime library.
Appendix D, “Compiler Passes”, describes the specifics of the parser,
code generator and assembly language optimizer and the command line
options that each accepts.
This manual also contains an Index.

2

Preface

© 2007 COSMIC Software

CHAPTER

1
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

•

Programming Support Utilities

•

Listings

•

Optimizations

•

Support for ROMable Code

•

Support for eeprom

•

Memory Models

© 2007 COSMIC Software

Introduction

3

1

Introduction

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 generate an object module that contains debugging information that can be
used by COSMIC’s C source level cross debugger or by other debuggers or in-circuit emulators.
You begin compilation by invoking the cxstm8 compiler driver with
the specific options you need and the files to be compiled.

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.
To distinguish it from other examples or listings, input from the user
will appear in a shaded box throughout the text. Output to the terminal
or to a file will appear in a line box.
For example, if you were instructed to type the compiler command that
generates debugging information, it would appears as:
cxstm8 +debug acia.c

Typewriter font enclosed in a shaded box indicates that this line is
entered by the user at the terminal.
4

Introduction

© 2007 COSMIC Software

Document Conventions

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 typewriter font would still be used, but would be enclosed in a line box:
/* defines the ACIA as a structure */
struct acia {
char status;
char data;
} acia @0x6000;

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 information for any file, it might appear as:
cxstm8 +debug file.c

In this example, cxstm8 +debug file.c is shown in typewriter font
because it must be typed exactly as shown. Because the filename must
be specified by the user, however, file is shown in italics.

[ Brackets ]

Items enclosed in brackets are optional. For example, the line:
[ options ]
means that zero or more options may be specified because options
appears in brackets. Conversely, the line:
options
means that one or more options must be specified because options is not
enclosed by brackets.

© 2007 COSMIC Software

Introduction

5

1

Document Conventions

As another example, the line:
file1.[o|sm8]

means that one file with the extension .o or .sm8 may be specified, and
the line:
file1 [ file2 . . . ]

means that additional files may be specified.

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:
program_name [] 

where  is the name of the program to run,  an
optional series of flags, and  a series of files. Each element of a
command line is usually a string separated by whitespace from all the
others.

Flags

Flags are used to select options or specify parameters. Options are recognized 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 previous one.
It is possible for each utility to display a list of accepted options by
specifying the -help option. Each option will be displayed alphabetically on a separate line with its name and a brief description. If an
option requires additional information, then the type of information is

6

Introduction

© 2007 COSMIC Software

Document Conventions

indicated by one of the following code, displayed immediately after the
option name:
Code

Type of information

*

character string

#

short integer

##

long integer

?

single character

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.
For example, the options of the chex utility are:
chex [options] file
-a##
absolute file start address
-b##
address bias
-e##
entry point address
-f?
output format
-h
suppress header
+h*
specify header string
-m#
maximum data bytes per line
-n*>
output only named segments
-o*
output file name
-p
use paged address format
-pp
use paged address with mapping
-pn
use paged address in bank only
-s
output increasing addresses
-x*
exclude named segment

chex accepts the following distinct flags:
Flag

Function

-a

accept a long integer value

-b

accept a long integer value

© 2007 COSMIC Software

Introduction

7

1

Compiler Architecture

Flag

Function

-e

accept a long integer value

-f

accept a single character

-h

simply a flag indicator

+h

accept a character string

-m

accept a short integer value

-n

accept a character string and may be repeated

-o

accept a character string

-p

simply a flag indicator

-pn

simply a flag indicator

-pp

simply a flag indicator

-s

simply a flag indicator

-x

accept a character string and may be repeated

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:

cpstm8 - the C preprocessor and language parser. cpstm8 expands
directives in your C source and parses the resulting text.

cgstm8 - the code generator. cgstm8 accepts the output of cpstm8 and
generates assembly language statements.

costm8 - the assembly language optimizer. costm8 optimizes the
assembly language code that cgstm8 generates.
castm8 - the assembler. castm8 converts the assembly language output of costm8 to a relocatable object module.
8

Introduction

© 2007 COSMIC Software

Predefined Symbol

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:
bit 2

set if unsigned char option specified (-pu)

bit 4

set if reverse bitfield option specified (+rev)

bit 5

set if no enum optimization specified (-pne)

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.

Programming Support Utilities
Once object files are produced, you run clnk (the linker) to produce an
executable image for your target system; you can use the programming
support utilities to inspect the executable.

chex - absolute hex file generator. chex translates executable images
produced by the linker into hexadecimal interchange formats, for use
with in-circuit emulators and PROM programmers. chex produces the
following formats:
- Motorola S-record format
- standard Intel hex format

clabs - absolute listing utility. clabs translates relocatable listings produced by the assembler by replacing all relocatable information by
absolute information. This utility must to be used only after the linker.

© 2007 COSMIC Software

Introduction

9

1

Listings

clib - build and maintain object module libraries. clib allows you to
collect related files into a single named library file for convenient storage. You use it to build and maintain object module libraries in standard
library format.
cobj - object module inspector. cobj allows you to examine standard
format executable and relocatable object files for symbol table information and to determine their size and configuration.

cv695 - IEEE695 format converter. cv695 allows you to generate
IEEE695 format file. This utility must to be used only after the linker.
cvdwarf - ELF/DWARF format converter. cvdwarf allows you to convert a file produced by the linker into an ELF/DWARF format file.

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 interspersed 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 optimizations that help make your application smaller and faster:

10

•

The compiler will perform arithmetic operations in 8-bit precision
if the operands are 8-bit.

•

The compiler eliminates unreachable code.

•

The compiler performs multiplication by powers of two as faster
shift instructions.

Introduction

© 2007 COSMIC Software

Support for ROMable Code

•

Branch shortening logic chooses the smallest possible jump/
branch instructions. Jumps to jumps and jumps over jumps are
eliminated as well.

•

Integer and float constant expressions are folded at compile time.

•

Redundant load and store operations are removed.

•

enum is large enough to represent all of its declared values, each
of which is given a name. The names of enum values occupy the
same space as type definitions, functions and object names. The
compiler provides the ability to declare an enum using the smallest type char, int or long:

•

An optimized switch statement produces combinations of tests
and branches, jump tables for closely spaced case labels, a scan
table for a small group of loosely spaced case labels, or a sorted
table for an efficient search.

•

The functions in the C library are packaged in three separate
libraries; one of them is built without floating point support. If
your application does not perform floating point calculations, you
can decrease its size and increase its runtime efficiency by linking
with the non-floating-point version of the modules needed.

Support for ROMable Code
The compiler provides the following features to support ROMable code
production. See Chapter 3 for more information.
•

Referencing of absolute hardware addresses;

•

Control of the STM8 interrupt system;

•

Automatic data initialization;

•

User configurable runtime startup file;

•

Support for mixing C and assembly language code; and

•

User configurable executable images suitable for direct input to a
PROM programmer or for direct downloading to a target system.

© 2007 COSMIC Software

Introduction

11

1

Support for eeprom

Support for eeprom
The compiler provides the following features to support eeprom handling:
•

@eeprom type qualifier to describe a variable as an eeprom location. The compiler generates special sequences when the variable
is modified.

•

Library functions for erasure, initialization and copy of eeprom
locations.

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.
These basic routines are not updating any watchdog, so applications
enabling a watchdog must modify these routines to add watchdog
updates in the wait loops.

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 the physical stack for functions arguments and
local variables, or to simulate such a stack in memory thus leaving more
space on the stack for return addresses and interrupt stacks. You can
also specify where those areas are located in the memory space, inside
or outside the zero page (short addressing). For more information,
please refer to Chapter 3.
For information on using the compiler, see Chapter 4.
For information on using the assembler, see Chapter 5.
For information on using the linker, see Chapter 6.
For information on debugging support, see Chapter 7.
For information on using the programming utilities, see Chapter 8.
For information on the compiler passes, see Appendix D.

12

Introduction

© 2007 COSMIC Software

CHAPTER

2
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 distribution media. Although this tutorial cannot show all the topics relevant
to the COSMIC tools, it will demonstrate the basics of using the compiler for the most common applications.
In this tutorial you will find information on the following topics:
•

Default Compiler Operation

•

Compiling and Linking

•

Linking Your Application

•

Generating Automatic Data Initialization

•

Specifying Command Line Options

© 2007 COSMIC Software

Tutorial Introduction

13

2

Acia.c, Example file

Acia.c, Example file
The following is a listing of acia.c. This C source file is copied during
the installation of the compiler:
/*
STM8 EXAMPLE PROGRAM WITH INTERRUPT HANDLING
*
Copyright (c) 2007 by COSMIC Software
*/
#include 
#define SIZE64
#define TRDE0x80

/* buffer size */
/* transmit ready bit */

/*
Authorize interrupts.
*/
#define rim() _asm("rim")
/*
Some variables
*/
char buffer[SIZE];
char *ptlec;
char *ptecr;

/* reception buffer */
/* read pointer */
/* write pointer */

/*
Character reception.
*
Loops until a character is received.
*/
char getch(void)
{
char c;
/* character to be returned */
while (ptlec == ptecr) /* equal pointers => loop */
;
c = *ptlec++;
/* get the received char */
if (ptlec >= &buffer[SIZE])/* put in in buffer */
ptlec = buffer;
return (c);
}
/*
Send a char to the SCI.
*/
void outch(char c)
{
while (!(USART_SR & TRDE))/* wait for READY */
;
USART_DR = c;
/* send it */
}

14

Tutorial Introduction

© 2007 COSMIC Software

Acia.c, Example file

/*
Character reception routine.
*
This routine is called on interrupt.
*
It puts the received char in the buffer.
*/
@interrupt void recept(void)
{
USART_SR;
/* clear interrupt */
*ptecr++ = USART_DR;
/* get the char */
if (ptecr >= &buffer[SIZE])
/* put it in buffer */
ptecr = buffer;
}
/*
Main program.
*
Sets up the SCI and starts
*
of receive transmit.
*/
void main(void)
{
ptecr = ptlec = buffer; /*
USART_BRR1 = 0xc9;
/*
USART_CR1 = 0x00;
/*
USART_CR2 = 0x2c;
/*
rim();
/*
for (;;)
/*
outch(getch());
/*
}

an infinite loop

initialize pointers */
parameter for baud rate */
param. for word length */
parameters for interrupt */
authorize interrupts */
loop */
get and put a char */

Default Compiler Operation

By default, the compiler compiles and assembles your program. You
may then link object files using clnk to create an executable program.
The compiler supports several memory models, for applications smaller
or larger than 64K, defining how the stack is used and where variables
are allocated. A model option should always be specified on the command line; if nothing is specified, the compiler assumes the +modsl
option (physical stack and globals in long range). See “Memory Models
for code smaller than 64K” in Chapter 3 and “Memory Models for
code larger than 64K” in Chapter 3 for more information.
As it processes the command line, cxstm8 echoes the name of each
input file to the standard output file (your terminal screen by default).
You can change the amount of information the compiler sends to your
terminal screen using command line options, as described later.

© 2007 COSMIC Software

Tutorial Introduction

15

2

Acia.c, Example file

According to the options you will use, the following files, recognized
by the COSMIC naming conventions, will be generated:
file.s
file.o
file.sm8

16

Tutorial Introduction

Assembler source module
Relocatable object module
input (e.g. libraries) or output (e.g. absolute executable)
file for the linker

© 2007 COSMIC Software

Compiling and Linking

Compiling and Linking
To compile and assemble acia.c using the short stack model, type:
cxstm8 +mods acia.c

The compiler writes the name of the input file it processes:
acia.c:

The result of the compilation process is an object module named acia.o
produced by the assembler. We will, now, show you how to use the different components.

Step 1: Compiling

The first step consists in compiling the C source file and producing an
assembly language file named acia.s.
cxstm8 +mods -s acia.c

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

If you wish to get an interspersed C and assembly language file, you
should type:
cxstm8 +mods -l acia.c

© 2007 COSMIC Software

Tutorial Introduction

17

2

Compiling and Linking

The -l option directs the compiler to produce an assembly language file
with C source line interspersed in it. Please note that the C source lines
are commented in the assembly language file: they start with ‘;’.
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.
The -v option, known as verbose mode, instructs the C compiler to display all of its actions. For example if you type:
cxstm8 +mods -v -s acia.c

the display will look like something similar to the following:
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

The compiler runs each pass:
cpstm8

the C parser

cgstm8

the assembly code generator

costm8

the optimizer

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 -i\cxstm8\hstm8 acia.s

if you want to use directly the macro cross assembler.

18

Tutorial Introduction

© 2007 COSMIC Software

Compiling and Linking

The cross assembler can provide, when necessary, listings, symbol
table, cross reference and more. The following command will generate
a listing file named acia.ls that will also contain a cross reference:
castm8 -c -l acia.s

For more information, see Chapter 5, “Using The Assembler”.

Step 3: Linking

This step consists in linking relocatable files, also referred to as object
modules, produced by the compiler or by the assembler (.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 several 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 zero page or short addressing range.

.ubsct

non initialized data in the zero page

.fdata

large variables (@far)

.eeprom

any variable in eeprom (@eeprom)

.bit

bit variables in the zero page

© 2007 COSMIC Software

Tutorial Introduction

19

2

Compiling and Linking

In our example, and in the test file provided with the compiler, the
acia.lkf file contains the following information:
line
line
line
line
line
line
line
line
line
line
line
line
line

1 # LINK COMMAND FILE FOR TEST PROGRAM
2 # Copyright (c) 2002 by COSMIC Software
3 #
4 +seg .text -b0xf000 -n.text# program start address
5 +seg .const -a .text
# constants follow code
6 +seg .bsct -b0x0 -m0x100# zero page start address
7 +seg .ubsct
# uninitialized zero page
8 crts.o
# startup routine
9 acia.o
# application program
10 \cx32\lib\libis.sm8
# C library (if needed)
11 \cx32\lib\libm.sm8
# machine library
12 +seg .vector -b0x8000 # vectors start address
13 vector.o
# interrupt vectors

You can create your own link command file by modifying the one provided with the compiler.
Here is the explanation of the lines in acia.lkf:
lines 1 to 3: These are comment lines. Each line can include comments.
They must be prefixed by the “#” character.
line 4: +seg .text -b0xf000 creates a text (code) segment located
at f000 (hex address) named .text.
line 5: +seg .const -n.text creates a constant segment following
the text segment.
line 6: +seg .bsct -b0x0 -m0x100 creates a zero page segment
located at 0 (hex address) with a maximum size of 256 bytes.
line 7: +seg .ubsct creates an uninitialized zero page segment
located by default after the .bsct segment.
line 8: crts.o runtime startup code. It will be located at 0xf000
(code segment)
line 9: acia.o, the file that constitutes your application. It follows the
startup routine for code and data

20

Tutorial Introduction

© 2007 COSMIC Software

Compiling and Linking

line 10: libis.sm8 the integer library to resolve references
line 11: libm.sm8 the machine library to resolve references
line 12: +seg .vector -b0x8000 creates a segment vector (const)
segment located at 8000 (hex address)
line 13: vectors.o interrupt vectors file
By default and in our example, the .bss segment follows the .data segment.
The crts.o file contains the runtime startup that performs the following
operations:
•

initialize the bss, if any

•

initialize the stack pointer

•

call main() or any other chosen entry point.

For more information, see “Modifying the Runtime Startup” in Chapter
3.
After you have modified the linker command file, you can link by typing:
clnk -o acia.sm8 acia.lkf

Step 4: Generating S-Records file

Although acia.sm8 is an executable image, it may not be in the correct
format to be loaded on your target. Use the chex utility to translate the
format produced by the linker into standard formats. To translate
acia.sm8 to Motorola standard S-record format:
chex acia.sm8 > acia.hex

or

© 2007 COSMIC Software

Tutorial Introduction

21

2

Compiling and Linking

chex -o acia.hex acia.sm8

acia.hex is now an executable image in Motorola S-record format and
is ready to be loaded in your target system.
For more information, see “The chex Utility” in Chapter 8.

22

Tutorial Introduction

© 2007 COSMIC Software

Linking Your Application

Linking Your Application
You can create as many text, data and bss segments as your application
requires. For example, assume we have one bss, two data and two text
segments. Our link command file will look like:
+seg .text -b 0xf000 -n .text #
+seg .const -a .text
#
+seg .data -b 0x100
#
+seg .bss -b 0x200
#
+seg .bsct -b0x0 -m0x100
#
+seg .ubsct -n iram
#
crts.o
#
acia.o
#
module1.o
#
+seg .text -b 0x2000
#
module2.o
#
module3.o
#
\cx\lib\libis.sm8
#
\cx\lib\libm.sm8
#
+seg .vector -b0x8000
#
vector.o
#
#
# define these symbols if crtsi
#
#+def __endzp=@.ubsct
#
#+def __memory=@.bss
#

program start address
constant follow
data start address
bss start address
zpage start address
uninitialized zero page
startup routine
main program
application program
start new text section
application program
application program
C library (if needed)
machine library
vectors start address
interrupt vectors
is used
end of uninitialized zpage
symbol used by startup

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. zero page 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”.

© 2007 COSMIC Software

Tutorial Introduction

23

2

Generating Automatic Data Initialization

Generating Automatic Data Initialization
Usually, in embedded applications, your program must reside in ROM.
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 values must reside in RAM.
There are two types of static data initializations:
1) data that is explicitly initialized to a non-zero value:
char var1 = 25;

which is generated into the .bsct section and
2) data that is explicitly initialized to zero or left uninitialized:
char var2;

which is generated into the .ubsct section.
There is one exception to the above rules when you declare data that
will be located in the external memory, using the @near type qualifier. In this case, the data is generated into the .data section if it is initialized or in the .bss section otherwise.
The first method to ensure that these values are correct consists in adding code in your application that reinitializes them from a copy that you
have created and located in ROM, at each restart of the application.
The second method is to use the crtsi.sm8 start-up file:
1) that defines a symbol that will force the linker to create a copy of
the initialized RAM in ROM
2) and that will do the copy from ROM to RAM

24

Tutorial Introduction

© 2007 COSMIC Software

Generating Automatic Data Initialization

The following link file demonstrates how to achieve automatic data initialization.
# demo.lkf: link command with automatic init
+seg .text -b 0xf000 -n .text # program start address
+seg .const -a .text
# constant follow
+seg .bsct -b 0x0 -m 0x100
# zpage start address
+seg .data -b0x100
# data start address
\cx32\lib\crtsi.sm8
# startup with auto-init
acia.o
# main program
module1.o
# module program
\cx32\lib\libis.sm8
# C library (if needed)
\cx32\lib\libm.sm8
# machine library
+seg .vector -b 0x8000
# vectors start address
vector.o
# interrupt vectors
# define these symbols if crtsi is used
+def __endzp=@.ubsct
# end of uninitialized zpage
+def __memory=@.bss
# end of bss segment

In the above example, the text segment is located at address 0xf000,
the data segment is located at address 0x100, immediately followed by
the bss segment that contains uninitialized data. The initialized data in
ROM will follow the descriptor created by the linker after the code segment.
In case of multiple code and data segments, a link command file could
be:
# demoinit.lkf: link command with automatic init
+seg .text -b 0xf000 -n .text # program start address
+seg .const -a .text
# constant follow
+seg .bsct -b 0x0 -m 0x100
# zpage start address
+seg .data -b0x100
# data start address
\cx32\lib\crtsi.sm8
# startup with auto-init
acia.o
# main program
module1.o
# module program
+seg .text -b0xf800
# new code segment
module2.o
# module program
module3.o
# module program
\cx32\lib\libis.sm8
# C library (if needed)
\cx32\lib\libm.sm8
# machine library
+seg .vector -b 0x8000
# vectors start address
vector.o
# interrupt vectors
# define these symbols if crtsi is used
+def __endzp=@.ubsct
# end of uninitialized zpage
+def __memory=@.bss
# end of bss segment

© 2007 COSMIC Software

Tutorial Introduction

25

2

Generating Automatic Data Initialization

or
# demoinit.lkf: link command with automatic init
+seg .text -b 0xf000 -n .text # program start address
+seg .const -a .text
# constant follow
+seg .bsct -b 0x0 -m 0x100
# zpage start address
+seg .data -b0x100
# data start address
\cx32\lib\crtsi.sm8
# startup with auto-init
acia.o
# main program
module1.o
# module program
+seg .text -b0xf800 -it
# sets the section attribute
module2.o
# module program
module3.o
# module program
\cx32\lib\libis.sm8
# C library (if needed)
\cx32\lib\libm.sm8
# machine library
+seg .vector -b 0x8000
# vectors start address
vector.o
# interrupt vectors
# define these symbols if crtsi is used
+def __endzp=@.ubsct
# end of uninitialized zpage
+def __memory=@.bss
# end of bss segment

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 initialized data will be located after the second code segment located at
address 0xf800.
For more information, see “Initializing data in RAM” in Chapter 3 and
“Automatic Data Initialization” in Chapter 6.

26

Tutorial Introduction

© 2007 COSMIC Software

Specifying Command Line Options

Specifying Command Line Options
You specify command line options to cxstm8 to control the compilation
process.
To compile and get a relocatable file, type:
cxstm8 +mods acia.c

The file produced is acia.o.
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.
To perform the operations described above, enter the command:
cxstm8 +mods -v -l acia.c

When the compiler exits, the following files are left in your current
directory:
•

the C source file acia.c

•

the C and assembly language listing acia.ls

•

the object module acia.o

It is possible to locate listings and object files in specified directories if
they are different from the current one, by using respectively the -cl and
-co options:
cxstm8 +mods -cl\mylist -co\myobj -l acia.c

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.

© 2007 COSMIC Software

Tutorial Introduction

27

2

Specifying Command Line Options

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.
If your application is composed with the following files: two C source
files and one assembly source file, you would type:
cxstm8 +mods -v start.s acia.c getchar.c

This command will assemble the start.s file, and compile the two C
source files.
See “Compiler Command Line Options” in Chapter 4 for information
on these and other command line options.

28

Tutorial Introduction

© 2007 COSMIC Software

CHAPTER

3
Programming
Environments
This chapter explains how to use the COSMIC program development
system to perform special tasks required by various STM8 applications.

© 2007 COSMIC Software

Programming Environments

29

3

Introduction

Introduction
This chapter provides details about:

30

•

Modifying the Runtime Startup

•

Initializing data in RAM

•

Memory Models for code smaller than 64K

•

Memory Models for code larger than 64K

•

Handling Large Code and Constants

•

Bit Variables

•

The const and volatile Type Qualifiers

•

Performing Input/Output in C

•

Referencing Absolute Addresses

•

Accessing Internal Registers

•

Placing Data Objects in The Bss Section

•

Placing Data Objects in Short Range Memory

•

Placing Data Objects in Long Range Memory

•

Placing Data Objects in the EEPROM Space

•

Redefining Sections

•

Inserting Inline Assembly Instructions

•

Writing Interrupt Handlers

•

Placing Addresses in Interrupt Vectors

•

Inline Function

•

Interfacing C to Assembly Language

Programming Environments

© 2007 COSMIC Software

Introduction

•

Register Usage

•

Data Representation

© 2007 COSMIC Software

Programming Environments

31

3

Modifying the Runtime Startup

Modifying the Runtime Startup
The runtime startup module performs many important functions to
establish a runtime environment for C. The runtime startup file included
with the standard distribution provides the following:
•

Initialization of the bss section if any,

•

ROM into RAM copy if required,

•

Initialization of the stack pointer,

•

f_main or other program entry point call, and

•

An exit sequence to return from the C environment. Most users
must modify the exit sequence provided to meet the needs of their
specific execution environment.

The following is a listing of the standard runtime startup file crts.sm8
included on your distribution media. It does not perform automatic data
initialization. The runtime startup file can be placed anywhere in memory. Usually, the startup will be “linked” with the RESET interrupt, and
the startup file may be at any convenient location.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

32

;
;
;
;

C STARTUP FOR STM8
WITHOUT ANY DATA INITIALIZATION
Copyright (c) 2006 by COSMIC Software
xref
xdef

;
;
;

f_main, __stack
f_exit, __stext, f__stext

startup routine from reset vector

switch .text
__stext:
f__stext:
;
; initialize stack pointer
;
ldw
x,#__stack ; stack pointer
ldw
sp,x
; in place
;
; execute main() function
; may be called by a 'jpf' instruction if no return

Programming Environments

© 2007 COSMIC Software

Modifying the Runtime Startup

expected
21 ;
22
callf f_main
23 f_exit:
24
jra
f_exit
25 ;
26
end

; execute main
; and stay here

Description of Runtime Startup Code

f_main is the entry point into the user C program.
Line 15 resets the stack pointer.
Line 22 calls main() in the user's C program.
Lines 23 to 24 trap a return from main(). If your application must return
to a monitor, for example, you must modify this line.

© 2007 COSMIC Software

Programming Environments

33

3

Initializing data in RAM

Initializing data in RAM
If you have initialized static variables, which are located in RAM, you
need to perform their initialization before you start your C program.
The clnk linker will take care of that: it moves the initialized data segments after the first text segment, or the one you have selected with the
-it option, and creates a descriptor giving the starting address, destination and size of each segment.
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.
;
;
;
;

C STARTUP FOR STM8
WITH AUTOMATIC DATA INITIALISATION
Copyright (c) 2006 by COSMIC Software
xref f_main, __memory, __idesc__, __stack
xref.b c_x, c_y, __endzp
xdef f_exit, __stext, f__stext

;
;
;

start address of zpage

switch .ubsct
__suzp:
;
;
start address of bss
;
switch .bss
__sbss:
;
;
startup routine from reset vector
;
switch.text
__stext:
f__stext:
;
;
initialize stack pointer
;
ldw
x,#__stack ; stack pointer
ldw
sp,x
; in place
;
;
setup initialized data
;
ldw
y,__idesc__ ; data start address

34

Programming Environments

© 2007 COSMIC Software

Initializing data in RAM

ldw

x,#__idesc__+2

; descriptor address

ld
jreq
bcp
jreq
ldw
ldw
ldw
ldw
ldw

a,(x)
zero
a,#$60
qbcl
c_x,x
x,(3,x)
c_y,x
x,c_x
x,(1,x)

;
;
;
;
;
;
;
;
;

test flag byte
no more segment
test for moveable code segment
yes, skip it
save pointer
move end address
in memory
reload pointer
start address

ld
ld
incw
incw
cpw
jrne
ldw

a,(y)
(x),a
x
y
y,c_y
dbcl
x,c_x

;
;
;
;
;
;
;

transfer
byte
increment
pointers
last byte ?
no, loop again
reload pointer

addw
jra

x,#5
ibcl

; next descriptor
; and loop

ibcl:

dbcl:

qbcl:

;
;
reset
;
zero:
ldw
jra
zbcl:
ld
incw
loop:
cpw
jrne
;
;
reset
;
ldw
jra
bbcl:
ld
incw
ok:
cpw
jrne
;

uninitialized data in zero page

x,#__suzp
loop

; start of uninitialized zpage
; test segment end first

(x),a
x

; clear byte
; next byte

x,#__endzp
zbcl

; end of zpage
; no, continue

uninitialized data in bss
x,#__sbss
ok

; start address
; test segment end first

(x),a
x

; clear byte
; next byte

x,#__memory ; compare end
bbcl
; not equal, continue

© 2007 COSMIC Software

Programming Environments

35

3

Initializing data in RAM

;
execute main() function
;
may be called by a 'jpf' instruction if no return
expected
;
callf f_main
; execute main
f_exit:
jra
f_exit
; and stay here
;
end

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.
The compiler is provided with several startup files implementing the
automatic data initialization depending on the range of variables to be
initialized and the range of the initialization table:

Startup

Initialize

From Table in

crtsi.s

@near

@near

crtsx.s

@near and @far

@near

crtsif.s

@near

@far

crtsxf.s

@near and @far

@far

For more information, see “Generating Automatic Data Initialization”
in Chapter 2 and “Automatic Data Initialization” in Chapter 6.

36

Programming Environments

© 2007 COSMIC Software

Memory Models for code smaller than 64K

Memory Models for code smaller than 64K
The STM8 compiler supports two memory models for application
smaller than 64K, allowing you to choose the most efficient behavior
depending on your processor configuration and your application. All
these models handle code smaller than 64K and then function pointers
are defaulted to @near pointers (2 bytes). Data pointers are defaulted
to @near pointers (2 bytes). The supported models are:
•

Stack Short (mods0) stack is physically in long range and global
variables are defaulted to short range. Any global object in long
range will have to be accessed explicitly with the @near modifier
unless accessed through a pointer.

•

Stack Long (modsl0) stack is physically in long range and global
variables are also defaulted to long range. Any object in long range
will have to be accessed explicitly with the @tiny modifier.

The following table shows for each model how and where the stack is
implemented, how globals are defaulted and how pointers are defaulted.
Models

Stack

Globals

Stack Short

Physical in Long Range

Zero Page

Stack Long

Physical in Long Range

Long Range

The physical stack is implemented in the long range and its value is set
by the symbol __stack in the linker file, if you use the run time setup
files provided with the compiler. The user must insure that the stack and
the variables do not overlap at run time.
The choice of the appropriate model for a given application should be
driven by the amount of globals and locals compared with the available
space in memory. Zero Page variables are more efficient than Long
Range variables but the Zero Page size is limited to 256 bytes.

NOTE
When using a model for application smaller than 64K, you must link with
the specific set of libraries (names ending with ‘0’).

© 2007 COSMIC Software

Programming Environments

37

3

Memory Models for code larger than 64K

Memory Models for code larger than 64K
The STM8 compiler supports two memory models for application
larger than 64K, allowing you to choose the most efficient behavior
depending on your processor configuration and your application. All
these models allow the code to be larger than 64K and then function
pointers are defaulted to @far pointers (3 bytes). Data pointers are
defaulted to @near pointers (2 bytes) unless explicitly declared with
the @far modifier. The supported models are:
•

Stack Short (mods) stack is physically in long range and global
variables are defaulted to short range. Any global object in long
range will have to be accessed explicitly with the @near modifier
unless accessed through a pointer.

•

Stack Long (modsl) stack is physically in long range and global
variables are also defaulted to long range. Any object in long range
will have to be accessed explicitly with the @tiny modifier.

The following table shows for each model how and where the stack is
implemented, how globals are defaulted and how pointers are defaulted.
Models

Stack

Globals

Stack Short

Physical in Long Range

Zero Page

Stack Long

Physical in Long Range

Long Range

The physical stack is implemented in the long range and its value is set
by the symbol __stack in the linker file, if you use the run time setup
files provided with the compiler. The user must insure that the stack and
the variables do not overlap at run time.
The choice of the appropriate model for a given application should be
driven by the amount of globals and locals compared with the available
space in memory. Zero Page variables are more efficient than Long
Range variables but the Zero Page size is limited to 256 bytes.

38

Programming Environments

© 2007 COSMIC Software

Handling Large Code and Constants

Handling Large Code and Constants
The STM8 addresses more than 64K of code, dividing the total space in
64K large sections. The compiler allows by default functions to be as
large as needed and to be allocated anywhere in the total space, regardless of any sections boundary crossing. Interrupt functions need to be
located in the first section. The assembly name of functions allocated
anywhere, implicitly declared as @far functions, is prefixed with the
sequence “f_”, the function beeing called by a callf instruction and
ended with a retf instruction, while the name of functions declared
explicitly as @near functions is prefixed with a single “_”, the function
beeing called by a call instruction and ended with a ret instruction.
Such @near functions must be completely located inside the same section and called only by functions located in the same section. Unless
trying to optimize the code space, the @near modifier should be
restricted to interrupt functions. Such a difference in the function names
allows the linker to check that @far and @near functions are called
properly, any mixing beeing forbidden as the stack display would not
be the same.
In order to allow large functions to cross section boundaries, the compiler has to use the far jump instruction jpf for any unconditional jump
inside the function when the range is too large for a jra instruction. This
makes the code larger even if such a function is not actually crossing a
section boundary. It is possible to force the compiler using the jp
instruction on any function by using the -gnc option. Such functions
may still be @far or @near but cannot be larger than 64K and cannot
be allocated across section. Such functions and @near functions are
checked by the linker in order to verify this constraint.
Constants and literals are normally produced in the .const section
which must be located in the first section. Large constants may be
declared with an @far modifier. In such a case, they are produced in a
.fconst section which may be located anywhere. Although the far space
is used for code and constants, the compiler allows variables to be
declared with the @far modifier. Such variables are allocated in a
.fdata section which may be located anywhere.

© 2007 COSMIC Software

Programming Environments

39

3

Bit Variables

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 which needs to be allocated in the zero page in order to
allow and efficient handling using the bit instructions. 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;
in_range = (value >= 10) && (value <= 20);
p_valid = ptr;
/* p_valid is true if ptr not 0 */
if (p_valid && in_range)
*ptr = value;

40

Programming Environments

© 2007 COSMIC Software

The const and volatile Type Qualifiers

The const and volatile Type Qualifiers
You can add the type qualifiers const and volatile to any base type or
pointer type attribute.
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 optimize references to volatile data.
An expression that stores a value in a data object of volatile type stores
the value immediately. An expression that accesses a value in a data
object of volatile type obtains the stored value for each access. Your
program will not reuse the value accessed earlier from a data object of
volatile type.

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 conditions:
1) All data objects or variables associated with a memory mapped hardware register e.g. volatile char DDRB @0x05;
2) All global variable that can be modified (written to) by an interrupt
service routine either directly or indirectly. e.g. a global variable used as
a counter in an interrupt service routine.
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 encounters an expression that alters the value stored in a const data object.

© 2007 COSMIC Software

Programming Environments

41

3

The const and volatile Type Qualifiers

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 initializer. 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 variable whose value may be set by another program.
Examples of data objects declared with type qualifiers are:
char * const x;
/* const pointer to char */
int * volatile y;
/* volatile pointer to int */
const float pi = 355.0 / 113.0; /* pi is never changed */

42

Programming Environments

© 2007 COSMIC Software

Performing Input/Output in C

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 functions 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.
Function definitions for getchar and putchar are:
char getchar(void);
char putchar(char c);

+

© 2007 COSMIC Software

Programming Environments

43

3

Referencing Absolute Addresses

Referencing Absolute Addresses
This C compiler allows you to read from and write to absolute
addresses, and to assign an absolute address to a function entry point or
to a data object. You can give a memory location a symbolic name and
associated type, and use it as you would do with any C identifier. This
feature is usefull for accessing memory mapped I/O ports or for calling
functions at known addresses in ROM.
References to absolute addresses have the general form @
, where
is a valid memory location in your environment. For example, to associate an I/O port at address 0x20 with the identifier name ttystat, write a definition of the form: char MISCR1 @0x20; where @0x20 indicates an absolute address specification and not a data initializer. Since input/output on the STM8 architecture is memory mapped, performing I/O in this way is equivalent to writing in any given location in memory. 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. Individual bits can also be declared as _Bool objects by adding a bit number to the address using the syntax @
:, where
is a byte memory location and a bit number expressed by a constant value (or expression) between 0 and 7. For example, to define bit 3 of memory byte at 0x01 as PB3: _Bool PB3 @0x01:3; To use the I/O port in your application, write: char c; c = MISCR1; /* to read from input port */ MISCR1 = c; /* to write to output port */ 44 Programming Environments © 2007 COSMIC Software Referencing Absolute Addresses Another solutions is to use a #define directive with a cast to the type of the object being accessed, such as: #define MISCR1 *(char *)0x20 which is both inelegant and confusing. The COSMIC implementation is more efficient and easier to use, at the cost of a slight loss in portability. Note that COSMIC C does support the pointer and #define methods of implementing I/O access. Another example of how to reference a direct memory address, defines a structure at absolute address 0x6000: struct acia { char status; char data; } acia @0x6000 Using this declaration, references to acia.status will refer to memory location 0x6000 and acia.data will refer to memory location 0x6001. This is very useful if you are building your own custom I/O hardware that must reside at some location in the STM8 memory map. © 2007 COSMIC Software Programming Environments 45 3 Accessing Internal Registers Accessing Internal Registers All registers are declared in io*.h files provided with the compiler, each one dedicated to a specific processor. One of these files should be included in each file using the input-output registers, for example by a: #include All the register names are defined by assembly equates which are made public. This allows any assembler source to use directly the input-output register names by defining them with an xref directive. All those definitions are already provided in a io*.s file which may be included in an assembly source by a: include "io75f51x.s" Note that the compiler will access to these registers as standard variables. 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. 46 Programming Environments © 2007 COSMIC Software Placing Data Objects in The Bss Section Placing Data Objects in The Bss Section The compiler automatically reserves space for uninitialized data object. All such data are placed in the .bss section. All initialized static data are placed in the .data section. The bss section is located, by default, after the data section by the linker. The run-time startup files, crtsi.s and crtsi.s, contain code which initializes the bss section space to zero. The compiler provides a special option, +nobss, which forces uninitialized data to be explicitly located in the .data section. In such a case, these variables are considered as being explicitly initialized to zero. © 2007 COSMIC Software Programming Environments 47 3 Placing Data Objects in Short Range Memory Placing Data Objects in Short Range Memory The Stack Short model allocates global variables by default in short range memory. Such variables are located into the section .bsct if they are initialized, or in the section .ubsct otherwise. An external object name is published via a xref.b declaration at the assembly language level. A variable can be explicitly allocated in zero page by using the @tiny modifier: @tiny char c; To place data objects into short range memory on a file basis, if not yet selected the memory model, you can use the #pragma directive of the compiler: #pragma space extern [] @tiny instructs the compiler to place all data objects of storage class extern or static into short range memory for the current unit of compilation (usually a file). The section must end with a #pragma space extern [] @near to revert to the default compiler behaviour. NOTE The code generator does not check for zero page overflow. Setting Zero Page Size You can set the size of the zero page section of your object image at link time by specifying the following options on the linker command line: +seg .bsct -m## where ## represents the size of the zero page section in bytes. Note that the size of the zero page section can never exceed 256 bytes. 48 Programming Environments © 2007 COSMIC Software Placing Data Objects in Long Range Memory Placing Data Objects in Long Range Memory The Stack Long model allocates global variables by default in long range memory. Such variables will be located into the .data section if they are initialized, or in the .bss section otherwise. An external object name is published via a xref declaration at the assembly language level. A variable can be explicitly allocated in Long Range memory by using the @near modifier. The following declaration: @near char ext; instructs the compiler to locate the variable ext in the long range memory. 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: #pragma space extern [] @near instructs the compiler to place all data objects of storage class extern or static into Long Range memory for the current unit of compilation (usually a file). The section must end with a #pragma space extern [] @tiny to revert to the default compiler behaviour. © 2007 COSMIC Software Programming Environments 49 3 Placing Data Objects in the EEPROM Space Placing Data Objects in the EEPROM Space The compiler allows the use to define a variable as an eeprom location, using the type qualifier @eeprom. This causes the compiler to produce special code when such a variable is modified. When the compiler detects a write to an eeprom location, it calls a machine library function which performs the actual write. An example of such a definition is: @eeprom char var; To place all data objects from a file into eeprom, you can use the #pragma directive of the compiler: #pragma space extern [] @eeprom @near instructs the compiler to treat all extern and static data in the current file as eeprom locations. The @near modifier is necessary because the eeprom is located outside the zero page. The section must end with a #pragma space extern [] @near or @tiny, depending on the memory model selected. The compiler allocates @eeprom variables in a separate section named .eeprom, which will be located at link time. The linker directive: seg .eeprom -b0xb600 -m512 var_eeprom.o will create a segment located at address 0xb600, with a maximum size of 512 bytes. NOTE The code generator cannot check if data address will be eeprom addresses after linkage. 50 Programming Environments © 2007 COSMIC Software Redefining Sections 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 zero page (@tiny by default) .ubsct uninitialized variables in zero page (@tiny by default) .fdata large variables (@far) .eeprom any variable in eeprom (@eeprom) .bit bit variables in the zero page It is possible to redirect any of these components to any user defined section by using the following pragma definition: #pragma section where is either empty or one of the following sequences: const _Bool @tiny @near @far @eeprom and is a section name enclosed as follows: (name) - parenthesis indicating a code section [name] - square brackets indicating uninitialized data {name} - curly braces indicating initialized data © 2007 COSMIC Software Programming Environments 51 3 Redefining Sections 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 sequence. Each pragma directive starts redirecting the selected component from the next declarations. Redefining the bss section forces the compiler to produce the memory definitions for all the previous bss declarations before to switch to the new section. The following directives: #pragma #pragma #pragma #pragma #pragma #pragma #pragma #pragma section section section section section section section section (code) const {string} @near [udata] @near {idata} @tiny [uzpage] @tiny {izpage} @eeprom @near {e2prom} _Bool {bdata} redefine the default sections (or the previous one) as following: - executable code is redirected to section .code - strings and constants are redirected to section .string - uninitialized variables are redirected to section .udata - initialized data are redirected to section .idata - uninitialized zpage variables are redirected to section .uzpage - initialized zpage variables are redirected to section .izpage - eeprom variables are redirected to section .e2prom - bit variables are redirected to section .bdata Note that {name} and [name] are equivalent for constant and eeprom sections as they are all considered as initialized. The following directive: #pragma section () switches back the code section to the default section .text. 52 Programming Environments © 2007 COSMIC Software Inserting Inline Assembly Instructions Inserting Inline Assembly Instructions The compiler features two ways to insert assembly instructions in a C file. The first method uses #pragma directives to enclose assembly instructions. The second method uses a special function call to insert assembly instructions. The first one is more convenient for large sequences but does not provide any connection with C object. The second one is more convenient to interface with C objects but is more limited regarding the code length. Inlining with pragmas The compiler accepts the following pragma sequences to start and finish assembly instruction blocks: 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 Such an assembler block may be located anywhere, inside or outside a function. Outside a function, it behaves syntactically as a declaration. This means that such an assembler block cannot split a C declaration somewhere in the middle. Inside a function, it behaves syntactically as one C instruction. This means that there is no trailing semicolon at the end, and no need for enclosing braces. It also means that such an assembler block cannot split a C instruction or expression somewhere in the middle. The following example shows a correct syntax: © 2007 COSMIC Software Programming Environments 53 3 Inserting Inline Assembly Instructions #pragma asm xref asmvar #pragma endasm extern char test; void func(void) { if (test) #asm /* no need for { */ scf ; set carry bit rlc asmvar; access assembler variable #endasm else test = 1; } Inlining with _asm The _asm() function inserts inline assembly code in your C program. The syntax is: _asm(“string constant”, arguments...); The “string constant” argument is the assembly code you want embedded 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. For example, to produce the following assembly sequence: ldw x,sp callf f_main you would write _asm(“ldw x,sp\n callf f_main\n”); The ‘\n’ character is used to separate the instructions when writing multiple instructions in the same line. 54 Programming Environments © 2007 COSMIC Software Inserting Inline Assembly Instructions 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. _asm() can be used in expressions, if the code produced by _asm complies with the rules for function returns. For example: var = _asm(“sra a\n rlc a\n rlc a\n”, var); allows to rotate the variable var passed as argument in the a register, and store the result in the same variable. The variable var is supposed to be declared as a char, and is loaded in the a register because it is considered as a first argument. The result is expected in the a register in order to comply with the return register convention, as described below. NOTE With both methods, the assembler source is added as is to the code during the compilation. The optimizer does not modify the specified instructions, unless the -a option is specified on the code generator. The assembler input can use lowercase or uppercase mnemonics, and may include assembler comments. By default, _asm() is returning an int as any undeclared function. To avoid the need of several definitions (usually conflictuous) when _asm() is used with different return types, the compiler implements a special behaviour when a cast is applied to _asm(). In such a case, the cast is considered to define the return type of _asm() instead of asking for a type conversion. There is no need for any prototype for the _asm() function as the parser verifies that the first argument is a string constant. © 2007 COSMIC Software Programming Environments 55 3 Inserting Inline Assembly Instructions Inlining Labels When labels are necessary in the inlined assembly code, the compiler provides a special syntax allowing local labels to be created and handled 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 #endasm 56 Programming Environments ; loop on the previous label © 2007 COSMIC Software Writing Interrupt Handlers Writing Interrupt Handlers A function declared with the type qualifier @interrupt is suitable for direct connection to an interrupt (hardware or software). @interrupt functions may not return a value. @interrupt functions are allowed to have arguments, although hardware generated interrupts are not likely to supply anything meaningful. When you define an @interrupt function, the compiler uses the “iret” instruction for the return sequence, and saves, if necessary, the y register and 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. Whatever the model used is, these copies are made directly on the stack. Because the STM8 allows several levels of interrupts, the compiler by default enforces a stack model for the interrupt function. The STM8 architecture forces any interrupt function to be located in the first 64K. The interrupt vector table containing 2-byte addresses, interrupt functions declared in C must be declared with the @near modifier if the vector table is also written in C. You define an @interrupt function by using the type qualifier @interrupt to qualify the type returned by the function you declare. An example of such a definition is: © 2007 COSMIC Software Programming Environments 57 3 Writing Interrupt Handlers @interrupt @near void it_handler(void) { ... } NOTE The @interrupt modifier is an extension to the ANSI standard. 58 Programming Environments © 2007 COSMIC Software Placing Addresses in Interrupt Vectors Placing Addresses in Interrupt Vectors You may use either an assembly language program or a C program to place the addresses of interrupt handlers in interrupt vectors. The assembly language program would be similar to the following example: switch .text xref handler1, handler2, handler3 vector1:dc.w handler1 vector2:dc.w handler2 vector3:dc.w handler3 end where handler1 and so forth are interrupt handlers. A small C routine that performs the same operation is: extern @near void handler1(), handler2(), handler3(); @near void (* const vector[])() = { handler1, handler2, handler3, }; where handler1 and so forth are interrupt handlers. Then, at link time, include the following options on the link line: +seg .const -b0x8000 vector.o where vector.o is the file which contains the vector table. This file is provided in the compiler package. © 2007 COSMIC Software Programming Environments 59 3 Inline Function 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. The compiler allows access to specific instructions or features of the STM8 processor, using @inline functions. Such functions shall be declared as external functions with the @inline modifier. The compiler recognizes three predefined functions when explicitly declared as follows: @inline char carry(void); @inline char irq(void); @inline char imask(void); 60 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 register 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 instruction. The imask function can be used only in a test. Programming Environments © 2007 COSMIC Software Inline Function These functions are predeclared in the processor.h header file. A full description with examples is provided in Chapter 4. Any other function declared as an @inline will be translated into a call to a user provided macro. The macro name is obtained by prefixing the @inline function name with the ‘_’ character. Arguments are allowed but should be restricted to variable references. Each reference is translated into the proper assembler expression (same translation as applied by the compiler) and then passed to the macro as a quoted text string. @inline functions may use the registers a and/or x, but the compiler can not check their use and will not save them. To save the registers before they are used by @inline functions, you must add the @usea and/or the @usex modifiers. For example: @inline @usea lsub(); tells the compiler that lsub() uses the register a, so that the compiler will save it. If both registers are used, you must specify both modifiers. © 2007 COSMIC Software Programming Environments 61 3 Interfacing C to Assembly Language Interfacing C to Assembly Language The C cross compiler translates C programs into assembly language according to the specifications described in this section. You may write external identifiers in both uppercase and lowercase. The compiler prepends an underscore ‘_’ character to each identifier. If the identifier is the name of an @far function, the compiler prepends a ‘f’ character to the extra underscore. 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. Literal data such as strings, float or long constants, and switch tables, are normally generated into the .const section. An option on the code generator allows such constants to be produced in the .text section. Const variables declared with the @far modifier are published in the .fconst section. The compiler generates initialized data declared with the @near modifier 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 normally generated into the .const 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. 62 Section Declaration Reference .bsct @tiny char i =2; xdef .ubsct @tiny char i; xdef .data int init = 1 xdef .bss int uninit xdef Programming Environments © 2007 COSMIC Software Interfacing C to Assembly Language Section Declaration Reference .text char putchar(c); xdef .const const char c = 1; xdef .fconst @far const char c = 1; xdef .fdata @far char i; xdef .bit _Bool Pb3; xdef Any of above extern int out; xref, xbit Function calls are performed according to the following: 1) Arguments are evaluated from right to left. The first argument is stored in the a register if it is a char or a @tiny pointer, or in the x register if its type is short, int or @near pointer, and if the function does not return a structure larger than 2 bytes. Other arguments are pushed to the stack if a Stack model is selected, or stored in memory otherwise. 2) The function is called via a callf f_func instruction. 3) Stacked arguments are cleaned out if a Stack model is selected. © 2007 COSMIC Software Programming Environments 63 3 Register Usage 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 (two upper bytes) and the x register (lower byte) 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: int func(int arg1, int arg2, int arg3) will create the following memory area: locals arg1 return address arg2 arg3 Stack pointer 64 Programming Environments © 2007 COSMIC Software Data Representation 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 significant byte first. 15 8 7 0 Most Significant Byte Less Significant Byte Short Int, Int Data objects of type long int are stored as four bytes, in descending order of significance. 31 24 23 16 15 8 7 Most Significant Byte 0 Less Significant Byte Long @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 Less Significant Byte Most Significant Byte @far Pointer Data objects of type float are represented as for the proposed IEEE Floating Point Standard; four bytes stored in descending order of significance. The IEEE representation is: most significant bit is one for negative 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 © 2007 COSMIC Software Programming Environments 65 3 Data Representation 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, multiplied by -1 if the sign bit is set, multiplied by 2 raised to the exponent. 31 30 23 22 Sign Characteristic 0 Mantissa Float representation 66 Programming Environments © 2007 COSMIC Software CHAPTER 4 Using The Compiler This chapter explains how to use the C cross compiler to compile programs on your host system. It explains how to invoke the compiler, and describes its options. It also describes the functions which constitute the C library. This chapter includes the following sections: • Invoking the Compiler • File Naming Conventions • Generating Listings • Generating an Error File • C Library Support • Descriptions of C Library Functions © 2007 COSMIC Software Using The Compiler 67 4 Invoking the Compiler Invoking the Compiler To invoke the cross compiler, type the command cxstm8, followed by the compiler options and the name(s) of the file(s) you want to compile. All the valid compiler options are described in this chapter. Commands to compile source files have the form: cxstm8 [options] .[c|s] cxstm8 is the name of the compiler. The option list is optional. You must include the name of at least one input 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 combination of these suffixes in any order. If you do not specify any command line options, cxstm8 will compile your with the default options. It will also write the name of each file as it is processed. It writes any error messages to STDERR. The following command line: cxstm8 +mods acia.c compiles and assembles the acia.c C program, using the Stack Short model, creating the relocatable program acia.o. If the compiler finds an error in your program, it halts compilation. When an error occurs, the compiler sends an error message to your terminal screen unless the option -e has been specified on the command line. In this case, all error messages are written to a file whose name is obtained by replacing the suffix .c of the source file by the suffix .err. An error message is still output on the terminal screen to indicate that errors have been found. Appendix A, “Compiler Error Messages” lists the error messages the compiler generates. If one or more command line arguments are invalid, cxstm8 processes the next file name on the command line and begins the compilation process again. The example command above does not specify any compiler options. In this case, the compiler will use only default options to compile and 68 Using The Compiler © 2007 COSMIC Software Invoking the Compiler assemble your program. You can change the operation of the compiler by specifying the options you want when you run the compiler. To specify options to the compiler, type the appropriate option or options on the command line as shown in the first example above. Options should be separated with spaces. You must include the ‘-’ or ‘+’ that is part of the option name. Compiler Command Line Options The cxstm8 compiler accepts the following command line options, each of which is described in detail below: cxstm8 [options] -a*> assembler options -ce* path for errors -cl* path for listings -co* path for objects -d*> define symbol -e create error file -ec all C files -es all assembler files -ex* prefix executables -f* configuration file -g*> code generator options -i*> path for include -l create listing -no do not use optimizer -o*> optimizer options -p*> parser options -sm create only dependencies -s create only assembler file -sp create only preprocessor file -t* path for temporary files -v verbose -x do not execute +*> select compiler options © 2007 COSMIC Software Using The Compiler 69 4 Invoking the Compiler Cxstm8 Option Usage 70 Option Description -a*> specify assembler options. Up to 60 options can be specified on the same command line. See Chapter 5, “Using The Assembler”, for the list of all accepted options. -ce* specify a path for the error files. By default, errors are created in the same directory than the source files. -cl* specify a path for the listing files. By default, listings are created in the same directory than the source files. -co* specify a path for the object files. By default, objects are created in the same directory than the source files. -d*^ specify * as the name of a user-defined preprocessor symbol (#define). The form of the definition is -dsymbol[=value]; the symbol is set to 1 if value is omitted. You can specify up to 60 such definitions. -e log errors from parser in a file instead of displaying them on the terminal screen. The error file name is defaulted to .err, and is created only if there are errors. -ec treat all files as C source files. -es treat all files as assembler source files. -ex use the compiler driver’s path as prefix to quickly locate the executable passes. Default is to use the path variable environment. 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 contains 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”. -g*> specify code generation options. Up to 60 options can be specified. See “The cgstm8 Code Generator” in Appendix D, for the list of all accepted options. Using The Compiler © 2007 COSMIC Software Invoking the Compiler Cxstm8 Option Usage (cont.) Option Description -i*> define include path. You can define up to 128 different paths. Each path is a directory name, not terminated by any directory separator character, or a file containing a list of directory names. -l merge C source listing with assembly language code; listing output defaults to .ls. -no do not use the optimizer. -o*> specify optimizer options. Up to 60 options can be specified. See “The costm8 Assembly Language Optimizer” in Appendix D, for the list of all accepted options. -p*> specify parser options. Up to 60 options can be specified. See “The cpstm8 Parser” in Appendix D, for the list of all accepted options. -s create only assembler files and stop. Do not assemble the files produced. -sm create only a list of ‘make’ compatible dependencies consisting for each source file in the object name followed by a list of header files needed to compile that file. -sp create only preprocessed files and stop. Do not compile files produced. Preprocessed output defaults to .p. The produced files can be compiled as C source files. -t* specify path for temporary files. The path is a directory name, not terminated by any directory separator character. -v be “verbose”. Before executing a command, print the command, along with its arguments, to STDOUT. The default is to output only the names of each file processed. Each name is followed by a colon and newline. -x do not execute the passes, instead write to STDOUT the commands which otherwise would have been performed. © 2007 COSMIC Software Using The Compiler 71 4 Invoking the Compiler Cxstm8 Option Usage (cont.) 72 Option Description +*> select a predefined compiler option. These options are predefined in the configuration file. You can specify up to 60 compiler options on the command line. The following documents the available options as provided by the default configuration file +compact produce a smaller code but slower than the default behaviour. Smaller code is produced by enabling the optimizer factorization feature with a default depth of seven instructions. +debug produce debug information to be used by the debug utilities provided with the compiler and by any external debugger. +mods select the Stack Short model. Stack is physically in long range, variables are in short range memory but pointers are pointing to long range memory. See “Memory Models for code larger than 64K” in Chapter 3. +modsl select the Stack Long mode. Stack is physically in long range, variables and pointers are in and pointing to long range memory. See “Memory Models for code larger than 64K” in Chapter 3. +mods0 select the Stack Short model for application smaller than 64K. Stack is physically in long range, variables are in short range memory but pointers are pointing to long range memory. See “Memory Models for code smaller than 64K” in Chapter 3. +modsl0 select the Stack Long model for application smaller than 64K. Stack is physically in long range, variables and pointers are in and pointing to long range memory. See “Memory Models for code smaller than 64K” in Chapter 3. +nobss do not use the .bss section for variables allocated in external memory. By default, such uninitialized variables are defined into the .bss section. This option is useful to force all variables to be grouped into a single section. +nocst output literals and constants in the code section .text instead of the specific section .const. Using The Compiler © 2007 COSMIC Software Invoking the Compiler Cxstm8 Option Usage (cont.) Option Description +proto enforce prototype declaration for functions. An error message is issued if a function is used and no prototype declaration is found for it. By default, the compiler accepts both syntaxes without any error. +rev reverse the bitfield filling order. By default, bitfields are filled from the Less Significant Bit (LSB) towards the Most Significant Bit (MSB) of a memory cell. If the +rev option is specified, bitfields are filled from the msb to the lsb. +split create a separate sub-section per function, up to a maximum number of 256 sections, thus allowing the linker to suppress unused functions if the -k option has been specified on at least one segment in the linker command file. For objects with more than 256 functions, the functions will be grouped together to a minimum number of functions per sub-section to not exceed the maximum number of 256 sub-sections. See “Segment Control Options” in Chapter 6. +strict direct the compiler to enforce stronger type checking. +warn enable warnings. © 2007 COSMIC Software Using The Compiler 73 4 File Naming Conventions File Naming Conventions The programs making up the C cross compiler generate the following output file names, by default. See the documentation on a specific program for information about how to change the default file names accepted as input or generated as output. 74 Program Input File Name Output File Name cpstm8 .c .1 cgstm8 .1 .2 costm8 .2 .s error listing .c .err assembler listing .[c|s] .ls C header files .h castm8 .s .o source listing .s .ls clnk .o name required chex STDOUT clabs .la clib name required cobj STDOUT cv695 .695 cvdwarf .elf Using The Compiler © 2007 COSMIC Software Generating Listings 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 produced by compiling the C source file acia.c with the -l option: cxstm8 +mods -l acia.c Generating an Error File You can generate a file containing all the error messages output by the parser by specifying the -e option to cxstm8. You can locate the error file in a different directory by using the -ce option. For example, you would type: cxstm8 +mods -e prog.c 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: cxstm8 +mods -v file.c To save the intermediate files created by the code generator and halt before the assembler: cxstm8 +mods -s file.c © 2007 COSMIC Software Using The Compiler 75 4 C Library Support 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. How C Library Functions are Packaged The functions in the C library are packaged in three separate sub-libraries; one for machine-dependent routines (the machine library), one that does not support floating point (the integer library) and one that provides full floating point support (the floating point library). If your application does not perform floating point calculations, you can decrease its size and increase its runtime efficiency by including only the integer library. Inserting Assembler Code Directly Assembler instructions can be quoted directly into C source files, and entered unchanged into the output assembly stream, by use of the _asm() function. This function is not part of any library as it is recognized by the compiler itself. See “Inserting Inline Assembly Instructions” in Chapter 3. Linking Libraries with Your Program If your application requires floating point support, you must specify the floating point library before the integer library in the linker command file. Modules common to both libraries will therefore be loaded from the floating point library, followed by the appropriate modules from the floating point and integer libraries, in that order. NOTE When using a model for application smaller than 64K, you must link with the specific set of libraries (names ending with ‘0’). Integer Library Functions The following table lists the C library functions in the integer library. _asm checksum checksum16 checksum16x 76 Using The Compiler isalpha iscntrl isdigit isgraph memcmp memcpy memmove memset strcmp strcpy strcspn strlen © 2007 COSMIC Software C Library Support checksumx abs atoi atol calloc div free getchar gets imask irq isalnum islower isprint ispunct isqrt isspace isupper isxdigit labs ldiv lsqrt malloc memchr printf putchar puts rand realloc sbreak scanf sprintf srand sscanf strcat strchr strncat strncmp strncpy strpbrk strrchr strspn strstr strtol tolower toupper Floating Point Library Functions The following table lists the C library functions in the float library. acos asin atan atan2 atof ceil cos cosh exp fabs floor fmod frexp ldexp log log10 modf pow printf sin sinh sprintf sqrt strtod tan tanh Common Input/Output Functions Two of the functions that perform stream output are included in both the integer and floating point libraries. The functionalities of the versions in the integer library are a subset of the functionalities of their floating point counterparts. The versions in the integer library cannot print or manipulate floating point numbers. These functions are: printf, sprintf. Functions Implemented as Macros Two of the functions in the C library are actually implemented as “macros”. Unlike other functions, which (if they do not return int) are declared in header files and defined in a separate object module that is linked in with your program later, functions implemented as macros are defined using #define preprocessor directives in the header file that declares them. Macros can therefore be used independently of any library by including the header file that defines and declares them with your program, as explained below. The functions in the C library that are implemented as macros are: max and min. © 2007 COSMIC Software Using The Compiler 77 4 C Library Support Including Header Files If your application calls a C library function, you must include the header file that declares the function at compile time, in order to use the proper return type and the proper function prototyping, so that all the expected arguments are properly evaluated. You do this by writing a preprocessor directive of the form: #include in your program, where is the name of the appropriate header file enclosed in angle brackets. The required header file should be included before you refer to any function that it declares. The names of the header files packaged with the C library and the functions declared in each header are listed below. - Header file for the assertion macro: assert. - Header file for the character functions: isalnum, isalpha, iscntrl, isgraph, isprint, ispunct, isspace, isxdigit, isdigit, isupper, islower, tolower and toupper. - Header file for limit constants for floating point values. - Header files for input-output registers. Each register has an upper-case name which matches the data sheet definition. The compiler provides a large set of header files for most derivative processors. - Header file for limit constants of the compiler. - Header file for mathematical functions: acos, asin, atan, atan2, ceil, cos, cosh, exp, fabs, floor, fmod, frexp, ldexp, log, log10, modf, pow, sin, sinh, sqrt, tan and tanh. - Header file for inline functions: carry, irq, imask. - Header file for type bool and values true, false. - Header file for types: size_t, wchar_t and ptrdiff_t. 78 Using The Compiler © 2007 COSMIC Software Descriptions of C Library Functions - Header file for stream input/output: getchar, gets, printf, putchar, puts and sprintf. - Header file for general utilities: abs, abort, atof, atoi, atol, div, exit, labs, ldiv, rand, srand, strtod, strtol and strtoul. - Header file for string functions: memchr, memcmp, memcpy, memmove, memset, strcat, strchr, strcmp, strcpy, strcspn, strlen, strncat, strncmp, strncpy, strpbrk, strrchr, strspn and strstr. 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. Descriptions of C Library Functions The following pages describe each of the functions in the C library in quick reference format. The descriptions are in alphabetical order by function name. 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. © 2007 COSMIC Software Using The Compiler 79 4 C Library - _asm _asm Description Generate inline assembly code Syntax _asm(“string constant”, arguments...) Function _asm() generates inline assembly code by copying and quoting it into the output assembly code stream. 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 possible, and all other arguments are pushed onto the stack. After the 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: _asm(“inc x\n call _main”); Note that the string-quoting syntax matches the familiar printf() function. Notes _asm() is not packaged in any library. It is recognized by the compiler itself. For more information, see “Inserting Inline Assembly Instructions” in Chapter 3. 80 Using The Compiler © 2007 COSMIC Software C Library - abort abort Description Abort program execution Syntax #include 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. © 2007 COSMIC Software Using The Compiler 81 4 C Library - abs abs Description Find absolute value Syntax #include 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: printf(“balance %d%s\n”, abs(bal), (bal < 0)? “CR” : “”); See Also labs, fabs Notes abs is packaged in the integer library, and may be implemented as a macro. 82 Using The Compiler © 2007 COSMIC Software C Library - acos acos Description Arccosine Syntax #include double acos(double x) Function acos computes the angle in radians the cosine of which is x, to full double 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. © 2007 COSMIC Software Using The Compiler 83 4 C Library - asin asin Description Arcsine Syntax #include 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. 84 Using The Compiler © 2007 COSMIC Software C Library - atan atan Description Arctangent Syntax #include 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: theta = atan(y/x) * 180.0 / pi; See Also acos, asin, atan2 Notes atan is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 85 4 C Library - atan2 atan2 Description Arctangent of y/x Syntax #include 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: theta = atan2(y/x) * 180.0/pi; See Also acos, asin, atan Notes atan2 is packaged in the floating point library. 86 Using The Compiler © 2007 COSMIC Software C Library - atof atof Description Convert buffer to double Syntax #include 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 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’. No checks are made against overflow, underflow, or invalid character strings. Return Value atof returns the converted double value. If the string has no recognizable 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. © 2007 COSMIC Software Using The Compiler 87 4 C Library - atoi atoi Description Convert buffer to integer Syntax #include 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 unrecognizable character. Acceptable characters are the decimal digits. If the stop character is l or L, it is skipped over. No checks are made against overflow or invalid character strings. Return Value atoi returns the converted integer value. If the string has no recognizable 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. 88 Using The Compiler © 2007 COSMIC Software C Library - atol atol Description Convert buffer to long Syntax #include 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. No checks are made against overflow or invalid character strings. 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. © 2007 COSMIC Software Using The Compiler 89 4 C Library - carry carry Description Test or get the carry bit Syntax #include @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; if (carry()) ++high; produces sll _low jruge L1 inc _high L1: low <<= 1; high = carry() produces sll clr rlc ld _low a a _high,a 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. 90 Using The Compiler © 2007 COSMIC Software C Library - ceil ceil Description Round to next higher integer Syntax #include 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 5.1 5.0 0.0 -5.0 -5.1 ceil(x) 6.0 5.0 0.0 -5.0 -5.0 See Also floor Notes ceil is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 91 4 C Library - _checksum _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. _checksum is packaged in the integer library. See Also _checksumx, _checksum16, _checksum16x 92 Using The Compiler © 2007 COSMIC Software C Library - _checksumx _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 the checksum is correct, or a value different 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. _checksumx is packaged in the integer library. See Also _checksum, _checksum16, _checksum16x © 2007 COSMIC Software Using The Compiler 93 4 C Library - _checksum16 _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. _checksum16 is packaged in the integer library. See Also _checksum, _checksumx, _checksum16x 94 Using The Compiler © 2007 COSMIC Software C Library - _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 the checksum is correct, or a value different 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. _checksum16x is packaged in the integer library. See Also _checksum, _checksumx, _checksum16 © 2007 COSMIC Software Using The Compiler 95 4 C Library - cos cos Description Cosine Syntax #include double cos(double x) Function cos computes the cosine of x, expressed in radians, to full double precision. 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: xnew = xold * cos(theta) - yold * sin(theta); ynew = xold * sin(theta) + yold * cos(theta); See Also sin, tan Notes cos is packaged in the floating point library. 96 Using The Compiler © 2007 COSMIC Software C Library - cosh cosh Description Hyperbolic cosine Syntax #include 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 represented, cosh returns zero. Example To use the Moivre's theorem to compute (cosh x + sinh x) to the nth power: demoivre = cosh(n * x) + sinh(n * x); See Also exp, sinh, tanh Notes cosh is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 97 4 C Library - div div Description Divide with quotient and remainder Syntax #include div_t div(int numer, int denom) Function div divides the integer numer by the integer denom and returns the quotient and the remainder in a structure of type div_t. The field quot contains 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. 98 Using The Compiler © 2007 COSMIC Software C Library - eepera eepera Description Erase the full eeprom space Syntax void eepera(void) Function eepera erases the full eeprom space with the global erase sequence. It does not erase the config register. Return Value Nothing. Example To erase the full eeprom space: eepera(); See Also Notes eepera is packaged in the machine library. © 2007 COSMIC Software Using The Compiler 99 4 C Library - exit exit Description Exit program execution Syntax #include void exit(int status) Function exit stops the execution of a program by switching to the startup module 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. 100 Using The Compiler © 2007 COSMIC Software C Library - exp exp Description Exponential Syntax #include 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 represented, exp returns zero. Example To compute the hyperbolic sine of x: sinh = (exp(x) - exp(-x)) / 2.0; See Also log Notes exp is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 101 4 C Library - fabs fabs Description Find double absolute value Syntax #include 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 0.0 -3.7 5.0 0.0 3.7 See Also abs, labs Notes fabs is packaged in the floating point library. 102 Using The Compiler © 2007 COSMIC Software C Library - _fctcpy _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 location 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 information, see “Moveable Code” in Chapter 6. Return Value _fctcpy returns a non zero value if a segment has been found and copied. It returns 0 otherwise. Example if (_fctcpy(‘b’)) flash(); Notes _fctcpy is packaged in the machine library. © 2007 COSMIC Software Using The Compiler 103 4 C Library - floor floor Description Round to next lower integer Syntax #include 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 5.1 5.0 0.0 -5.0 -5.1 floor(x) 5.0 5.0 0.0 -5.0 -6.0 See Also ceil Notes floor is packaged in the floating point library. 104 Using The Compiler © 2007 COSMIC Software C Library - fmod fmod Description Find double modulus Syntax #include double fmod(double x, double y) Function fmod computes the floating point remainder of x / y, to full double precision. 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 5.5 5.0 0.0 -5.5 y 5.0 5.0 0.0 5.0 fmod(x, y) 0.5 0.0 0.0 -0.5 Notes fmod is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 105 4 C Library - frexp frexp Description Extract fraction from exponent part Syntax #include double frexp(double val, int *exp) Function frexp partitions the double at val, which should be non-zero, into a fraction 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. 106 Using The Compiler © 2007 COSMIC Software C Library - getchar getchar Description Get character from input stream Syntax #include 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: while ((c = getchar()) != EOF) putchar(c); See Also putchar Notes getchar is packaged in the integer library, and is by default using the first serial port SCI 1. © 2007 COSMIC Software Using The Compiler 107 4 C Library - gets gets Description Get a text line from input stream Syntax #include 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. gets uses getchar to read each character. 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. gets is packaged in the integer library. 108 Using The Compiler © 2007 COSMIC Software C Library - imask imask Description Test the interrupt mask bit Syntax #include @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()) ++high; produces jrnm inc L3 _high bms inc L1 _high L3: if (!imask()) ++high produces L1: 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. © 2007 COSMIC Software Using The Compiler 109 4 C Library - irq irq Description Test the interrupt line level Syntax #include @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()) ++high; produces jril inc L3 _high bih inc L1 _high L3: if (!irq()) ++high produces L1: Notes irq 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. 110 Using The Compiler © 2007 COSMIC Software C Library - isalnum isalnum Description Test for alphabetic or numeric character Syntax #include 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. isalnum is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 111 4 C Library - isalpha isalpha Description Test for alphabetic character Syntax #include 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. Otherwise the value returned is zero. Example To find the end points of an alphabetic string: while (*first && !isalpha(*first)) ++first; for (last = first; isalpha(*last); ++last) ; See Also isalnum, isdigit, islower, isupper, isxdigit, tolower, toupper Notes If the argument is outside the range [-1, 255], the result is undefined. isalpha is packaged in the integer library. 112 Using The Compiler © 2007 COSMIC Software C Library - iscntrl iscntrl Description Test for control character Syntax #include int iscntrl(char c) Function iscntrl tests whether c is a delete character (0177 in ASCII), or an ordinary 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: for (; *s; ++s) if (iscntrl(*s)) *s = '%'; See Also isgraph, isprint, ispunct, isspace Notes If the argument is outside the range [-1, 255], the result is undefined. iscntrl is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 113 4 C Library - isdigit isdigit Description Test for digit Syntax #include 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: for (sum = 0; isdigit(*s); ++s) sum = sum * 10 + *s - '0'; See Also isalnum, isalpha, islower, isupper, isxdigit, tolower, toupper Notes If the argument is outside the range [-1, 255], the result is undefined. isdigit is packaged in the integer library. 114 Using The Compiler © 2007 COSMIC Software C Library - isgraph isgraph Description Test for graphic character Syntax #include int isgraph(char c) Function isgraph tests whether c is a graphic character; i.e. any printing character 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: for (; *s; ++s) if (isgraph(*s)) putchar(*s); See Also iscntrl, isprint, ispunct, isspace Notes If the argument is outside the range [-1, 255], the result is undefined. isgraph is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 115 4 C Library - islower islower Description Test for lowercase character Syntax #include 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. islower is packaged in the integer library. 116 Using The Compiler © 2007 COSMIC Software C Library - isprint isprint Description Test for printing character Syntax #include 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: for (; *s; ++s) if (isprint(*s)) putchar(*s); See Also iscntrl, isgraph, ispunct, isspace Notes If the argument is outside the range [-1, 255], the result is undefined. isprint is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 117 4 C Library - ispunct ispunct Description Test for punctuation character Syntax #include int ispunct(char c) Function ispunct tests whether c is a punctuation character. Punctuation characters 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: for (i = 0; *s; ++s) if (ispunct(*s)) buf[i++] = *s; See Also iscntrl, isgraph, isprint, isspace Notes If the argument is outside the range [-1, 255], the result is undefined. ispunct is packaged in the integer library. 118 Using The Compiler © 2007 COSMIC Software C Library - isspace isspace Description Test for whitespace character Syntax #include int isspace(char c) Function isspace tests whether c is a whitespace character. Whitespace characters 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. isspace is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 119 4 C Library - isupper 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. isupper is packaged in the integer library. 120 Using The Compiler © 2007 COSMIC Software C Library - isxdigit isxdigit Description Test for hexadecimal digit Syntax #include 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: for (sum = 0; isxdigit(*s); ++s) if (isdigit(*s) sum = sum * 10 + *s - '0'; else sum = sum * 10 + tolower(*s) + (10 - 'a'); See Also isalnum, isalpha, isdigit, islower, isupper, tolower, toupper Notes If the argument is outside the range [-1, 255], the result is undefined. isxdigit is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 121 4 C Library - labs labs Description Find long absolute value Syntax #include 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: printf(“balance %ld%s\n”,labs(bal),(bal < 0) ? “CR” : “”); See Also abs, fabs Notes labs is packaged in the integer library. 122 Using The Compiler © 2007 COSMIC Software C Library - ldexp ldexp Description Scale double exponent Syntax #include 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 1.0 1.0 1.0 0.0 exp 1 0 -1 0 ldexp(x, exp) 2.0 1.0 0.5 0.0 See Also frexp, modf Notes ldexp is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 123 4 C Library - ldiv ldiv Description Long divide with quotient and remainder Syntax #include 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 remainder. 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. 124 Using The Compiler © 2007 COSMIC Software C Library - log log Description Natural logarithm Syntax #include 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: arccosh = log(x + sqrt(x * x - 1)); See Also exp Notes log is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 125 4 C Library - log10 log10 Description Common logarithm Syntax #include double log10(double x) Function log10 computes the common log of x to full double precision by computing 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 argument 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. 126 Using The Compiler © 2007 COSMIC Software C Library - max max Description Test for maximum Syntax #include 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 parenthesized. Example To set a new maximum level: hiwater = max(hiwater, level); See Also min Notes max is an extension to the proposed ANSI C standard. max is a macro declared in the header file. You can use it by including 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. © 2007 COSMIC Software Using The Compiler 127 4 C Library - memchr memchr Description Scan buffer for character Syntax #include 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: if ((t = memchr(keybuf, *s, KEYSIZ)) != NULL) *s = subst[t - keybuf]; See Also strchr, strcspn, strpbrk, strrchr, strspn Notes memchr is packaged in the integer library. 128 Using The Compiler © 2007 COSMIC Software C Library - memcmp memcmp Description Compare two buffers for lexical order Syntax #include 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. © 2007 COSMIC Software Using The Compiler 129 4 C Library - memcpy memcpy Description Copy one buffer to another Syntax #include 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[]: memcpy(buf, “first string”, 12); memcpy(buf + 13, “, second string”, 15); See Also strcpy, strncpy Notes memcpy is packaged in the integer library and may be implemented as an inline function. 130 Using The Compiler © 2007 COSMIC Software C Library - memmove memmove Description Copy one buffer to another Syntax #include 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: memmove(buf, &buf[5], 10); See Also memcpy Notes memmove is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 131 4 C Library - memset memset Description Propagate fill character throughout buffer Syntax #include 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. 132 Using The Compiler © 2007 COSMIC Software C Library - min min Description Test for minimum Syntax #include 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 parenthesized. Example To set a new minimum level: nmove = min(space, size); See Also max Notes min is an extension to the ANSI C standard. min is a macro declared in the header file. You can use it by including 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. © 2007 COSMIC Software Using The Compiler 133 4 C Library - modf modf Description Extract fraction and integer from double Syntax #include double modf(double val, double *pd) Function modf partitions the double val into an integer portion, which is delivered 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 5.1 5.0 4.9 0.0 -1.4 *pd 5 5 4 0 -1 modf(val, *pd) 0.1 0.0 0.9 0.0 -0.4 See Also frexp, ldexp Notes modf is packaged in the floating point library. 134 Using The Compiler © 2007 COSMIC Software C Library - pow pow Description Raise x to the y power Syntax #include 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 double 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 2.0 2.0 2.0 1.0 0.0 -1.0 -1.0 y 2.0 1.0 0.0 any -2.0 2.0 2.1 pow(x, y) 4.0 2.0 1.0 1.0 0 1.0 0 See Also exp Notes pow is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 135 4 C Library - printf printf Description Output formatted arguments to stdout Syntax #include 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. printf uses putchar to output each character. 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 format string is encountered. Each is started by the character ‘%’. After the ‘%’, the following appear in sequence: - zero or more which modify the meaning of the conversion specification. - a decimal number which optionally specifies a minimum field width. If the converted value has fewer characters than the field width, it is padded on the left (or right, if the left adjustment flag has been given) to the field width. The padding is with spaces unless the field width digit string starts with zero, in which case the padding is with zeros. 136 Using The Compiler © 2007 COSMIC Software C Library - printf - a decimal number which specifies the minimum number of digits to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the decimal point for e, E, and f conversions, the maximum number of significant digits for the g and G conversions, or the maximum number of characters to be printed from a string in an s conversion. The precision takes the form of a period followed by a decimal digit string. A null digit string is treated as zero. h - optionally specifies that the following d, i, o, u, x, or X conversion character applies to a short int or unsigned short int argument (the argument will have been widened according to the integral widening conversions, and its value must be cast to short or unsigned short before printing). It specifies a short pointer argument if associated with the p conversion character. If an h appears with any other conversion character, it is ignored. l - optionally specifies that the d, i, o, u, x, and X conversion character applies to a long int or unsigned long int argument. It specifies a long or far pointer argument if used with the p conversion character. If the l appears with any other conversion character, it is ignored. L - optionally specifies that the following e, E, f, g, and G conversion character applies to a long double argument. If the L appears with any other conversion character, it is ignored. - character that indicates the type of conversion to be applied. A field width or precision, or both, may be indicated by an asterisk '*' instead of a digit string. In this case, an int argument supplies the field width or precision. The arguments supplying field width must appear before the optional argument to be converted. A negative field width argument is taken as a - flag followed by a positive field width. A negative precision argument is taken as if it were missing. The field is zero or more of the following: space - a space will be prepended if the first character of a signed conversion is not a sign. This flag will be ignored if space and + flags are both specified. © 2007 COSMIC Software Using The Compiler 137 4 C Library - printf # - result is to be converted to an “alternate form”. For c, d, i, s, and u conversions, the flag has no effect. For o conversion, it increases the precision to force the first digit of the result to be zero. For p, x and X conversion, a non-zero result will have Ox or OX prepended to it. For e, E, f, g, and G conversions, the result will contain a decimal point, even if no digits follow the point. For g and G conversions, trailing zeros will not be removed from the result, as they normally are. For p conversion, it designates hexadecimal output. + - result of signed conversion will begin with a plus or minus sign. - - result of conversion will be left justified within the field. The is one of the following: % - a ‘%’ is printed. No argument is converted. c - the char argument is converted to a character and printed. d, i, o, u, x, X - the int argument is converted to signed decimal (d or i), unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal notation (x or X); the letters abcdef are used for x conversion and the letters ABCDEF are used for X conversion. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it will be expanded with leading zeros. The default precision is 1. The result of converting a zero value with precision of zero is no characters. e, E - the double argument is converted in the style [-]d.ddde+dd, where there is one digit before the decimal point and the number of digits after it is equal to the precision. If the precision is missing, six digits are produced; if the precision is zero, no decimal point appears. The E format code will produce a number with E instead of e introducing the exponent. The exponent always contains at least two digits. However, if the magnitude to be printed is greater than or equal to 1E+100, additional exponent digits will be printed as necessary. f - the double argument is converted to decimal notation in the style [-]ddd.ddd, where the number of digits following the decimal point is equal to the precision specification. If the precision is missing, it is 138 Using The Compiler © 2007 COSMIC Software C Library - printf taken as 6. If the precision is explicitly zero, no decimal point appears. If a decimal point appears, at least one digit appears before it. g, G - the double argument is printed in style f or e (or in style E in the case of a G format code), with the precision specifying the number of significant digits. The style used depends on the value converted; style e will be used only if the exponent resulting from the conversion is less than -4 or greater than the precision. Trailing zeros are removed from the result; a decimal point appears only if it is followed by a digit. n - the argument is taken to be an int * pointer to an integer into which is written the number of characters written to the output stream so far by this call to printf. No argument is converted. p - the argument is taken to be a void * pointer to an object. The value of the pointer is converted to a sequence of printable characters, and printed as a hexadecimal number with the number of digits printed being determined by the field width. s, S - the argument is taken to be a char * pointer to a string. When the Compact model is used, the s format will use a @tiny pointer and the S format will use a @near pointer. Characters from the string are written up to, but not including, the terminating NUL, or until the number of characters indicated by the precision are written. If the precision is missing, it is taken to be arbitrarily large, so all characters before the first NUL are printed. If the character after '%' is not a valid conversion character, the behavior is undefined. If any argument is or points to an aggregate (except for an array of characters using %s conversion or any pointer using %p conversion), unpredictable results will occur. A nonexistent or small field width does not cause truncation of a field; if the result is wider than the field width, the field is expanded to contain the conversion result. Return Value printf returns the number of characters transmitted, or a negative number if a write error occurs. © 2007 COSMIC Software Using The Compiler 139 4 C Library - printf 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); both forms will output: 05100.53 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 version cannot print or manipulate floating point numbers. If your programs 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. If printf encounters an invalid conversion specifier, the invalid specifier is ignored and no special message is generated. 140 Using The Compiler © 2007 COSMIC Software C Library - putchar putchar Description Put a character to output stream Syntax #include int putchar(char c) Function putchar copies c to the user specified output stream. You must rewrite putchar in either C or assembly language to provide an interface to the output mechanism to the C library. Return Value putchar returns c. If a write error occurs, putchar returns EOF. Example To copy input to output: while ((c = getchar()) != EOF) putchar(c); See Also getchar Notes putchar is packaged in the integer library, and is by default using the first serial port SCI 1. © 2007 COSMIC Software Using The Compiler 141 4 C Library - puts puts Description Put a text line to output stream Syntax #include 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. 142 Using The Compiler © 2007 COSMIC Software C Library - rand rand Description Generate pseudo-random number Syntax #include 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. © 2007 COSMIC Software Using The Compiler 143 4 C Library - sin sin Description Sin Syntax #include double sin(double x) Function sin computes the sine of x, expressed in radians, to full double precision. 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: xnew = xold * cos(theta) - yold * sin(theta); ynew = xold * sin(theta) + yold * cos(theta); See Also cos, tan Notes sin is packaged in the floating point library. 144 Using The Compiler © 2007 COSMIC Software C Library - sinh sinh Description Hyperbolic sine Syntax #include 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 represented, sinh returns zero. Example To obtain the hyperbolic sine of complex z: typedef struct { double x, iy; }complex; complex z; z.x = sinh(z.x) * cos(z.iy); z.iy = cosh(z.x) * sin(z.iy); See Also cosh, exp, tanh Notes sinh is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 145 4 C Library - sprintf sprintf Description Output arguments formatted to buffer Syntax #include 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 terminating NUL character. Example To format a double at d into buf: sprintf(buf, “%10f\n”, d); 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 subset of the functionality of the floating point version. The integer only version cannot print or manipulate floating point numbers. If your programs 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. 146 Using The Compiler © 2007 COSMIC Software C Library - sqrt sqrt Description Real square root Syntax #include 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: if (!(n & 01)) return (NOTPRIME); sq = sqrt((double)n); for (div = 3; div <= sq; div += 2) if (!(n % div)) return (NOTPRIME); return (PRIME); Notes sqrt is packaged in the floating point library. © 2007 COSMIC Software Using The Compiler 147 4 C Library - srand srand Description Seed pseudo-random number generator Syntax #include void srand(unsigned char nseed) Function srand uses nseed as a seed for a new sequence of pseudo-random numbers 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. 148 Using The Compiler © 2007 COSMIC Software C Library - strcat strcat Description Concatenate strings Syntax #include 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. strcat is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 149 4 C Library - strchr strchr Description Scan string for first occurrence of character Syntax #include 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. 150 Using The Compiler © 2007 COSMIC Software C Library - strcmp strcmp Description Compare two strings for lexical order Syntax #include 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. © 2007 COSMIC Software Using The Compiler 151 4 C Library - strcpy strcpy Description Copy one string to another Syntax #include 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. strcpy is packaged in the integer library, and may be implemented as an inline function. 152 Using The Compiler © 2007 COSMIC Software C Library - strcspn strcspn Description Find the end of a span of characters in a set Syntax #include unsigned int strcspn(char *s1, char *s2) Function strcspn scans the string starting at s1 for the first occurrence of a character in the string starting at s2. It computes a subscript i such that: • s1[i] is a character in the string starting at s1 • s1[i] compares equal to some character in the string starting at s2, which may be its terminating null character. Return Value strcspn returns the lowest possible value of i. s1[i] designates the terminating 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: if (!str[i = strcspn(str, “0123456789+-”)]) printf(“can't find number\n”); See Also memchr, strchr, strpbrk, strrchr, strspn Notes strcspn is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 153 4 C Library - strlen strlen Description Find length of a string Syntax #include unsigned int strlen(char *s) Function strlen scans the text string starting at s to determine the number of characters 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. 154 Using The Compiler © 2007 COSMIC Software C Library - strncat strncat Description Concatenate strings of length n Syntax #include 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 terminating 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. © 2007 COSMIC Software Using The Compiler 155 4 C Library - strncmp strncmp Description Compare two n length strings for lexical order Syntax #include 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 compared, 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. 156 Using The Compiler © 2007 COSMIC Software C Library - strncpy strncpy Description Copy n length string Syntax #include 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: strncpy(dest, s2, n); See Also memcpy, strcpy Notes If the string s2 points at is longer than n characters, the result may not be NUL-terminated. strncpy is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 157 4 C Library - strpbrk strpbrk Description Find occurrence in string of character in set Syntax #include 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): while (string = strpbrk(string, “‘{|}~”)) *string = '@'; See Also memchr, strchr, strcspn, strrchr, strspn Notes strpbrk is packaged in the integer library. 158 Using The Compiler © 2007 COSMIC Software C Library - strrchr strrchr Description Scan string for last occurrence of character Syntax #include 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. © 2007 COSMIC Software Using The Compiler 159 4 C Library - strspn strspn Description Find the end of a span of characters not in set Syntax #include unsigned int strspn(char *s1, char *s2) Function strspn scans the string starting at s1 for the first occurrence of a character not in the string starting at s2. It computes a subscript i such that • s1[i] is a character in the string starting at s1 • s1[i] compares equal to no character in the string starting at s2, except possibly its terminating null character. Return Value strspn returns the lowest possible value of i. s1[i] designates the terminating 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. 160 Using The Compiler © 2007 COSMIC Software C Library - strstr strstr Description Scan string for first occurrence of string Syntax #include 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. © 2007 COSMIC Software Using The Compiler 161 4 C Library - strtod strtod Description Convert buffer to double Syntax #include 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 overflow, underflow, or invalid character strings. Return Value strtod returns the converted double value. If the string has no recognizable 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. 162 Using The Compiler © 2007 COSMIC Software C Library - strtol strtol Description Convert buffer to long Syntax #include 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, 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. No checks are made against overflow or invalid character strings. Return Value strtol 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 = strtol(buf, NULL, 0); See Also atof, atoi, strtoul, strtod Notes strtol is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 163 4 C Library - strtoul strtoul Description Convert buffer to unsigned long Syntax #include 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, 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, 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. No checks are made against overflow or invalid character strings. Return Value strtoul 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 = strtoul(buf, NULL, 0); See Also atof, atoi, strtol, strtod Notes strtoul is a macro redefined to strtol. 164 Using The Compiler © 2007 COSMIC Software C Library - tan tan Description Tangent Syntax #include double tan(double x) Function tan computes the tangent of x, expressed in radians, to full double precision. 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. © 2007 COSMIC Software Using The Compiler 165 4 C Library - tanh tanh Description Hyperbolic tangent Syntax #include double tanh(double x) Function tanh computes the value of the hyperbolic tangent of x to double precision. 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 represented, 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. 166 Using The Compiler © 2007 COSMIC Software C Library - tolower tolower Description Convert character to lowercase if necessary Syntax #include int tolower(char c) Function tolower converts an uppercase letter to its lowercase equivalent, leaving all other characters unmodified. Return Value tolower returns the corresponding lowercase letter, or the unchanged character. Example To accumulate a hexadecimal digit: for (sum = 0; isxdigit(*s); ++s) if (isdigit(*s) sum = sum * 16 + *s - '0'; else sum = sum * 16 + tolower(*s) + (10 - 'a'); See Also toupper Notes tolower is packaged in the integer library. © 2007 COSMIC Software Using The Compiler 167 4 C Library - toupper toupper Description Convert character to uppercase if necessary Syntax #include 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: for (i = 0; i < size; ++i) buf[i] = toupper(buf[i]); See Also tolower Notes toupper is packaged in the integer library. 168 Using The Compiler © 2007 COSMIC Software CHAPTER 5 Using The Assembler The castm8 cross assembler translates your assembly language source files into relocatable object files. The C cross compiler calls castm8 to assemble your code automatically, unless specified otherwise. castm8 generates also listings if requested. This chapter includes the following sections: • Invoking castm8 • Object File • Listings • Assembly Language Syntax • Branch Optimization • Old Syntax • C Style Directives • Assembler Directives © 2007 COSMIC Software Using The Assembler 169 5 Invoking castm8 Invoking castm8 castm8 accepts the following command line options, each of which is described in detail below: castm8 [options] -a absolute assembler -b do not optimizes branches -c output cross reference -d*> define symbol=value +e* error file name -ff use formfeed in listing -ft force title in listing -f# fill byte value -h* include header -i*> include path -l output listing +l* listing file name -m accept old syntax -mi accept label syntax -o* output file name -pe all equates public -p all symbols public -pl keep local symbol -u undefined in listing -v be verbose -x include line debug info -xp no path in debug info -xx include full debug info Castm8 Option Usage Option Description -a map all sections to absolute, including the predefined ones. -b do not optimize branch instructions. By default, the assembler replaces long branches by short branches wherever a shorter instruction can be used, and short branches by long branches wherever the displacement is too large. This optimization also applies to jump and jump to subroutines instructions. 170 Using The Assembler © 2007 COSMIC Software Invoking castm8 Castm8 Option Usage (cont.) Option Description -c produce cross-reference information. The cross-reference information will be added at the end of the listing file. This option enforces the -l option. -d*> where * has the form name=value, defines name to have the value specified by value. This option is equivalent to using an equ directive in each of the source files. +e* log errors from assembler in the text file * instead of displaying the messages on the terminal screen. -ff use formfeed character to skip pages in listing instead of using blank lines. -ft output a title in listing (date, file name, page). By default, no title is output. -f# define the value of the filling byte used to fill any gap created by the assembler directives. Default is 0. -h* include the file specified by * before starting assembly. It is equivalent to an include directive in each source file. -i*> define a path to be used by the include directive. Up to 20 paths can be defined. A path is a directory name and is not ended by any directory separator character. -l create a listing file. The name of the listing file is derived from the input file name by replacing the suffix by the ‘.ls’ extension, unless the +l option has been specified. +l* create a listing file in the text file *. If both -l and +l are specified, the listing file name is given by the +l option. -m accept the old syntax. -mi accept label that is not ended with a ‘:’ character. -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. © 2007 COSMIC Software Using The Assembler 171 5 Object File Castm8 Option Usage (cont.) Option Description -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. -u produce an error message in the listing file for all occurrence of an undefined symbol. This option enforces the -l option. -v display the name of each file which is processed. -x add line debug information to the object file. -xp do not prefix filenames in the debug information with any absolute path name. Debuggers will have to be informed about the actual files location. -xx add debug information in the object file for any label defining code or data. This option disables the -p option as only public or used labels are selected. Each source file specified by will be assembled separately, and will produce separate object and listing files. For each source file, if no errors are detected, castm8 generates an object file. If requested by the l or -c options, castm8 generates a listing file even if errors are detected. Such lines are followed by an error message in the listing. 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. 172 Using The Assembler © 2007 COSMIC Software Listings Listings The listing stream contains the source code used as input to the assembler, 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:
where
is the hexadecimal relocatable address where the has been assembled, is the hexadecimal representation of the object code generated by the assembler and is the original source line input to the assembler. If expansion of data, macros and included files is not enabled, the print will not contain a complete listing of all generated code. Addresses in the listing output are the offsets from the start of the current 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. Several directives are available to modify the listing display, such as title for the page header, plen for the page length, page for starting a new page, tabs for the tabulation characters expansion. By default, the listing file is not paginated. Pagination is enabled by using at least one title directive in the source file, or by specifying the -ft option on the command line. Otherwise, the plen and page directives are simply ignored. Some other directives such as clist, mlist or dlist control the amount of information produced in the listing. A cross-reference table will be appended to the listing if the -c option has been specified. This table gives for each symbol its value, its attributes, the line number of the line where it has been defined, and the list of line numbers where it is referenced. © 2007 COSMIC Software Using The Assembler 173 5 Assembly Language Syntax Assembly Language Syntax The assembler castm8 conforms to the STM8 syntax as described in the document Assembly Language Input Standard. The assembly language consists of lines of text in the form: [label:] [command [operands]] [; comment] or ; comment where ‘:’ indicates the end of a label and ‘;’ defines the start of a comment. The end of a line terminates a comment. The command field may be an instruction, a directive or a macro call. Instruction mnemonics and assembler directives may be written in upper or lower case. The C compiler generates lowercase assembly language. 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: adc add addw and bccm bcp bcpl bkpt bres bset btjf btjt call callf callr ccf clr clrw cp cpl cplw cpw dec decw div divw exg exgw halt inc 174 Using The Assembler incw iret jp jpf jra jrc jreq jrf jrh jrih jril jrm jrmi jrnc jrne jrnh jrnm jrnv jrpl jrsge jrsgt jrsle jrslt jrt jruge jrugt jrule jrult jrv ld ldf ldw mov mul neg negw nop or pop popw push pushw rcf ret retf rim rlc rlcw rlwa rrc rrcw rrwa rvf sbc scf sim sla slaw sll sllw sra sraw srl srlw sub subw swap swapw tnz tnzw trap wfe wfi xor © 2007 COSMIC Software Assembly Language Syntax The operand field of an instruction uses an addressing mode to describe the instruction argument. The following examples demonstrate the accepted syntax: rcf push ld and ld ld ld jrne bset btjt y a,#1 a,var a,(2,x) a,[var] a,([var.w],y) loop 2,#1 2,#1,loop ; ; ; ; ; ; ; ; ; ; implicit register immediate short, long indexed indirect indirect indexed long relative bit number bit test and branch The assembler chooses the smallest addressing mode where several solutions are possible. Short addressing mode is selected when using a label defined in the .bsct section. For an exact description of the above instructions, refer to the ST Microelectronics’s STM8 Family Programming Manual. 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 an alphabetic character, the underscore character ‘_’ or the period character ‘.’. It is continued by alphabetic (A-Z or a-z) or numeric (0-9) characters, underscores, dollar signs ($) or periods. Labels are case sensitive. The processor register names ‘a’ and ‘x’ are reserved and cannot be used as labels. data1: dc.b c_reg: ds.b $56 1 When a label is used within a macro, it may be expanded more than once and in that case, the assembler will fail with a multiply defined symbol error. In order to avoid that problem, the special sequence ‘\@’ may be used as a label prefix. This sequence will be replaced by a unique sequence for each macro expansion. This prefix is only allowed inside a macro definition. © 2007 COSMIC Software Using The Assembler 175 5 Assembly Language Syntax wait: macro \@loop:btjf endm PORTA,#1,\@loop 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 decimal 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$: 2$: dec jrne 1$ dec jrne 2$ Temporary labels do not appear in the symbol table or the cross reference list. For example, to define 3 different local blocks and create and use 3 different local labels named 10$: function1: 10$: ld jreq ld local 10$: ld jreq ld ret function2: 10$: ld sub jrne ret a,var 10$ a,var2 a,var2 10$ a,var a,var2 a,var 10$ Constants The assembler accepts numeric constants and string constants. Numeric constants are expressed in different bases depending on a prefix character as follows: 176 Using The Assembler © 2007 COSMIC Software Assembly Language Syntax Number 10 %1010 @12 $A Base decimal (no prefix) binary octal hexadecimal The assembler also accepts numerics constants in different bases depending on a suffix character as follow: Suffix D, d or none Base decimal (no prefix) B or b binary Q or q octal 0AH or 0Ah hexadecimal The suffix letter can be entered uppercase or lowercase. Hexadecimal numbers still need to start with a digit. String constants are a series of printable characters between single or double quote characters: ‘This is a string’ “This is also a string” Depending on the context, a string constant will be seen either as a series of bytes, for a data initialization, or as a numeric; in which case, the string constant should be reduced to only one character. hexa: dc.b start: cp © 2007 COSMIC Software ‘0123456789ABCDEF’ x,#’A’ ; ASCII value of ‘A’ Using The Assembler 177 5 Assembly Language Syntax 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. A special label written ‘*’ is used to represent the current location address. Note that when ‘*’ is used as the operand of an instruction, it has the value of the program counter before code generation for that instruction. The set of accepted operators is: + * / % & | ^ ~ << >> == != < <= > >= && || ! 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 These operators may be applied to constants without restrictions, but are restricted when applied to relocatable labels. For those labels, the addition and substraction operators only are accepted and only in the following cases: 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. 178 Using The Assembler © 2007 COSMIC Software Assembly Language Syntax An expression may also be constructed with a special operator. These expressions cannot be used with the previous operators and have to be specified alone. high(expression) low(expression) page(expression) upper byte lower byte page byte These special operators evaluate an expression and extract the appropriate information from the result. The expression may be relocatable, and may use the set of operators if allowed. high - extract the upper byte of the 16-bit expression low - extract the lower byte of the 16-bit expression page - extract the page value of the expression. It is computed by the linker according to the -bs option used. This is used to get the address extension when bank switching is used. 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. signex:macro clr tnz jrpl cpl \@pos: endm x a \@pos x ; ; ; ; ; sign extension prepare MSB test sign if not positive invert MSB ; end of macro 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: ld signex ld © 2007 COSMIC Software a,char+1 ; load LSB ; expand macro char,x ; store result Using The Assembler 179 5 Assembly Language Syntax The resulting code will be the same as if the following code had been written: ld clr tnz jrpl cpl a,char+1 ; x ; a ; pos ; x ; ld char,x load LSB prepare MSB test sign if not positive invert MSB pos: ; store result A macro may have up to 35 parameters. A parameter is written \1, \2,... \9, \A,...,\Z inside the macro body and refers explicitly to the first, second,... ninth argument and \A to \Z to denote the tenth to 35th operand on the invocation line, which are placed after the macro name, and separated by commas. Each argument replaces each occurrence of its corresponding parameter. An argument may be expressed as a string constant if it contains a comma character. A macro can also handle named arguments instead of numbered argument. In such a case, the macro directive is followed by a list of argument named, each prefixed by a \ character, and separated by commas. Inside the macro body, arguments will be specified using the same syntax or a sequence starting by a \ character followed by the argument named placed between parenthesis. This alternate syntax is useful to catenate the argument with a text string immediately starting with alphanumeric characters. The special parameter \# is replaced by a numeric value corresponding to the number of arguments actually found on the invocation line. In order to operate directly in memory, the previous macro may have been written using the numbered syntax: signex:macro clr ld jrpl cpl \@pos: ld endm 180 Using The Assembler x a,\1 \@pos x \1,x ; ; ; ; ; sign extension prepare MSB load LSB if not positive invert MSB ; store MSB ; end of macro © 2007 COSMIC Software Assembly Language Syntax And called: signex char ; sign extend char This macro may also be written using the named syntax: signex:macro clr ld jrpl cpl \@pos: ld endm \value x a,\value \@pos x ; ; ; ; ; sign extension prepare MSB load LSB if not positive invert MSB \(value),x ; store MSB ; end of macro The form of a macro call is: name>[.] [] The special parameter \0 corresponds to an extension which may follow the macro name, separated by the period character ‘.’. An extension is a single letter which may represent the size of the operands and the result. For example: table: macro dc.\0 endm 1,2,3,4 When invoking the macro: table.b will generate a table of byte: dc.b 1,2,3,4 When invoking the macro: table.w will generate a table of word: dc.w © 2007 COSMIC Software 1,2,3,4 Using The Assembler 181 5 Assembly Language Syntax The special parameter \* is replaced by a sequence containing the list of all the passed arguments separated by commas. This syntax is useful to pass all the macro arguments to another macro or a repeatl directive. The directive mexit may be used at any time to stop the macro expansion. 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. If a listing is produced, the macro expansion lines are printed if enabled by the mlist directive. If enabled, the invocation line is not printed, and all the expanded lines are printed with all the parameters replaced by their corresponding arguments. Otherwise, the invocation line only is printed. 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 condition 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 ld call endif debug == 1 x,#message print If the symbol debug is equal to 1, the next two lines are assembled. Otherwise they are skipped. if addptr else inc endif 182 Using The Assembler offset != 1 offset x ; ; ; ; if offset too large call a macro otherwise increment X register © 2007 COSMIC Software Assembly Language Syntax If the symbol offset is not one, the macro addptr is expanded with offset as argument, otherwise the aix instruction is directly assembled. Conditional directives may be nested. An else directive refers to the closest previous if directive, and an endif directive refers to the closest previous if or else directive. If a listing is produced, the skipped lines are printed only if enabled by the clist directive. Otherwise, only the assembled lines are printed. 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 following code and data thereto. The directive switch can be used to redirect the following code and data to another section. data: section text: section start: ld jp switch value: dc.b ; defines data section ; defines text section x,#value ; fills text section print data ; use now data section 1,2,3 ; fills data section The assembler allows up to 255 different sections. A section name is limited to 15 characters. If a section name is too long, it is simply truncated without any error message. The assembler predefines the following sections, meaning that a section directive is not needed before to use them: © 2007 COSMIC Software Using The Assembler 183 5 Assembly Language Syntax Section Description .text executable code .data initialized data .bss uninitialized data .bsct initialized data in zero page .ubsct non initialized data in zero page The sections .bsct and .ubsct are used for locating data in the zero page of the processor. The zero page 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 instructions 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 zero page 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 assembler may use 8 bit addressing modes. switch zvar2: ds.b switch var2: ds.b switch ld ld ld ld end .bsct 1 .bss 1 .text a,var a,zvar a,var2 a,var2 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- 184 Using The Assembler © 2007 COSMIC Software Assembly Language Syntax tion directive with the bit attribute. In a bit section, any directive creating 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. External definitions for bit symbols located in the zero page will used the xbit.b directive. PA3: .bit: b0: xbit.b equ section ds.b switch btjf bset b1 ; external bit declaration PORTA:3 ; bit 3 of byte PORTA zpage,bit; create bit section named “.bit” 1 ; allocates one bit .text PA3,skip ; use directly bit symbol b0 ; with bit instructions bres b1 skip: Bit sections are located at link time either at specified bit addresses or attached to any zero page 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. © 2007 COSMIC Software Using The Assembler 185 5 Branch Optimization 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. A conditional branch offset is limited to the range [-128,127]. If such an instruction cannot be encoded properly, the assembler will replace it by a sequence containing an inverted branch to the next location followed immediately by a jump to the original target address. The assembler keep track of the last replacement for each label, so if a long branch has already been expanded for the same label at a location close enough from the current instruction, the target address of the short branch will be changed only to branch on the already existing jump instruction to the specified label. jreq farlabel becomes jrne jp *+5 farlabel Note that a jra instruction will be replaced by a single jp instruction if it cannot be encoded as a relative branch. A jp or call instruction will be replaced by a jra or callr instruction if the destination address is in the same section than the current one, and if the displacement is in the range allowed by a relative branch. Old Syntax The -m option allows the assembler to accept old constructs which are now obsolete. The following features are added to the standard behaviour: • a comment line may begin with a ‘*’ character; • a label starting in the first column does not need to be ended with a ‘:’ character; • no error message is issued if an operand of the dc.b directive is too large; • the section directive handles numbered sections; 186 Using The Assembler © 2007 COSMIC Software C Style Directives The comment separator at the end of an instruction is still the ‘;’ character because the ‘*’ character is interpreted as the multiply operator. C Style Directives The assembler also supports C style directives matching the preprocessor directives of a C compiler. The following directives list shows the equivalence with the standard directives: C Style Assembler Style #include “file” include “file” #define label expression label: equ expression #define label label: equ 1 #if expression if expression #ifdef label ifdef label #ifndef label ifndef label #else else #endif endif #error “message” fail “message” NOTE The #define directive does not implement all the text replacement features 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. © 2007 COSMIC Software Using The Assembler 187 5 Assembler Directives - align align Description Align the next instruction on a given boundary Syntax align ,[] 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 is specified, it will be used locally as the filling byte, instead of the one specified by the -f option. Example align ds.b 3 1 ; next address is multiple of 3 See Also even 188 Using The Assembler © 2007 COSMIC Software Assembler Directives - base base Description Define the default base for numerical constants Syntax base Function The base directive sets the default base for numerical constants beginning with a digit. The base directive is followed by a constant expression 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 ld © 2007 COSMIC Software 8 a,#377 ; select octal base ; load $FF Using The Assembler 189 5 Assembler Directives - bsct 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 zero page section. The assembler will automatically select the short addressing mode when referencing an object defined in the .bsct section. Example bsct c_reg: 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 190 Using The Assembler © 2007 COSMIC Software Assembler Directives - clist 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 © 2007 COSMIC Software Using The Assembler 191 5 Assembler Directives - dc dc Description Allocate constant(s) Syntax dc[.size] [,...] Function The dc directive allocates and initializes storage for constants. If is a string constant, one byte is allocated for each character 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 . The dc.w directive will allocate one word per . The dc.l directive will allocate one long word per . Example digit: dc.b dc.w Note 10,'0123456789' digit For compatibility with previous assemblers, the directive fcb is alias to dc.b, and the directive fdb is alias to dc.w. 192 Using The Assembler © 2007 COSMIC Software Assembler Directives - dcb dcb Description Allocate constant block Syntax dcb. , Function The dcb directive allocates a memory block and initializes storage for constants. The size area is the number of the specified value of . The memory area can be initialized with the specified. The dcb and dcb.b directives will allocate one byte per . The dcb.w directive will allocate one word per . The dcb.l directive will allocate one long word per . Example digit: dcb.b © 2007 COSMIC Software 10,5 ; allocate 10 bytes, ; all initialized to 5 Using The Assembler 193 5 Assembler Directives - dlist 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. 194 Using The Assembler © 2007 COSMIC Software Assembler Directives - ds ds Description Allocate variable(s) Syntax ds[.size] Function The ds directive allocates storage space for variables. must be an absolute expression. Bytes created are set to the value of the filling byte defined by the -f option. The ds and ds.b directives will allocate bytes. The ds.w directive will allocate words. The ds.l directive will allocate long words. Example ptlec: ds.b ptecr: ds.b chrbuf: ds.w Note 2 2 128 For compatibility with previous assemblers, the directive rmb is alias to ds.b. © 2007 COSMIC Software Using The Assembler 195 5 Assembler Directives - else else Description Conditional assembly Syntax if instructions else instructions endc Function The else directive follows an if directive to define an alternative conditional sequence. It reverts the condition status for the following instructions up to the next matching endif directive. An else directive applies to the closest previous if directive. Example if addptr else inc endif Note offset != 1 offset x ; ; ; ; if offset too large call a macro otherwise increment X register The else and elsec directives are equivalent and may used without distinction. They are provided for compatibility with previous assemblers. See Also if, endif, clist 196 Using The Assembler © 2007 COSMIC Software Assembler Directives - elsec elsec Description Conditional assembly Syntax if instructions elsec instructions endc Function The elsec directive follows an if directive to define an alternative conditional sequence. It reverts the condition status for the following instructions up to the next matching endc directive. An elsec directive applies to the closest previous if directive. Example ifge addptr elsec inc endc Note offset-127 offset x ; ; ; ; if offset too large call a macro otherwise increment X register The elsec and else directives are equivalent and may used without distinction. They are provided for compatibility with previous assemblers. See Also if, endc, clist, else © 2007 COSMIC Software Using The Assembler 197 5 Assembler Directives - end end Description Stop the assembly Syntax end Function The end directive stops the assembly process. Any statements following it are ignored. If the end directive is encountered in an included file, it will stop the assembly process for the included file only. 198 Using The Assembler © 2007 COSMIC Software Assembler Directives - endc endc Description End conditional assembly Syntax if instructions endc Function The endc directive closes an if or elsec conditional directive. The conditional status reverts to the one existing before entering the if directives. The endc directive applies to the closest previous if or elsec directive. Example ifge addptr elsec inc endc Note offset-127 offset x ; ; ; ; if offset too large call a macro otherwise increment X register The endc and endif directives are equivalent and may used without distinction. They are provided for compatibility with previous assemblers. See Also if, elsec, clist, end © 2007 COSMIC Software Using The Assembler 199 5 Assembler Directives - endif endif Description End conditional assembly Syntax if instructions endif Function The endif directive closes an if, or else conditional directive. The conditional 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 addptr else inc endif Note offset != 1 offset x ; ; ; ; if offset too large call a macro otherwise increment X register The endif and endc directives are equivalent and may used without distinction. They are provided for compatibility with previous assemblers. See Also if, else, clist 200 Using The Assembler © 2007 COSMIC Software Assembler Directives - endm endm Description End macro definition Syntax label: macro 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: ds.b macro \@2 - \@1 ds.b \1 \@1: \@2: endm See Also mexit, macro © 2007 COSMIC Software Using The Assembler 201 5 Assembler Directives - endr endr Description End repeat section Syntax repeat endr Function The endr directive is used to terminate repeat sections. Example ; shift a value n times asln: macro repeat \1 sla endr endm ; use of above macro asln 10 ;shift 10 times See Also repeat, repeatl, rexit 202 Using The Assembler © 2007 COSMIC Software Assembler Directives - equ equ Description Give a permanent value to a symbol Syntax label: equ 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. must be either a constant expression, or a relocatable expression involving a symbol declared in the same section as the current 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 expression can be absolute or relocatable. Example false: true: tablen: nul: soh: stx: etx: eot: enq: equ equ equ equ equ equ equ equ equ 0 ; initialize these values 1 tabfin - tabsta;compute table length $0 ; define strings for ascii characters $1 $2 $3 $4 $5 PORTB: PB2: equ $1 equ PORTB:2 See Also lit, set © 2007 COSMIC Software Using The Assembler 203 5 Assembler Directives - even even Description Assemble next byte at the next even address relative to the start of a section. Syntax even [fill_] 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 filling byte defined by the -f option. If is specified, it will be used locally as the filling byte, instead of the one specified by the -f option. Example vowtab: dc.b even tentab: dc.w 204 Using The Assembler 'aeiou' ; ensure aligned at even address 1, 10, 100, 1000 © 2007 COSMIC Software Assembler Directives - fail 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 ifge fail © 2007 COSMIC Software 512 value - Max “Value too large” Using The Assembler 205 5 Assembler Directives - if if Description Conditional assembly Syntax if instructions endif or if instructions 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. If the if statement ends with an else directive, the expression result is inverted and the same process applies to the following instructions up to the next matching endif. So, if the if expression was not zero, the instructions between else and endif are skipped; otherwise, the instructions between else and endif are assembled. An else 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 if addptr else inc endif offset != 1 offset x ; ; ; ; if offset too large call a macro otherwise increment X register See Also else, endif, clist 206 Using The Assembler © 2007 COSMIC Software Assembler Directives - ifc ifc Description Conditional assembly Syntax ifc , orifc , 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 and are equals, 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 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 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 ifc ld elsec ld endc “hello”, \2 a,#45 ; if “hello” equals argument ; load 45 ; otherwise... a,#0 See Also elsec, endc, clist © 2007 COSMIC Software Using The Assembler 207 5 Assembler Directives - ifdef ifdef Description Conditional assembly Syntax ifdef

Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.3
Linearized                      : Yes
Modify Date                     : 2007:12:11 16:05:57Z
Create Date                     : 2007:12:11 15:58:44Z
Page Count                      : 456
Creation Date                   : 2007:12:11 15:58:44Z
Mod Date                        : 2007:12:11 16:05:57Z
Producer                        : Acrobat Distiller 5.0.5 (Windows)
Author                          : COSMIC Software France
Metadata Date                   : 2007:12:11 16:05:57Z
Creator                         : COSMIC Software France
Title                           : C Cross Compiler User’s Guide for STM8
Page Mode                       : UseOutlines
EXIF Metadata provided by EXIF.tools

Navigation menu