Hi-Tech C User Manual
Hi-Tech C User Manual
Mixed-Signal Array
HI-TECH Software.
Copyright (C) 2009 HI-TECH Software.
All Rights Reserved. Printed in Australia.
PSoC and Cypress are registered trademarks
of Cypress Semiconductor Corp.
Produced on: January 30, 2009
HI-TECH Software Pty. Ltd.
ACN 002 724 549
45 Colebard Street West
Acacia Ridge QLD 4110
Australia
email: [email protected]
web: http://cypress.htsoft.com
ftp: ftp://www.htsoft.com
Contents
Table of Contents 3
List of Figures 17
List of Tables 19
1 Introduction 21
1.1 Typographic conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3
CONTENTS CONTENTS
4
CONTENTS CONTENTS
3 C Language Features 69
3.1 ANSI Standard Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.1.1 Implementation-defined behaviour . . . . . . . . . . . . . . . . . . . . . . . 69
3.2 Processor-related Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
3.2.1 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
5
CONTENTS CONTENTS
3.2.2 Endianism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.3 Supported Data Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.3.1 Radix Specifiers and Constants . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.3.2 Bit Data Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 72
3.3.3 8-Bit Integer Data Types and Variables . . . . . . . . . . . . . . . . . . . . 73
3.3.4 16-Bit Integer Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
3.3.5 24-Bit Integer Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
3.3.6 32-Bit Integer Data Types and Variables . . . . . . . . . . . . . . . . . . . . 74
3.3.7 Floating Point Types and Variables . . . . . . . . . . . . . . . . . . . . . . . 74
3.3.8 Structures and Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3.3.8.1 Bitfields in Structures . . . . . . . . . . . . . . . . . . . . . . . . 75
3.3.8.2 Structure and Union Qualifiers . . . . . . . . . . . . . . . . . . . 77
3.3.9 Standard Type Qualifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.3.9.1 Const and Volatile Type Qualifiers . . . . . . . . . . . . . . . . . 78
3.3.10 Special Type Qualifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.3.10.1 Persistent Type Qualifier . . . . . . . . . . . . . . . . . . . . . . 78
3.3.10.2 __ioport Type Qualifier . . . . . . . . . . . . . . . . . . . . . . . 79
3.3.11 Pointer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.3.11.1 Combining Type Qualifiers and Pointers . . . . . . . . . . . . . . 80
3.3.11.2 Data Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3.3.11.3 Pointers to Const . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
3.3.11.4 Pointers to Both Memory Spaces . . . . . . . . . . . . . . . . . . 83
3.3.11.5 Function Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.4 Storage Class and Object Placement . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.4.1 Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.4.1.1 Auto Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.4.1.2 Static Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.4.2 Absolute Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.4.3 Objects in the Program Space . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.5.1 Function Qualifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.5.1.1 Interrupt Function Qualifier . . . . . . . . . . . . . . . . . . . . . 86
3.5.1.2 Reentrant Function Qualifier . . . . . . . . . . . . . . . . . . . . 86
3.5.1.3 Fastcall16 Function Qualifier . . . . . . . . . . . . . . . . . . . . 87
3.5.2 Function Argument Passing . . . . . . . . . . . . . . . . . . . . . . . . . . 87
3.5.2.1 Reentrant Function Parameters . . . . . . . . . . . . . . . . . . . 87
3.5.2.2 Non-reentrant Function Parameters . . . . . . . . . . . . . . . . . 87
3.5.3 Function Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.6 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
6
CONTENTS CONTENTS
7
CONTENTS CONTENTS
8
CONTENTS CONTENTS
9
CONTENTS CONTENTS
10
CONTENTS CONTENTS
11
CONTENTS CONTENTS
12
CONTENTS CONTENTS
GETCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
GETCHAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
GETS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
GMTIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
ISALNUM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
ISDIG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
ITOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
LABS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
LDEXP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
LDIV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
LOCALTIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
LOG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
LONGJMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
LTOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
MEMCHR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
MEMCMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
MEMCPY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
MEMSET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
MKTIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
MODF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
POW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
PUTCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
PUTCHAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
PUTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
QSORT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
RAND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
ROUND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
SETJMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
SIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
SPRINTF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
SQRT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
SRAND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
SSCANF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
STRCAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
STRCHR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
STRCMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
STRCPY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
STRCSPN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
STRLEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
13
CONTENTS CONTENTS
STRNCAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
STRNCMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
STRNCPY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
STRPBRK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
STRRCHR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
STRSPN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
STRSTR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
STRTOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
STRTOL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
STRTOK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
TAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
TIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
TOLOWER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
TRUNC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
UDIV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
ULDIV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
UNGETCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
UTOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
VA_START . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
XTOI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
14
CONTENTS CONTENTS
1032... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
1157... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
1242... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
Index 443
15
CONTENTS CONTENTS
16
List of Figures
17
LIST OF FIGURES LIST OF FIGURES
18
List of Tables
19
LIST OF TABLES LIST OF TABLES
20
Chapter 1
Introduction
21
Typographic conventions Introduction
22
Chapter 2
CPSOC is the driver invoked from the command line to perform all aspects of compilation, including
C code generation, assembly and link steps. It is the recommended way to use the compiler as it
hides the complexity of all the internal applications used in the compilation process and provides a
consistent interface for all compilation steps.
This chapter describes the steps the driver takes during compilation, files that the driver can
accept and produce, as well as the command-line options that control the compiler’s operation.
W HAT IS “ THE COMPILER”? Throughout this manual, the term “the compiler” is
used to refer to either all, or some subset of, the collection of applications that form the
HI-TECH C package. Often it is not important to know, for example, whether an action
is performed by the parser or code generator application, and it is sufficient to say it was
performed by “the compiler”.
It is also reasonable for “the compiler” to refer to the command-line driver (or just
“driver”), CPSOC, as this is the application executed to invoke the compilation process.
Following this view, “compiler options” should be considered command-line driver op-
tions, unless otherwise specified in this manual.
Similarly “compilation” refers to all, or some part of, the steps involved in generating
source code into an executable binary image.
23
Invoking the Compiler CPSOC Command-line Driver
It is conventional to supply options(identified by a leading dash “-” or double dash “–”) before
the filenames, although this is not mandatory.
The formats of the options are discussed below in Section 2.6, and a detailed description of each
option follows.
The files may be any mixture of C and assembler source files, and precompiled intermediate
files, such as relocatable object (.obj) files or p-code (.p1) files. The order of the files is not
important, except that it may affect the order in which code or data appears in memory, and may
affect the name of some of the output files.
Libraries is a list of either object code or p-code library files that will be searched by the
linker. The -L option, see Section 2.6.6, can also be used to specify library files to search.
CPSOC distinguishes source files, intermediate files and library files solely by the file type or
extension. Recognized file types are listed in Table 2.1. This means, for example, that an assembler
file must always have a .as extension. Alphabetic case of the extension is not important from the
compiler’s point of view.
•
M ODULES AND SOURCE FILES: A C source file is a file on disk that contains all or
part of a program. C source files are initially passed to the preprocessor by the driver.
A module is the output of the preprocessor, for a given source file, after inclusion of
any header files (or other source files) which are specified by #include preprocessor
24
CPSOC Command-line Driver Invoking the Compiler
directives. These modules are then passed to the remainder of the compiler applications.
Thus, a module may consist of several source and header files. A module is also often
referred to as a translation unit. These terms can also be applied to assembly files, as
they too can include other header and source files.
Some of the compiler’s output files contain project-wide information and are not directly associated
with any one particular input file, e.g. the map file. If the names of these project-wide files are not
specified on the command line, the basename of these files is derived from the first C source file
listed on the command line. If there are no files of this type being compiled, the name is based on
the first input file (regardless of type) on the command line. Throughout this manual, the basename
of this file will be called the project name.
Most IDEs use project files whose names are user-specified. Typically the names of project-wide
files, such as map files, are named after the project, however check the manual for the IDE you are
using for more details.
T UT•RIAL
U SING COMMAND FILES A command file xyz.cmd is constructed with your favorite
text editor and contains both the options and file names that are required to compile your
project as follows:
--chip=CY8C29466 -m \
--opt=all -g \
main.c isr.c
After it is saved, the compiler may be invoked with the command:
CPSOC @xyz.cmd
25
The Compilation Sequence CPSOC Command-line Driver
code -S
.as
generator
.lst --ASMLIST -C
assembler .obj
HLINK
26
CPSOC Command-line Driver The Compilation Sequence
.hex
-M --NODEL
.map HLINK l.obj
OBJTOHEX
.hex
HEXMATE
debug CROMWELL
The link and post-link steps are graphically illustrated in Figure 2.2.
This diagram shows .hex files as additional input file type not considered in the initial compi-
lation sequence. These files can be merged into the .hex file generated from the other input files in
the project by an application called HEXMATE. See Section 5.15 for more information on this utility.
The output of the linker is a single absolute object file, called l.obj, that can be preserved by
using the --NODEL driver option. Without this option, this temporary file is used to generate an
output file (e.g. a HEX file ) and files used for debugging by development tools (e.g. COFF files)
before it is deleted. The file l.obj can be used as the input to OBJTOHEX if running this application
manually, but it cannot be passed to the driver as an input file as it absolute and cannot be further
processed.
27
The Compilation Sequence CPSOC Command-line Driver
generated filename.
T UT•RIAL
S INGLE STEP COMPILATION The files, main.c, io.c, mdef.as, sprt.obj, a_sb.lib
and c_sb.lpp are to be compiled. To perform this in a single step, the following com-
mand line can be used as a starting point for the project development.
CPSOC --chip=CY8C29466 main.c io.c mdef.as sprt.obj a_sb.lib c_sb.lpp
This will run the C pre-processor then the parser with main.c as input, and then again
for io.c producing two p-code files. These two files, in addition to the library file
c_sb.lpp, are passed to the code generator producing a single temporary assembler file
output. The assembler is then executed and is passed the output of the code generator.
It is run again with mdef.as, producing two relocatable object files. The linker is then
executed, passing in the assembler output files in addition to sprt.obj and the library
file a_sb.lib. The output is a single absolute object file, l.obj. This is then passed to
the appropriate post-link utility applications to generate the specified output file format
and debugging files. All temporary files, including l.obj, are then deleted. The inter-
mediate files: p-code and relocatable object files, are not deleted. This tutorial does not
consider the runtime startup code that is automatically generated by the driver.
• Compile all modified C source files to p-code files using the --PASS1 driver option
28
CPSOC Command-line Driver The Compilation Sequence
• Compile all modified assembler source files to relocatable object files using the -C driver
option
• Compile all p-code and relocatable object files into a single output object file
The final step not only involves the link stage, but also code generation of all the p-code files. In
effect, the HI-TECH C version code generator performs some of the tasks normally performed by
the linker. Any user-specified (non standard) libraries also need to be passed to the compiler during
TM
the final step. This is the incremental build sequence used by HI-TIDE .
T UT•RIAL
M ULTI - STEP COMPILATION The files in the previous example are to be compiled
using a multi-step compilation. The following could be used.
CPSOC --chip=CY8C29466 --pass1 main.c
CPSOC --chip=CY8C29466 --pass1 io.c
CPSOC --chip=CY8C29466 -c mdef.as
CPSOC --chip=CY8C29466 main.p1 io.p1 mdef.obj sprt.obj c_sb.lpp a_sb.lib
If using a make system with incremental builds, only those source files that have changed
since the last build need the first compilation step performed again, so not all of the first
three steps need be executed.
If is important to note that the code generator needs to compile all p-code or p-code library files in
the one step. Thus, if the --PASS1 option is not used (or --PRE is not used), all C source files, and
any p-code libraries, must be built together in the one command.
If a compilation is performed, and the source file that contains main() is not present in the list
of C source files, an undefined symbol error for _main will be produced by the code generator. If the
file that contains the definition for main() is present, but it is a subset of the C source files making
up a project that is being compiled, the code generator will not be able to see the entire C program
and this will defeat most of the optimization techniques employed by the code generator.
There may be multi-step compilation methods employed that lead to compiler errors as a result
of the above restrictions, for example you cannot have an C function compiled into a p-code library
that is called only from assembler code.
29
Runtime Files CPSOC Command-line Driver
• Library files;
• The runtime startup module;
• The powerup routine; and
• The printf routine.
Strictly speaking, the powerup routine is neither compiler-generated source, nor a library routine. It
is fully defined by the user, however as it is very closely associated with the runtime startup module,
it is discussed with the other runtime files in the following sections.
30
CPSOC Command-line Driver Runtime Files
By default, libraries appropriate for the selected driver options are automatically passed to the
code generator and linker. Although individual library functions or routines will be linked in once
referenced in C code, the compiler still requires the inclusion of the appropriate header file for the
library function that is being used. See the appropriate library function section in Chapter A for the
header file that should be used.
31
Runtime Files CPSOC Command-line Driver
Rather than the traditional method of linking in a generic, precompiled routine, HI-TECH C uses
a more efficient method which actually determines what runtime startup code is required from the
user’s program. It does this by performing an additional link step, the output of which is used
to determine the requirements of the program. From this information CPSOC then “writes” the
assembler code which will perform the startup sequence. This code is stored into a file which is then
assembled and linked into the remainder of the program automatically.
Since the runtime startup code is generated automatically on every compilation, the generated
files associated with this process are deleted after they have been used. If required, the assembler file
which contains the runtime startup code can be kept after compilation by using the driver option:
--RUNTIME=default,+keep
The residual file will be called startup.as and will be located in the current working directory. If
you are using an IDE to perform the compilation the destination directory is dictated by the IDE
itself, however you may use the --OUTDIR option to specify an explicit output directory to the
compiler.
This is an automatic process which does not require any user interaction, however some aspects
of the runtime code can be controlled, if required, using the --RUNTIME option. Section 2.6.48
describes the use of this option, and the following sections describes the functional aspects of the
code contained in this module and its effect on program operation.
If you require any special initialization to be performed immediately after reset, you should use
the powerup routine feature described later in Section 2.3.3.
32
CPSOC Command-line Driver Runtime Files
Such initialized objects have two components: their initial value stored in a psect destined for non-
volatile memory (i.e. placed in the HEX file), and space for the variable in RAM psect where the
variable will reside and be accessed during program execution.
The actual initial values are placed in a psect called romdatan, where n is a digit representing
a bank number. Space is reserved for the runtime location of initialized variables in a psect called
romdatan.
The runtime startup code performs a block copy of the values from the romdatan to the ramdatan
psect so that the RAM variables will contain their initial values before main() is executed.
•
Since the contents of both the ramdatan and romdatan psect must match up precisely,
extreme caution must be employed with any assembly code, or any user-defined linker
options, that may affect these psects.
The block copy of the data psects may be omitted by disabling the init suboption of --RUNTIME.
For example:
--RUNTIME=default,-init
With this part of the runtime startup code absent, the contents of initialized variables will be unpre-
dictable when the program begins execution. Code relying on variables containing their initial value
may fail.
•
Since auto objects are dynamically created (possibly with different values each time the
function is called), any initialized auto variables require assembly code to be produced
in the function in which they are defined to perform the initialization. As a result,
initialized auto objects do not use the data psects and are not considered by the runtime
startup code.
33
Runtime Files CPSOC Command-line Driver
Variables whose contents should be preserved over a reset, or even power off, should be qualified
with persistent, see Section 3.3.10.1. Such variables are linked at a different area of memory and are
not altered by the runtime startup code in any way.
•
The abbreviation "bss" stands for Block Started by Symbol and was an assembler pseudo-
op used in IBM systems back in the days when computers were coal-fired. The contin-
ued usage of this term is still appropriate.
HI-TECH C places initialized variables in psects called bssn, where n is a digital representing the
bank number in which the psect should be positioned. Code is inserted into the runtime startup
module to clear each bss psect for each bank that is defined.
The block clear of all the bss psects may be omitted by disabling the clear suboption of
--RUNTIME. For example:
--RUNTIME=default,-clear
With this part of the runtime startup code absent, the contents of uninitialized variables will be
unpredictable when the program begins execution.
Variables whose contents should be preserved over a reset, or even power off, should be qualified
with persistent. See Section 3.3.10.1 for more information. Such variables are linked at a different
area of memory and are not altered by the runtime startup code in anyway.
34
CPSOC Command-line Driver Runtime Files
The file should be copied to your working directory, modified and included into your project as
a source file. No special linker options or other code is required; the compiler will detect if you
have defined a powerup routine and will automatically use it, provided the code in this routine is
contained in a psect called powerup. The label which defines the start of the powerup routine must
be powerup.
For correct operation (when using the default compiler-generated runtime startup code), the code
must contain at its end an LJMP instruction to the label called start. As with all user-defined assem-
bly code, it must take into consideration program memory paging and/or data memory banking. The
program’s entry point is already defined by the runtime startup code, so this should not be specified
in the powerup routine at the END directive (if used). See Section ?? for more information on this
assembler directive.
T UT•RIAL
C ALLS TO PRINTF A program contains one call to printf, which looks like:
printf(”input is: $d”);
The compiler will note that only the %d placeholder is used and the doprnt module that is
linked into the program will only contain code that handles printing of decimal integers.
The code is latter changed and another call to printf is added. The new call looks like:
printf(”output is %6d”);
Now the compiler will detect that in addition there must be code present in the doprnt
module that handles integers printed to a specific width. The code that handles this flag
will be introduced into the doprnt module.
35
Runtime Files CPSOC Command-line Driver
The size of the doprnt module will increase as more printf features are detected.
If the format string in a call to printf is not a string literal as in the tutorial, but is rather a pointer
to a string, then the compiler will not be able to reliably predict the printf usage, and so it forces a
more complete version of printf to be generated. However, even without being able to scan printf
placeholders, the compiler can still make certain assumptions regarding the usage of the function.
In particular, the compiler can look at the number and type of the additional arguments to printf
(those following the format string expression) to determine which placeholders could be valid. This
enables the size and complexity of the generated printf routine to be kept to a minimum.
T UT•RIAL
No aspect of this operation is user-controllable (other than by adjusting the calls to printf), how-
ever the actual printf code used by a program can be observed. If compiling a program using
printf, the driver will leave behind the pre-processed version of doprnt.c. This module, called
doprnt.pre in your working directory, will show the C code that will actually be contained in the
printf routine. As this code has been pre-processed, indentation and comments will have been
stripped out as part of the normal actions taken by the C pre-processor.
36
CPSOC Command-line Driver Debugging Information
This option will also generate other symbol files for each module compiled. These files are produced
by the code generator and do not contain absolute address. These files have the extension .sdb.
The base name will be the same as the base name of the module being compiled. Thus the above
command line would also generate symbols files with the names test.sdb and init.sdb.
37
Compiler Messages CPSOC Command-line Driver
Map files can be produced by the linker after its final run in the compilation process. The -M
CPSOC option will generate a map file with the program name and extension .map. See Section 2.6.8
for more information on this option and Section 5.10 for information on how to interpret a map file.
An assembler list file can also be generated by the assembler using the CPSOC option --ASMLIST,
as discussed in Section 2.6.17. Only one file is produced for all C modules and modules derived
from p-code libraries as all these modules are combined by the code generator, however this file
will include assembly listings for all user-supplied code as well as listing for any library code that
was obtained from p-code libraries. Assembly source files will each have a list file generated, if
requested. Note that this option may overwrite some of the C listing files produced by CLIST.
The CPSOC -G option (see Section 2.6.4) tells the compiler to produce several symbol files which
can be used by debuggers and simulators to perform symbolic and source-level debugging. Using
the --IDE option may also enable symbol file generation as well.
The -G option produces an absolute symbol files which contain both assembler- and C-level
information. This file is produced by the linker after the linking process has been completed. If no
symbol filename is specified, the program name will be used.
This option will also generate other symbol files for each module compiled. These files are
produced by the code generator and do not contain absolute addresses. These files have the extension
.sdb and the base name of the module being compiled.
38
CPSOC Command-line Driver Compiler Messages
user considers significant will be displayed. In addition, messages with a particular number can be
disabled. Both of these methods are explained in Section 2.5.5.1.
Provided the message is enabled and it is not a warning messages that is below the warning
threshold, the message string will be displayed.
In addition to the actual message string, there are several other pieces of information that may
be displayed, such as the message number, the name of the file for which the message is applicable,
the file’s line number and the application that requested the message, etc.
If a message is being displayed as an error, a counter is incremented. After a certain number of
errors has been reached, compilation of the current module will cease. The default number of errors
that will cause this termination can be adjusted by using the --ERRORS option, see Section 2.6.26.
This counter is reset after each compilation step of each module, thus specifying a maximum of five
errors will allow up to five errors from the parser, five from the code generator, five from the linker,
five from the driver, etc.
If a language other than English is selected, and the message cannot be found in the appropriate
non-English MDF, the alert system tries to find the message in the English MDF. If an English
message string is not present, a message similar to:
where * indicates the message number that was generated, will be printed, otherwise the message in
the requested language will be displayed.
39
Compiler Messages CPSOC Command-line Driver
Advisory Messages convey information regarding a situation the compiler has encountered or some
action the compiler is about to take. The information is being displayed “for your interest”
and typically require no action to be taken.
Unless prevented by some driver option or another error message, the project will be linked
and the requested output file(s) will be generated.
Warning Messages indicate source code or some other situation that is valid, but which may lead
to runtime failure of the code. The code or situation that triggered the warning should be
investigated, however, compilation of the current module will continue, as will compilation of
any remaining modules.
Unless prevented by some driver option or another error message, the project will be linked
and the requested output file(s) will be generated.
Error Messages indicate source code that is illegal and that compilation of this code either cannot
or will not take place. Compilation will be attempted for the remaining source code in the
current module, but no additional modules will be compiled and the compilation process will
then conclude.
The requested output files will not be produced.
Fatal Error Messages indicate a situation that cannot allow compilation to proceed and which re-
quired the the compilation process to stop immediately.
The requested output files will not be produced.
40
CPSOC Command-line Driver Compiler Messages
user-friendly. Typically each message is displayed on a single line. The general form of messages
produced with the -E option in force is:
filename line_number: (message number) message string (message type)
The -E option also has another effect. If it is being used, the driver first checks to see if special
environment variables have been set. If so, the format dictated by these variables are used as a
template for all messages produced by all compiler applications. The names of these variables are
given in Table 2.3.
The value of these environment variables are strings that are used as templates for the message
format. Printf-like placeholders can be placed within the string to allow the message format to be
customised. The placeholders and what they represent are indicated in Table 2.4.
•
If these options are used in a DOS batch file, two percent characters will need to be used
to specify the placeholders, as DOS interprets a single percent character as an argument
and will not pass this on to the compiler. For example:
--ERRFORMAT=”file %%f: line %%l”
Environment variables, in turn, may be overridden by the driver options: --MSGFORMAT, --WARNFORMAT
and --ERRFORMAT, see Section ??. These options take a string as their argument. The option strings
are formatted, and can use the same placeholders, as their variable counterparts.
41
Compiler Messages CPSOC Command-line Driver
T UT•RIAL
42
CPSOC Command-line Driver Compiler Messages
Note that now the warning and error formats have changed to that requested. For the
case of the linker error, there is no line number information so the replacement for this
placeholder is left blank.
Disabling error or warning messages in no way fixes any potential problems reported
by the message. Always use caution when exercising this option.
43
CPSOC Driver Option Descriptions CPSOC Command-line Driver
44
CPSOC Command-line Driver CPSOC Driver Option Descriptions
Option Meaning
-Ipath Specify a directory pathname for include files
-Llibrary Specify a library to be scanned by the linker
-L-option Specify -option to be passed directly to the linker
-Mfile Request generation of a MAP file
-Nsize Specify identifier length
-Ofile Specify output filenames
-P Preprocess assembler files
-Q Specify quiet mode
-S Compile to assembler source files only
-Usymbol Undefine a predefined preprocessor symbol
-V Verbose: display compiler pass command lines
-X Eliminate local symbols from symbol table
--ASMLIST Generate assembly list files
--AUTOBANK Specify RAM bank for local
--CHAR=type Make the default char signed or unsigned
--CHIP=processor Selects which processor to compile for
--CHIPINFO Displays a list of supported processors
--CR=file Generate cross-reference listing
--ERRFORMAT<=format> Format error message strings to the given style
--GETOPTION=app,file Get the command line options for the named applica-
tion
--HELP<=option> Display the compiler’s command line options
--IDE=ide Configure the compiler for use by the named IDE
--LANG=language Specify language for compiler messages
--MAC=number Limit the number of MAC blocks used by the com-
piler
--MEMMAP=mapfile Display memory summary information for the map
file
--NOEXEC Go through the motions of compiling without actually
compiling
--OPT<=type> Enable compiler optimizations
--OUTDIR=path Specify directory for output files
--OUTPUT=type Generate output file type
--PASS1 Compile to p-code intermediate file
--PRE Produce preprocessed source files
continued. . .
45
CPSOC Driver Option Descriptions CPSOC Command-line Driver
Option Meaning
--PROTO Generate function prototype information
--RAM=lo-hi<,lo-hi,...> Specify and/or reserve RAM ranges
--ROM=lo-hi<,lo-hi,...>|tag Specify and/or reserve ROM ranges
--RUNTIME=type Configure the C runtime libraries to the specified type
--SCANDEP Generate file dependency “.DEP files”
--SETOPTION=app,file Set the command line options for the named applica-
tion
--SETUP=argument Setup the product
--STRICT Enable strict ANSI keyword conformance
--SUMMARY=type Selects the type of memory summary output
--VER Display the compiler’s version number
--WARN=level Set the compiler’s warning level
--WARNFORMAT=format Format warning message strings to given style
continued. . .
The compiler will produce three object files main.obj, module1.obj and asmcode.obj which
could then be linked to produce an Intel HEX file using the command:
This option should only be used when all of the C source files contained within a project are
specified on the command-line list of input files. Note that the intermediate file format used by PRO
compilers is the p1 file, which is produced using the --PASS1 option. See Section 2.6.42 option for
more information.
46
CPSOC Command-line Driver CPSOC Driver Option Descriptions
47
CPSOC Driver Option Descriptions CPSOC Command-line Driver
Section 2.5 has more information regarding this option as well as an overview of the messaging
system and other related driver options.
The --IDE option, see Section 2.6.30 will typically enable the -G option.
will search the directories c:\include and d:\myapp\include for any header files included into
the source code, then search the default include directory (the include directory where the compiler
was installed).
This option has no effect for files that are included into assembly source using the INCLUDE
directive. See Section 4.3.9.3.
48
CPSOC Command-line Driver CPSOC Driver Option Descriptions
If the linker is to scan libraries whose names do not follow the above naming convention or whose
locations are not in the LIB subdirectory, simply include the libraries’ names on the command line
along with the source files.
49
CPSOC Driver Option Descriptions CPSOC Command-line Driver
The -L option is especially useful when linking code which contains non-standard program sections
(or psects), as may be the case if the program contains C code which makes use of the #pragma
psect directive or assembly code which contains user-defined psects. See Section ?? for more
information. Without this -L option, it would be necessary to invoke the linker manually to allow
the linker options to be adjusted.
One commonly used linker option is -N, which sorts the symbol table in the map file by address,
rather than by name. This would be passed to CPSOC as the option -L-N.
This option can also be used to replace default linker options: If the string starting from the first
character after the -L up to the first = character matches first part of a default linker option, then that
default linker option is replaced by the option specified by the -L.
T UT•RIAL
If there are no characters following the first = character in the -L option, then any matching default
linker option will be deleted. For example: -L-pfirst= will remove any default linker option that
begins with the string -pfirst=. No warning is generated if such a default linker option cannot be
found.
T UT•RIAL
A DDING AND DELETING DEFAULT LINKER OPTIONS The default linker options for
for a project links several psects in the following fashion.
-pone=600h,two,three
which links one at 600h, then follows this with two, then three. It has been decided
50
CPSOC Command-line Driver CPSOC Driver Option Descriptions
that the psects should be linked so that one follows two, which follows three, and
that the highest address of one should be located at 5FFh. This new arragement can be
specified issuing the following driver option:
-L-pthree=-600h,two,one
which creates passes the required linker options to the linker. The existing default option
is still present, so this must be removed by use the driver option:
-L-pone=
which will remove the existing option.
The default option that you are deleting or replacing must contain an equal character.
51
CPSOC Driver Option Descriptions CPSOC Command-line Driver
To change the directory in which all output and intermediate files are written, use the --OUTDIR
option, see Section 2.6.40. Note that if -O specifies a path which is inconsistent with the path
specified in the --OUTDIR option, this will result in an error.
will produce an assembler file called test.as which contains the code generated from test.c.
This option is particularly useful for checking function calling conventions and signature values
when attempting to write external assembly language routines.
The file produced by this option differs to that produced by the --ASMLIST option in that it does
not contain op-codes or addresses and it may be used as a source file and subsequently passed to the
assembler to be assembled.
#undef draft
52
CPSOC Command-line Driver CPSOC Driver Option Descriptions
53
CPSOC Driver Option Descriptions CPSOC Command-line Driver
system rom SSC call parameters. By placing autos in a different bank, the likelihood of global vari-
ables also being in the that bank is increased, which can result in fewer bank-switching instructions
being generated for functions that access both local and global variables. The bank number must lie
within the range of available banks.
This option has no effect on re-entrant functions, whose variables are always placed on the
hardware stack in the last bank of RAM.
,width=n select the byte-width of the checksum result. A negative width will store the result in
little-endian byte order. Result widths from one to four bytes are permitted.
,algorithm=n Select one of the checksum algorithms implemented in hexmate. The selectable al-
gorithms are described in Table 5.10.
If no additional specifications are used the checksum will be calculated using an eight bit sum-
mation algorithm and the result will be stored as a two byte value in little endian byte order. By
default, no initial offset will be applied.
54
CPSOC Command-line Driver CPSOC Driver Option Descriptions
See also Section 4.3.8.25 for information on setting the target processor from within assembly
files.
The full list of supported devices is also included in Appendix C of this manual.
Thus this option can not be used when using any compilation process that compiles each source file
separately using the -C or --PASS1 options. Such is the case for most IDEs, including HI-TIDE,
and makefiles.
55
CPSOC Driver Option Descriptions CPSOC Command-line Driver
56
CPSOC Command-line Driver CPSOC Driver Option Descriptions
CPSOC --help=warn
This will display more detailed information about the --WARN option, the available suboptions, and
which suboptions are enabled by default.
57
CPSOC Driver Option Descriptions CPSOC Command-line Driver
MAC block will be used in main-line code, and if a second MAC block is available it will be used
in interrupt code. The MAC hardware is inherently non-reentrant as it is not possible to save and
restore the result registers. If MAC hardware is not available, software library routines will be used
to implement multiplication.
It may be desired on occasions to limit the compiler’s use of the MAC hardware (e.g. if a MAC
block was to be used for DSP functionality.) The number of MACs used by the compiler can be
limited by this option, e.g. –mac=1 will ensure that no more than one MAC block is used by the
compiler. If the chip has no MAC blocks, or fewer blocks than specified by this option, then it has
no effect.
58
CPSOC Command-line Driver CPSOC Driver Option Descriptions
59
CPSOC Driver Option Descriptions CPSOC Command-line Driver
60
CPSOC Command-line Driver CPSOC Driver Option Descriptions
#include <stdio.h>
add(arg1, arg2)
int * arg1;
int * arg2;
{
return *arg1 + *arg2;
}
CPSOC will produce test.pro containing the following declarations which may then be edited as
necessary:
61
CPSOC Driver Option Descriptions CPSOC Command-line Driver
--RAM=default,+100-1ff
for example. To only use an external range and ignore any on-chip memory, use:
--RAM=0-ff
This option may also be used to reserve memory ranges already defined as on-chip memory in the
chipinfo file. To do this supply a range prefixed with a minus character, -, for example:
--RAM=default,-100-103
will use all the defined on-chip memory, but not use the addresses in the range from 100h to 103h
for allocation of RAM objects.
Only the reservation aspect of this option will be of use with HI-TECH C as no external memory
interface is available.
62
CPSOC Command-line Driver CPSOC Driver Option Descriptions
--ROM=default,+100-2ff
for example. To only use an external range and ignore any on-chip memory, use:
--ROM=100-2ff
This option may also be used to reserve memory ranges already defined as on-chip memory in the
chip configuration file. To do this supply a range prefixed with a minus character, -, for example:
--ROM=default,-100-1ff
will use all the defined on-chip memory, but not use the addresses in the range from 100h to 1ffh for
allocation of ROM objects.
Only the reservation aspect of this option will be of use with HI-TECH C as no external memory
interface is available.
63
CPSOC Driver Option Descriptions CPSOC Command-line Driver
64
CPSOC Command-line Driver CPSOC Driver Option Descriptions
not desirable as almost all applications are critical to the success of the build process. Disabling a
critical application will result in catastrophic failure. However it is permissible to skip a non-critical
application such as clist or hexmate if the final results are not reliant on their function.
2.6.55 --TIME: Report time taken for each phase of build process
Adding --TIME when building generate a summary which shows how much time each stage of the
build process took to complete.
65
CPSOC Driver Option Descriptions CPSOC Command-line Driver
66
CPSOC Command-line Driver CPSOC Driver Option Descriptions
additional instructions to clear the watch dog timer will be inserted into the generated runtime startup
assembly code.
67
CPSOC Driver Option Descriptions CPSOC Command-line Driver
68
Chapter 3
C Language Features
HI-TECH C supports a number of special features and extensions to the C language which are de-
signed to ease the task of producing ROM-based applications. This chapter documents the compiler
options and special language features which are specific to these devices.
3.2.1 Stacks
The hardware stack on the M8C MCUs is used only for function return addresses, except if a function
is compiled as being reentrant. See Section 2.6.46 and Section for more information.
69
Supported Data Types and Variables C Language Features
Note that the depth of the stack is limited to 256 bytes. The stack pointer is initialized in the
runtime startup code, unless disabled by the stack, --RUNTIME suboption, and the initial value is
derived from the low byte of the stackps psect.
3.2.2 Endianism
The M8C only performs byte accesses of memory locations. For multi-byte objects, HI-TECH C
uses a big endian format. This is, the most significant byte will be located at the lower address.
70
C Language Features Supported Data Types and Variables
Any integral constant will have a type which is the smallest type that can hold the value without
overflow. The suffix l or L may be used with the constant to indicate that it must be assigned either
a signed long or unsigned long type, and the suffix u or U may be used with the constant to
indicate that it must be assigned an unsigned type, and both l or L and u or U may be used to indicate
unsigned long int type.
Floating-point constants have double type unless suffixed by f or F, in which case it is a float
constant. The suffixes l or L specify a long double type which is considered an identical type to
double by HI-TECH C.
Character constants are enclosed by single quote characters ’, for example ’a’. A character
constant has char type. Multi-byte character constants are not supported.
String constants or string literals are enclosed by double quote characters ", for example "hello
world". The type of string constants is const char [] and the strings are stored in the program
memory. Assigning a string constant to a non-const char pointer will generate a warning from the
compiler. For example:
char * cp= "one"; // "one" in ROM, produces warning
const char * ccp= "two"; // "two" in ROM, correct
Defining and initializing a non-const array (i.e. not a pointer definition) with a string, for example:
char ca[]= "two"; // "two" different to the above
produces an array in data space which is initialised at startup with the string "two" (copied from
program space), whereas a constant string used in other contexts represents an unnamed const-
qualified array, accessed directly in program space.
HI-TECH C will use the same storage location and label for strings that have identical character
sequences, except where the strings are used to initialise an array residing in the data space as shown
in the last statement in the previous example.
Two adjacent string constants (i.e. two strings separated only by white space) are concatenated
by the compiler. Thus:
const char * cp = "hello " "world";
assigned the pointer with the string "hello world".
71
Supported Data Types and Variables C Language Features
will be allocated in the bit-addressable psect rbit_0, and will be visible only in that function. When
the following declaration is used outside any function:
bit init_flag;
init_flag will be globally visible, but located within the same psect.
bit variables cannot be auto or parameters to a function. A function may return a bit object
by using the bit keyword in the functions prototype in the usual way. The bit return value will be
returning in the carry flag in the status register.
Bit variables behave in most respects like normal unsigned char variables, but they may only
contain the values 0 and 1, and therefore provide a convenient and efficient method of storing boolean
flags without consuming large amounts of internal RAM. It is, however, not possible to declared
pointers to bit variables or statically initialise bit variables.
Operations on bit objects are performed using the single bit instructions (SET and CLR) wherever
possible, thus the generated code to access bit objects is very efficient.
Note that when assigning a larger integral type to a bit variable, only the least-significant bit is
used. For example, if the bit variable bitvar was assigned as in the following:
it will be cleared by the assignment since the least significant bit of data is zero. If you want to set
a bit variable to be 0 or 1 depending on whether the larger integral type is zero (false) or non-zero
(true), use the form:
bitvar = data != 0;
The psects in which bit objects are allocated storage are declared using the bit PSECT directive
flag. Eight bit objects will take up one byte of storage space which is indicated by the psect’s scale
value of 8 in the map file. The length given in the map file for bit psects is in units of bits, not bytes.
All addresses specified for bit objects are also bit addresses.
The bit psects are cleared on startup, but are not initialised. To create a bit object which has a
non-zero initial value, explicitly initialise it at the beginning of your code.
If the CPSOC flag --STRICT is used, the bit keyword becomes unavailable.
72
C Language Features Supported Data Types and Variables
73
Supported Data Types and Variables C Language Features
Variables may be declared using the signed short int and unsigned short int keyword
sequences, respectively, to hold values of these types. When specifying a short int type, the
keyword int may be omitted. Thus a variable declared as short will contain a signed short int
and a variable declared as unsigned short will contain an unsigned short int.
74
C Language Features Supported Data Types and Variables
75
Supported Data Types and Variables C Language Features
Bit-fields are allocated within 8- or 16-bit words. Although the ANSI standard only allows for
bit-fields of type int or unsigned int, this is not optimial on CPSOC devices. The allocation size
of the bit-field structure is based on the number of bits defined in the structure as a whole, thus the
following structure:
struct {
unsigned hi : 1;
unsigned dummy : 6;
unsigned lo : 1;
} foo;
will be allocated 1 byte of memory in total, but the following:
struct {
unsigned hi : 1;
unsigned dummy : 6;
unsigned lo : 1;
unsigned extra : 2;
} foo;
will be allocated 2 bytes of storage.
Unnamed bit-fields may be declared to pad out unused space between active bits in control
registers. For example, if dummy is never used the structure above could have been declared as:
struct {
unsigned hi : 1;
unsigned : 6;
unsigned lo : 1;
} foo;
A structure with bit-fields may be initialised by supplying a comma-separated list of initial values
for each field. For example:
struct {
unsigned hi : 1;
unsigned mid : 6;
unsigned lo : 1;
} foo = {1, 8, 0};
As M8C devices are big endian, the first bit defined will be the most significant bit of the word in
which it will be stored. When a bit-field is declared, it is allocated within the current word if it will
fit, otherwise a new word is allocated within the structure. Bit-fields can never cross the boundary
between word allocation units. For example, the declaration:
76
C Language Features Supported Data Types and Variables
struct {
unsigned hi : 1;
unsigned dummy : 6;
unsigned lo : 1;
} foo;
will produce a structure occupying 1 byte. If foo was ultimately linked at address 10H, the field lo
will be bit 7 of address 10H, hi will be at bit 0. The least significant bit of dummy will be bit 6 of
address 10H and the most significant bit of dummy will be at bit 1.
const struct {
int number;
int *ptr;
} record = { 0x55, &i};
In this case, the structure will be placed into the program space and each member will, obviously, be
read-only. Remember that all members must be initialised if a structure is const as they cannot be
initialized at runtime.
If the members of the structure were individually qualified const but the structure was not, then
the structure would be positioned into RAM, but each member would be read-only. Compare the
following structure with the above.
struct {
const int number;
int * const ptr;
} record = { 0x55, &i};
77
Supported Data Types and Variables C Language Features
The volatile type qualifier is used to tell the compiler that an object cannot be guaranteed to retain
its value between successive accesses. This prevents the optimizer from eliminating apparently
redundant references to objects declared volatile because it may alter the behaviour of the program
to do so. All Input/Output ports and any variables which may be modified by interrupt routines
should be declared volatile, for example:
Volatile objects may be accessed using different generated code to non-volatile objects. Objects
that are not qualified volatile may be removed by the compiler if they not used in C or assemby
code.
void test(void)
{
78
C Language Features Supported Data Types and Variables
79
Supported Data Types and Variables C Language Features
Pointers can be qualified like any other C object, but care must be taken when doing so as there are
two quantities associated with pointers. The first is the actual pointer itself, which is treated like
any ordinary C variable and has memory reserved for it. The second is the target that the pointer
references, or to which the pointer points. The general form of a pointer definition looks like the
following.
Any qualifiers to the right of the * (i.e. next to the pointer’s name) relate to the pointer variable itself.
The type and any qualifiers to the left of the * relate to the pointer’s targets.
T UT•RIAL
Bare in mind that one pointer can be assigned the address of many objects, for example a pointer
that is a parameter to a function is assigned a new object address every time the function is called.
The definition of the pointer must be valid for every target address assigned.
80
C Language Features Supported Data Types and Variables
•
Care must be taken when describing pointers: Is a “const pointer” a pointer that points
to const objects, or a pointer that is const itself. You can talk about “pointers to const”
and “const pointers” to help clarify the definition, but such terms may not be universally
understood.
• An 8-bit pointer capable of accessing up to 256 bytes of the ROM address space;
• A 16-bit pointer capable of accessing the both the entire RAM and ROM address spaces;
– Addresses with the most significant bit set represent the ROM address space; others
addresses the RAM address space
Each data pointer will be allocated one of the above classifications after preliminary scans of the
source code. There is no mechanism by which the programmer can specify the style of pointer
required (other than by the address assignments to the pointer).
T UT•RIAL
DYNAMIC POINTER SIZES A program in the early stages of development contains the
following code;
81
Supported Data Types and Variables C Language Features
void main(void) {
int i, *ip;
ip = &i;
}
The code generator is able to automatically allocate the variable i to bank 0, which it
does. The code generator notes that the pointer ip only points to the bank 0 variable i,
so this pointer is made an 8-bit wide bank 0 pointer.
As the program is developed, other variables are defined and allocated space in bank 0.
A point is reach at which all the defined variables will no longer fit in the bank 0 and
the variable i happens to be moved to another RAM bank. When the program is next
compiled, the pointer ip will automatically become a 16-bit pointer to all of the RAM
address space, and the code used to initialize and dereference the pointer will change
accordingly.
One positive aspect of tracking pointer targets is less of a dependence on pointer qualifiers. The
standard qualifiers const and volatile must still be used in pointer definitions to indicate a read-
only or externally-modifiable target object, respectively. However this is in strict accordance with
the ANSI standard. The introduction of HI-TECH specific qualifiers would result in less portable
and readable code, and increase the chance of extraneous warnings being issued by the compiler.
T UT•RIAL
Pointers to different targets A program in the early stages of development contains the
following code;
void main(void) {
int i, *ip;
ip = &i;
}
The code generator allocate the variable i to the access bank and the pointer ip is made
an 8-bit wide access bank pointer.
82
C Language Features Supported Data Types and Variables
pointer having a classification capable of accessing the program space. The exact classification will
also depend on other factors.
T UT•RIAL
T UT•RIAL
83
Storage Class and Object Placement C Language Features
void main(void) {
int j, i = setV();
const int start = 0x10;
j = getValue(&i)
j += getValue(&start);
}
Now the pointer, ip, is assigned addresses of both data and const objects. After the
next compilation the size and encoding of ip will change, as will the code that assigns
the addresses to ip. The generated code that dereferences ip (in getValue) will check
the address to determine the memory space of the target address.
84
C Language Features Storage Class and Object Placement
The auto variables associated with a function are allocated space depending on whether the
function in which they are defined is reentrant. Individual functions may be qualified as reentrant
using the reentrant qualifier (see Section 3.5.1.2), or all functions in the entire program may be
compiled as reentrant using the --REENTRANT command-line driver option (see Section 2.6.46). In
either case, the variables will not necessarily be allocated space in the order declared — in contrast
to parameters which are always in lexical order.
reentrant functions access their auto variables via the hardware stack. Non-reentrant functions
store their auto variables in fixed memory locations — specifically as an offset into a block of
memory. This block may also be used for some parameters to the function, if the parameters are
not passed via registers. The auto/parameter blocks for each function form what is known as a
compiled stack. See 5.9 for more information.
When using a compiled stack, HI-TECH C places all auto variables in bank 0. This memory
is shared with other non-auto objects that reside in the same bank. The auto/parameter blocks for a
number of functions are overlapped by the linker if those functions are never active at the same time.
When using a compiled stack, auto objects are referenced with a symbol that consists of two
question marks, ??, concatenated with the assembly name of the function in which the auto is
defined, plus some offset. For example, if the int object test is the first object placed in main()’s
auto parameter block, it will be accessed using the addresses ??_main and ??_main+1, since an int
is two bytes long.
will declare a variable called SPvar located at RAM address 06h. The compiler equates the variable
to the address supplied, and the compiler-generated assembler will include a line of the form:
85
Functions C Language Features
This construct is primarily intended for equating the address of a C identifier with a microprocessor
special function register, in which case the __ioport qualifier must also be used — See Section
3.3.10.2, however it can also be used for ordinary variables defined in the RAM address space.
3.5 Functions
Function definitions in HI-TECH C conform to the ANSI standard, however there are several non-
ANSI qualifiers that can be used to indicate additional information regarding the function.
86
C Language Features Functions
87
Operators C Language Features
The function test() will receive the parameter x in the accumulator, parameter y in memory loca-
tions ?_test and ?_test+1, and parameter z in memory locations ?_test+2 through ?_test+5.
If you need to determine, for assembly code for example, the exact entry or exit code within a
function or the code used to call a function, it is often helpful to write a dummy C function with the
same argument types as your assembler function, and compile to assembly code with the CPSOC -S
option, allowing you to examine the assembly code.
3.6 Operators
HI-TECH C supports all the ANSI operators. Some special sequences are illustrated in the sections
below. The exact results of some operators are implementation defined. The following sections
illustrate code produced by the compiler.
88
C Language Features Operators
are not aware that these changes of type have taken place, the results of some expressions are not
what would normally be expected.
Integral promotion is the implicit conversion of enumerated types, signed or unsigned varieties
of char, short int or bitfield types to either signed int or unsigned int. If the result of the
conversion can be represented by an signed int, then that is the destination type, otherwise the
conversion is to unsigned int.
Consider the following example.
The unsigned char result of a - b is 206 (which is not less than 10), but both a and b are con-
verted to signed int via integral promotion before the subtraction takes place. The result of the
subtraction with these data types is -50 (which is less than 10) and hence the body of the if() state-
ment is executed. If the result of the subtraction is to be an unsigned quantity, then apply a cast.
For example:
The comparison is then done using unsigned int, in this case, and the body of the if() would not
be executed.
Another problem that frequently occurs is with the bitwise compliment operator, “~”. This
operator toggles each bit within a value. Consider the following code.
If c contains the value 55h, it often assumed that ~c will produce AAh, however the result is FFAAh
(for the case of 16-bit int types, and FFFFFFAAh for 32-bit int types, etc.) and so the comparison
in the above example would fail. The compiler may be able to issue a mismatched comparison error
to this effect in some circumstances. Again, a cast could be used to change this behaviour.
The consequence of integral promotion as illustrated above is that operations are not performed
with char-type operands, but with int-type operands. However there are circumstances when the
result of an operation is identical regardless of whether the operands are of type char or int. In
these cases, HI-TECH C will not perform the integral promotion so as to increase the code efficiency.
Consider the following example.
89
Operators C Language Features
unsigned char a, b, c;
a = b + c;
Strictly speaking, this statement requires that the values of b and c should be promoted to unsigned
int, the addition performed, the result of the addition cast to the type of a, and then the assignment
can take place. Even if the result of the unsigned int addition of the promoted values of b and c
was different to the result of the unsigned char addition of these values without promotion, after
the unsigned int result was converted back to unsigned char, the final result would be the same.
If an 8-bit addition is more efficient than an addition performed in the size of an int, the compiler
will encode the former.
If, in the above example, the type of a was unsigned int, then integral promotion would have
to be performed to comply with the ANSI standard.
where var must be an unsigned int. Rotates in either left or right directions, and of any number
of bits can be used. (NB a rotate left of 1 bit is equalivent to a rotate right of 7 bits when dealing
with byte-wide variables, etc.)
The above code sequences are portable – compilers not implementing the detection of the rotate
implications will revert to a longer shift and OR sequence when compiling this code.
90
C Language Features Psects
Right shifts of unsigned integral values always clear the most significant bit of the result.
Left shifts (< < operator), signed or unsigned, always clear the least significant bit of the result.
3.7 Psects
The compiler splits code and data objects into a number of standard program sections referred to
as psects. The HI-TECH assembler allows an arbitrary number of named psects to be included in
assembler code. The linker will group all data for a particular psect into a single segment, however
linker options and psect flags can control this operation.
•
If you are using CPSOC to invoke the linker, you don’t need to worry about the informa-
tion documented here, except as background knowledge. If you want to run the linker
manually (this is not recommended), or write your own assembly language subroutines,
you should read this section carefully.
A psect can be created in assembly code by using the PSECT assembler directive (see Section 4.3.8.4).
91
Psects C Language Features
powerup This contains executable code for the standard or user-supplied power-up routine.
init This contains executable code associated with the RAM clear and copy portion of the runtime
startup module.
end_init This contains executable code associated with the runtime startup module which transfer
control to the function main().
text This contain all executable code compiled from C source modules. It also contains all code
from library modules.
maintext This contain the executable code that forms part of the function main().
strings These psects hold objects that are declared const and string literals which are not modifi-
able.
romdatan where n is a digit representing a bank number. These psects hold the ROM image of
initialized data. This psect is copied to the ramdata psect by the runtime startup code.
vectors This psect contains the interrupt code linked directly at the interrupt vectors.
data This psect holds data objects that are qualified const.
The compiler-generated psects which are placed in the RAM address space are:
bssn These psects contain global or static local variables which are uninitialized.
ramdatan where n is a digit representing a bank number. These psects contain any initialised global
or static local variables,
nvramn where n is a digit representing a bank number. This psect is used to store persistent
qualified variables. It is not cleared or otherwise modified by the runtime startup code.
rbitn where n is a digit representing a bank number. This psect is used to store all bit variables,
except those qualified persistent.
nvbitn where n is a digit representing a bank number. This psect is used to store all bit variables
qualified persistent.
fnauto This psect is used to store all auto variables and function arguments not stored on the
hardware stack. It is placed in RAM bank 0.
92
C Language Features Interrupt Handling in C
int tick_count;
HI-TECH C automatically generates code to save context when an interrupt occurs. This code will
be executed before the code generated from the C interrupt function is entered.
The code generator is capable of analysing the the interrupt function to determine its register
requirements. If the interrupt function calls other function, these functions are in turn are analysed
for their register usage, and if these functions call other functions, the process is continued until the
exact register requirements of the interrupt function call graph are known.
93
Mixing C and assembly code C Language Features
Only those registers which are used by the interrupt function are saved. The program counter,
CPU_PC, and the flags register, CPU_F, are automatically saved by the M8C hardware when the inter-
rupt occurs.
HI-TECH C does not scan any assembly code, whether in-line with C code, or as separate as-
sembly modules, that may be executed anywhere in the interrupt call graph. Thus, if assembly code
is executed in response to an interrupt occurring, there may need to be extra assembly code added
to save and restore any registers or locations used if they are not already saved by the interrupt entry
routine.
94
C Language Features Mixing C and assembly code
A mapping is performed on the names of all C functions and non-static global variables. See
Section 3.9.3.1 for a complete description of mappings between C and assembly identifiers.
T UT•RIAL
An assembly routine is required which can add a single byte and a 16-bit quantity.
The routine must be callable from C code. Both the values are passed in as arguments
when the routine is called from the C code — the byte first, then the 16-bit value. The
assembly routine should return the result of the addition as a 16-bit quantity.
Most compiler-generated executable code is placed in a psect called text (see Section
3.7.1). As we do not need to have this assembly routine linked at any particular location,
we can use this psect so the code is bundled with other executable code and stored
somewhere in the program space. This way we do not need to use any additional linker
options. So we use an ordinary looking psect that you would see in assembly code
produced by the compiler. The psect’s name is text, which is not a globally unique psect
name, will be linked in the CODE class, unless the linker is explicitly told otherwise, and
which will reside in a memory space that has 2 bytes per addressable location) :
PSECT text,class=CODE
95
Mixing C and assembly code C Language Features
Now we would like to call this routine add. However in assembly we must choose the
name _add as this then maps to the C identifier add since the compiler prepends an
underscore to all C identifiers when it creates assembly labels. If the name add was
chosen for the assembler routine the it could never be called from C code. The name of
the assembly routine is the label that we will associate with the assembly code:
_add:
We need to be able to call this from other modules, so make this label globally accessi-
ble:
GLOBAL _add
Arguments, or parameters, to this routine will be placed in the accumulator and the
function’s parameter area by whatever code is calling this routine. So this is equivalent
to passing in a char and an int type in C code. The return value of the routine will
appear as an int to C code.
It is the responsibility of this routine to define the parameter area. The symbol name
is dictated by compiler convention and will be ?_add in this case. So we make this
globally accessible:
GLOBAL ?_add
The same symbol is used for the return value so the above makes the return value glob-
ally accessible as well.
By compiling a dummy C function with a similar prototype to how we will be call-
ing this assembly routine, we can determine the signature value. We add a assembler
directive to make this signature value known:
SIGNAT _add,90
Now to actually writing the function, remembering that the first byte parameter is al-
ready in the accumulator and the second parameter is already in this routine’s parameters
area – placed there by the calling function elsewhere. The result is placed back in to the
parameter area ready to be returned
add a,[?_add] ;add LSB of 2nd param to first param
mov [?_add],a ;store this ready for return
mov a,[?_add+1] ;read MSB of 2nd param
skipnc ;handle LSB of addition overflow
inca [?_add+1] ;ditto
mov [?_add+1],a ;store MSB of result
ret
Now, what resources did we use? In total, 2 bytes of parameter space and zero bytes of
local storage. So let’s tell the linker of how much memory to reserve for this routine:
96
C Language Features Mixing C and assembly code
FNSIZE _add,0,2
What registers did this routine use? The accumulator and status registers are both used
so we add to our program the regsused pragma. This can be added to the C module
that calls the assembly routine.
#pragma regsused _add a,f
Here is the entire routine:
GLOBAL _add,?_add
SIGNAT _add,90
FNSIZE _add,0,2
PSECT text1,local,class=CODE,delta=2
_add:
add a,[?_add] ;add LSB of 2nd param to first param
mov [?_add],a ;store this ready for return
mov a,[?_add+1] ;read MSB of 2nd param
skipnc ;handle LSB of addition overflow
inca [?_add+1] ;ditto
mov [?_add+1],a ;store MSB of result
ret
Note that we’ve combined the GLOBAL directive arguments into the one directive. The
placement of some assembler directives is not important, as is the case with GLOBAL,
FNSIZE and SIGNAT.
Provided this routine is called from C code, no FNCALL directive is required, as the code
generator will add this.
To call an assembly routine from C code, a declaration for the routine must be provided. This ensures
that the compiler knows how to encode the function call in terms of parameters and return values,
however no other code is necessary.
If a signature value is present in the assembly code routine, its value will be checked by the linker
when the calling and called routines’ signatures can be compared.
T UT•RIAL
To continue the previous example, here is a code snippet that declares the operation of
the assembler routine, then calls the routine.
#pragma regsused _add a,f
extern int add(char a, int b);
void main(void)
97
Mixing C and assembly code C Language Features
{
int input, result;
input = read_port();
result = add(’a’, input);
}
•
You should not use a #asm block within any C constructs such as if, while, do etc.
In these cases, use only the asm("") form, which is a C statement and will correctly
interact with all C flow-of-control structures.
98
C Language Features Mixing C and assembly code
When using in-line assembly code, great care must be taken to avoid interacting with compiler-
generated code. The code generator cannot scan the assembly code for register usage and so will
remain unaware if registers are clobbered or used by the code. If in doubt, compile your program
with the CPSOC -S option and examine the assembly code generated by the compiler.
99
Mixing C and assembly code C Language Features
100
C Language Features Mixing C and assembly code
The recommended method for accessing SFRs from assembly code is to include assembly ver-
sions of the chip-specific header files which are supplied with the compiler. For example, in an
assembly module or in-line with C code, you will need code similar to the following, assuming the
header file is in the working directory. See Section 4.3.9.3
101
Mixing C and assembly code C Language Features
HI-TECH C is able to determine the address bounds of absolute psects to enure that the output
of C code does not consume specific resources required by the assembly code. The code generator
will ensure that any memory used by these psects are reserved and not used by C code. The linker
options are also adjusted by the driver to enure that this memory is not allocated.
T UT•RIAL
P ROCESSING OF ABSOLUTE PSECTS An assembly code files defines a table that must
be located at address 210h in the data space. The assembly file contains:
PSECT lkuptbl,class=RAM,space=1,abs,ovlrd
ORG 210h
lookup:
ds 20h
When the project is compiled, this file is assembled and the resulting relocatable object
file scanned for absolute psects. As this psect is flagged as being abs and ovlrd, the
bounds and space of the psect will be noted — in this case a memory range from address
210h to 22fh in memory space 1 is being used. This information is passed to the code
generator to ensure that these address spaces are not used by C code. The linker will
also be told to remove these ranges from those available, and this reservation will be
observable in the map file. The RAM class definition, for example, may look like:
-ARAM=00h-0FFhx2,0200h-020Fh,0230h-02FFh,0300h-03FFhx5
for an CY8C29666 device, showing that addresses 210h through 22F were reserved
from this class range.
102
C Language Features Preprocessing
volatile will never be removed by the code generator, even if they appear to be unused throughout
the program.
T UT•RIAL
3.10 Preprocessing
All C source files are preprocessed before compilation. Assembler files can also be preprocessed if
the -P command-line option is issued.
3.10.1 C Comments
HI-TECH C accepts both block and in-line (C99 standard) C source comments, as shown in the
following examples. In-line comments are normally termined by the newline character, however
they can span multiple lines when the line is terminated with a backslash character.
/* I am a block comment
that can run over more
than one line of source */
// I am an in-line comment
// I am an in-line comment \
that spans two lines
Both these comment styles can be used, in addition to the standard assembly comment (see Section
4.3.3), in assembly source code if the -P command-line option is issued, see Section 2.6.11.
All comments are removed by the C preprocessor before being passed to the parser application.
103
Preprocessing C Language Features
104
C Language Features Preprocessing
105
Preprocessing C Language Features
106
C Language Features Preprocessing
•
M8Cs can only perform byte accesses to memory and so do not require any alignment
of memory objects. This pragma will have no effect when used.
107
Preprocessing C Language Features
•
Note that the warning level must be set to -1 or below for this option to have any visible
effect. See Section 2.6.58.
where routine_name is the assembly name of the function or assembly routine which is to be af-
fected, register_list is a space-separated list of registers names, taken from Table3.11. Those
registers not listed are assumed to be unused by the function or routine. The code generator may
uses the unlisted registers to hold values across a function call. Hence, if the routine does, in fact,
use these registers, unreliable program execution may eventuate.
The register names are not case sensitive and a warning will be produced if the register name is
not recognised. A blank list indicates that the specified function or routine uses no registers.
For example, to limit the compiler to saving no registers other than the accumulator register for
the C function, get_result(), use:
108
C Language Features Linking Programs
109
Linking Programs C Language Features
CPSOC, by default, generates Intel HEX files. Use the --OUTPUT option to specify a different
output format, see Section 2.6.41.
After linking, the compiler will automatically generate a memory usage map which shows the
address used by, and the total sizes of, all the psects which are used by the compiled code, similar
to:
Program space:
CODE used 20h ( 32) of 2000h words ( 0.4%)
ROM used 0h ( 0) of 2000h words ( 0.0%)
Data space:
RAM used 4h ( 4) of E0h bytes ( 1.8%)
Summary:
Program space used 20h ( 32) of 2000h words ( 0.4%)
Data space used 4h ( 4) of E0h bytes ( 1.8%)
The program statistics shown in the summary provides more concise information based on each
memory area of the device. This can be used as a guide to the available space left in the device.
Note that this memory summary may not include all objects allocated, particularly those allocated
space by the code generator. The map file should be used for accurate indications of memory used
and remaining after each build.
More detailed memory usage information, listed in ascending order of individual psects, may
be obtained by using the CPSOC --SUMMARY=psect option. Generate a map file for the complete
memory specification of the program.
•
This method works due to the way the linker scans source and library file. When trying
to resolve a symbol (in this instance a function name) the linker first scans all source
modules for the definition. Only if it cannot resolve the symbol in these files does it
then search the library files. Even though the symbol may be defined in a source file
110
C Language Features Standard I/O Functions and Serial I/O
and a library file, the linker will not search the libraries for this symbol and no multiply
defined symbol error will result. This is not true if a symbol is defined twice in source
files.
For example, if you wished to make changes to the library function max() which resides in the file
max.c in the SOURCES directory, you could make a copy of this source file, make the appropriate
changes and then compile and use it as follows.
The code for max() in max.c will be linked into the program rather than the max() function con-
tained in the standard libraries. Note, that if you replace an assembler module, you may need the -P
option (see Section 2.6.11) to preprocess assembler files as the library assembler files often contain
C preprocessor directives.
111
Standard I/O Functions and Serial I/O C Language Features
112
Chapter 4
Macro Assembler
The Macro Assembler included with HI-TECH C assembles source files for M8C MCUs. This
chapter describes the usage of the assembler and the directives (assembler pseudo-ops and controls)
accepted by the assembler in the source files.
The HI-TECH C Macro Assembler package includes a linker, librarian, cross reference generator
and an object code converter.
•
Athough the term “assembler” is almost universally used to decribe the tool which con-
verts human-readable mnemonics into machine code, both “assembler” and “assembly”
are used to describe the source code which such a tool reads. The latter is more com-
mon and is used in this manual to describe the language. Thus you will see the terms
assembly language (or just assembly), assembly listing and etc, but assembler options,
assembler directive and assembler optimizer.
113
Assembler Options Macro Assembler
where the assembler is being called directly, or when they are specified using the command-line
driver option --SETOPTION, see Section 2.6.51.
The usage of the assembler is similar under all of available operating systems. All command-line
options are recognised in either upper or lower case. The basic command format is shown:
files is a space-separated list of one or more assembler source files. Where more than one source
file is specified the assembler treats them as a single module, i.e. a single assembly will be performed
on the concatenation of all the source files specified. The files must be specified in full, no default
extensions or suffixes are assumed.
options is an optional space-separated list of assembler options, each with a minus sign - as
the first character. A full list of possible options is given in Table 4.1, and a full description of each
option follows.
114
Macro Assembler Assembler Options
-A An assembler file with an extension .opt will be produced if this option is used. This is useful
when checking the optimized assembler produced using the -O option.
-C A cross reference file will be produced when this option is used. This file, called srcfile.crf,
where srcfile is the base portion of the first source file name, will contain raw cross refer-
ence information. The cross reference utility CREF must then be run to produce the formatted
cross reference listing. See Section 4.7 for more information.
-Cchipinfo Specify the chipinfo file to use. The chipinfo file is called psoc.ini and can be found
in the DAT directory of the compiler distribution.
-E[file|digit] The default format for an error message is in the form:
where the error of type message occurred on line line of the file filename.
The -E option with no argument will make the assembler use an alternate format for
error and warning messages.
Specifying a digit as argument has a similar effect, only it allows selection of any of
the available message formats.
Specifying a filename as argument will force the assembler to direct error and warning
messages to a file with the name specified.
-Flength By default the listing format is pageless, i.e. the assembler listing output is continuous.
The output may be formatted into pages of varying lengths. Each page will begin with a
header and title, if specified. The -F option allows a page length to be specified. A zero value
of length implies pageless output. The length is specified in a number of lines.
-H Particularly useful in conjunction with the -A or -L ASPSOC options, this option specifies that
output constants should be shown as hexadecimal values rather than decimal values.
-I This option forces listing of macro expansions and unassembled conditionals which would other-
wise be suppressed by a NOLIST assembler control. The -L option is still necessary to produce
a listing.
-Llistfile This option requests the generation of an assembly listing file. If listfile is specified
then the listing will be written to that file, otherwise it will be written to the standard output.
-O This requests the assembler to perform optimization on the assembly code. Note that the use of
this option slows the assembly process down, as the assembler must make an additional pass
over the input code. Debug information for assembler code generated from C source code
may become unreliable.
115
HI-TECH C Assembly Language Macro Assembler
-Ooutfile By default the assembler determines the name of the object file to be created by stripping
any suffix or extension (i.e. the portion after the last dot) from the first source filename and
appending .obj. The -O option allows the user to override the default filename and specify a
new name for the object file.
-Pprocessor This option defines the processor which is being used. The processor type can also be
indicated by use of the PROCESSOR directive in the assembler source file, see Section 4.3.8.25.
You can also add your own processors to the compiler via the compiler’s chipinfo file.
-V This option will include line number and filename information in the object file produced by
the assembler. Such information may be used by debuggers. Note that the line numbers will
correspond with assembler code lines in the assembler file. This option should not be used
when assembling an assembler file produced by the code generator from a C source file.
-Twidth This option allows specification of the listfile paper width, in characters. width should be
a decimal number greater than 41. The default width is 80 characters.
-X The object file created by the assembler contains symbol information, including local symbols,
i.e. symbols that are neither public or external. The -X option will prevent the local symbols
from being included in the object file, thereby reducing the file size.
116
Macro Assembler HI-TECH C Assembly Language
If the assembly file is first processed by the C preprocessor, see Section 2.6.11, then it may also
contain lines that form valid preprocessor directives. See Section 3.10.2 for more information on the
format for these directives.
There is no limitation on what column or part of the line in which any part of the statement
should appear.
4.3.2 Characters
The character set used is standard 7 bit ASCII. Alphabetic case is significant for identifiers, but not
mnemonics and reserved words. Tabs are treated as equivalent to spaces.
4.3.2.1 Delimiters
All numbers and identifiers must be delimited by white space, non-alphanumeric characters or the
end of a line.
4.3.3 Comments
An assembly comment is initiated with a semicolon that is not part of a string or character constant.
Single-line C++ style comments (i.e. // syntax) are also permitted by the assembler.
If the assembly file is first processed by the C preprocessor, see Section 2.6.11, then it may also
contain C style comments using the standard /* ... */ syntax.
117
HI-TECH C Assembly Language Macro Assembler
4.3.4 Constants
4.3.4.1 Numeric Constants
The assembler performs all arithmetic with signed 32-bit precision. The radix of numeric constants
are specified using the formats given in Table 4.3.
Hexadecimal numbers must have a leading decimal digit (e.g. 0ffffh) to differentiate them from
identifiers. Hexadecimal digits are accepted in either upper or lower case.
Note that a binary constant cannot have a as a lower case b following it as this is used for
temporary (numeric) label backward references. Binary constants with a following upper case B are
of course permitted.
In expressions, real numbers are accepted in the usual format, and are interpreted as IEEE 32-bit
format.
118
Macro Assembler HI-TECH C Assembly Language
Multi-character constants, or strings, are a sequence of characters, not including carriage return
or newline characters, enclosed within matching quotes. Either single quotes ’ or double quotes "
maybe used, but the opening and closing quotes must be the same.
4.3.5 Identifiers
Assembly identifiers are user-defined symbols representing memory locations or numbers. A sym-
bol may contain any number of characters drawn from the alphabetics, numerics and the special
characters dollar, $, question mark, ? and underscore, _.
The first character of an identifier may not be numeric. The case of alphabetics is significant,
e.g. Fred is not the same symbol as fred. Some examples of identifiers are shown here:
An_identifier
an_identifier
an_identifier1
$
?$_12345
Users of other assemblers that attempt to implement forms of data typing for identifiers should note
that this assembler attaches no significance to any symbol, and places no restrictions or expectations
on the usage of a symbol.
The names of psects (program sections) and ordinary symbols occupy separate, overlapping
name spaces, but other than this, the assembler does not care whether a symbol is used to represent
bytes, words or sports cars. No special syntax is needed or provided to define the addresses of bits
or any other data type, nor will the assembler issue any warnings if a symbol is used in more than
one context. The instruction and addressing mode syntax provide all the information necessary for
the assembler to generate correct code.
Where a LOCAL directive is used in a macro block, the assembler will generate a unique symbol to
replace each specified identifier in each expansion of that macro. These unique symbols will have
the form ??nnnn where nnnn is a 4 digit number. The user should avoid defining symbols with the
same form.
119
HI-TECH C Assembly Language Macro Assembler
120
Macro Assembler HI-TECH C Assembly Language
psect text
main:
mov a, 0
.loop_start:
cmp a, 10
jz .loop_end
inc a
call foo
jmp .loop_start
.loop_end:
jmp main
foo:
push a
; do stuff
pop a
ret
In the above example there are two re-usable local labels defined, viz. .loop_start and
.loop_end. The scope of both these labels is bounded above by the global symbol main and
below by the local symbol foo. Outside of this scope these symbols may be redefined or
“re-used” and hence take on new meaning within those scopes.
Regardless of the type of label and how they are defined, the assembler list file produced by the
assembler will always show labels on a line by themselves.
Labels may be used (and are preferred) in assembly code rather than using an absolute address.
Thus they can be used as the target location for jump-type instructions or to load an address into a
register.
4.3.6 Expressions
The operands to instructions and directives are comprised of expressions. Expressions can be made
up of numbers, identifiers, strings and operators.
Operators can be unary (one operand, e.g. not) or binary (two operands, e.g. +). The operators
allowable in expressions are listed in Table 4.4. The usual rules governing the syntax of expressions
apply.
•
Care should be taken when using the modulus operator “%” as it can possibly be con-
fused with the beginning of a binary number. In order to avoid this confusion the oper-
ator should be surrounded by white-space. Furthermore care should also be exercised
121
HI-TECH C Assembly Language Macro Assembler
when using the operators “>” and “<”. Depending on the context in which they occur
these can be interpreted as the greater-than and less-than binary operators or the high-
byte and low-byte operators respectively.
The operators listed may all be freely combined in both constant and relocatable expressions. The
HI-TECH linker permits relocation of complex expressions, so the results of expressions involving
relocatable identifiers may not be resolved until link time.
•
The concept of a program section is not a HI-TECH-only feature. Often referred to as
blocks or segments in other compilers, these grouping of code and data have long used
the names text, bss and data.
A psect is identified by a name and has several attributes. The PSECT assembler directive can be used
to define a psect. It takes as arguments a name and an optional comma-separated list of flags. See
the section 4.3.8.4 for full information on psect definitions. A psect may also be defined using the
PSoC AREA directive. See the section 4.3.8.5 for more information regarding this directive. Chapter
5 has more information on the operation of the linker and on options that can be used to control psect
placement in memory.
The assembler associates no significance to the name of a psect and the linker is also not aware
of which are compiler-generated or user-defined psects. Unless defined as abs (absolute), psects are
relocatable.
The following is an example showing some executable instructions being placed in the text
psect, and some data being placed in the bss psect.
PSECT text,class=CODE,delta=1
adjust:
call clear_fred
inc:
mov a, [_fred]
inc a
mov [_fred], a
122
Macro Assembler HI-TECH C Assembly Language
123
HI-TECH C Assembly Language Macro Assembler
PSECT bss0,class=RAM,space=1
_fred:
BLK 1
PSECT text,class=CODE,delta=1
clear_fred:
mov [_fred], 0
ret
Note that even though the two blocks of code in the text psect are separated by a block in the bss0
psect, the two text psect blocks will be contiguous when loaded by the linker. In other words, the
mov [_fred],a instruction will be followed by the mov [_fred],0 instruction in the final output.
The actual location in memory of the text and bss0 psects will be determined by the linker.
Code or data that is not explicitly placed into a psect will become part of the default (unnamed)
psect.
4.3.8.1 GLOBAL
GLOBAL declares a list of symbols which, if defined within the current module, are made public. If
the symbols are not defined in the current module, it is a reference to symbols in external modules.
Example:
GLOBAL lab1,lab2,lab3
4.3.8.2 EXPORT
The EXPORT directive is a synonym of the GLOBAL directive. It has the exact same syntax and seman-
tics of the GLOBAL directive.
124
Macro Assembler HI-TECH C Assembly Language
125
HI-TECH C Assembly Language Macro Assembler
4.3.8.3 END
END is optional, but if present should be at the very end of the program. It will terminate the assembly
and not even blank lines should follow this directive. If an expression is supplied as an argument,
that expression will be used to define the start address of the program. Whether this is of any use
will depend on the linker. Example:
END start_label
4.3.8.4 PSECT
The PSECT directive declares or resumes a program section. It takes as arguments a name and,
optionally, a comma-separated list of flags. The allowed flags are listed in Table 4.6, below.
Once a psect has been declared it may be resumed later by another PSECT directive, however the
flags need not be repeated.
• abs defines the current psect as being absolute, i.e. it is to start at location 0. This does
not mean that this module’s contribution to the psect will start at 0, since other modules may
contribute to the same psect.
126
Macro Assembler HI-TECH C Assembly Language
• rel defines the current psect as being relocatable. All psects are by default relocatable.
• The bit flag specifies that a psect hold objects that are 1 bit long. Such psects have a scale
value of 8 to indicate that there are 8 addressable units to each byte of storage.
• The class flag specifies a class name for this psect. Class names are used to allow local psects
to be referred to by a class name at link time, since they cannot be referred to by their own
name. Class names are also useful where psects need only be positioned anywhere within a
range of addresses rather than at one specific address.
• The delta flag defines the size of an addressing unit. In other words, the number of bytes
covered for an increment in the address.
• A psect defined as global will be combined with other global psects of the same name from
other modules at link time. This is the default behaviour for psects, unless the local flag is
used.
• The limit flag specifies a limit on the highest address to which a psect may extend.
• A psect defined as local will not be combined with other local psects at link time, even if
there are others with the same name. Where there are two local psects in the one module,
they reference the same psect. A local psect may not have the same name as any global
psect, even one in another module.
• A psect defined as ovrld will have the contribution from each module overlaid, rather than
concatenated at runtime. ovrld in combination with abs defines a truly absolute psect, i.e. a
psect within which any symbols defined are absolute.
• A psect defined as con will have all its blocks in all modules loaded contiguously by the linker.
All psect blocks are by default loaded in this manner.
• The pure flag instructs the linker that this psect will not be modified at runtime and may
therefore, for example, be placed in ROM. This flag is of limited usefulness since it depends
on the linker and target system enforcing it.
• The reloc flag allows specification of a requirement for alignment of the psect on a particular
boundary, e.g. reloc=100h would specify that this psect must start on an address that is a
multiple of 100h.
• The size flag allows a maximum size to be specified for the psect, e.g. size=100h. This will
be checked by the linker after psects have been combined from all modules.
127
HI-TECH C Assembly Language Macro Assembler
• The space flag is used to differentiate areas of memory which have overlapping addresses,
but which are distinct. Psects which are positioned in program memory and data memory may
have a different space value to indicate that the program space address zero, for example,
is a different location to the data memory address zero. Devices which use banked RAM
data memory typically have the same space value as their full addresses (including bank
information) are unique.
• The with flag allows a psect to be placed in the same page with a specified psect. For example
with=text will specify that this psect should be placed in the same page as the text psect.
PSECT fred
PSECT bill,size=100h,global
PSECT joh,abs,ovrld,class=CODE,delta=2
4.3.8.5 AREA
The AREA directive provides a syntactic alternative to the PSECT directive and has the following
form:
where psect_name is the name of the psect being declared or resumed, class_name (which
is required) is the name of the class the psect belongs to and psect_flags_list is an optional
list of psects flags as described in previously in section 4.3.8.4 and table 4.6. The following pairs of
examples are equivalent:
4.3.8.6 ORG
The ORG directive changes the value of the location counter within the current psect. This means that
the addresses set with ORG are relative to the base address of the psect, which is not determined until
link time.
128
Macro Assembler HI-TECH C Assembly Language
•
The much-abused ORG directive does not necessarily move the location counter to the
absolute address you specify as the operand. This directive is rarely needed in programs.
The argument to ORG must be either an absolute value, or a value referencing the current psect. In
either case the current location counter is set to the value determined by the argument. It is not
possible to move the location counter backward. For example:
ORG 100h
will move the location counter to the beginning of the current psect plus 100h. The actual location
will not be known until link time.
In order to use the ORG directive to set the location counter to an absolute value, the directive
must be used from within an absolute, overlaid psect. For example:
PSECT absdata,abs,ovrld
ORG 50h
4.3.8.7 EQU
This pseudo-op defines a symbol and equates its value to an expression. For example
thomas EQU 123h
The identifier thomas will be given the value 123h. EQU is legal only when the symbol has not
previously been defined. See also Section 4.3.8.8.
4.3.8.8 SET
This pseudo-op is equivalent to EQU except that allows a symbol to be re-defined. For example
thomas SET 0h
4.3.8.9 DB
DB is used to initialize storage as bytes. The argument is a list of expressions, each of which will be
assembled into one byte. Each character of the string will be assembled into one memory location.
Examples:
alabel: DB ’X’,1,2,3,4,
Note that because the size of an address unit in ROM is 2 bytes, the DB pseudo-op will initialise a
word with the upper byte set to zero.
129
HI-TECH C Assembly Language Macro Assembler
4.3.8.10 DW
DW operates in a similar fashion to DB, except that it assembles expressions into words. Example:
4.3.8.11 DDW
DDW operates in a similar fashion to DW, except that it assembles expressions into double (32-bit)
words. Example:
DDW 12345678h
4.3.8.12 DWL
By default all bytes are stored in big-endian order. This directive will store the byte pairs of each of
the specified words in little-endian order. Example:
4.3.8.13 DS
DS is used to store the ASCII values of a string of characters (see Section 4.3.4.2) without a null
terminating character. Example:
mystr: DS ’HELLO’
// will be stored in memory as
// mystr+0: 48h ’H’
// mystr+1: 45h ’E’
// mystr+2: 4Ch ’L’
// mystr+3: 4Ch ’L’
// mystr+4: 4Fh ’O’
130
Macro Assembler HI-TECH C Assembly Language
4.3.8.14 DSU
DSU is used to store the UNICODE values of a string of characters (see Section 4.3.4.2) without a
null terminating character. Example:
mystr: DSU ’HELLO’
// will be stored in memory as
// mystr+0: 00,48h ’H’
// mystr+2: 00,45h ’E’
// mystr+4: 00,4Ch ’L’
// mystr+6: 00,4Ch ’L’
// mystr+8: 00,4Fh ’O’
4.3.8.15 ASCIZ
ASCIZ is used to store the ASCII values of a string of characters (see Section 4.3.4.2) with a null
terminating character. Example:
mystr: DS ’HELLO’
// will be stored in memory as
// mystr+0: 48h ’H’
// mystr+1: 45h ’E’
// mystr+2: 4Ch ’L’
// mystr+3: 4Ch ’L’
// mystr+4: 4Fh ’O’
// mystr+5: 00h ’\0’
4.3.8.16 BLK
This directive reserves, but does not initialize, memory locations. The single argument is the number
of bytes to be reserved. Examples:
alabel: BLK 23 ;Reserve 23 bytes of memory
xlabel: BLK 2+3 ;Reserve 5 bytes of memory
4.3.8.17 BLKW
This directive reserves, but does not initialize, memory locations. The single argument is the number
of words to be reserved. Examples:
alabel: BLKW 23 ;Reserve 23 words (or 46 bytes) of memory
xlabel: BLKW 2+3 ;Reserve 5 words (or 10 bytes) of memory
131
HI-TECH C Assembly Language Macro Assembler
IF ABC
jmp aardvark
ELSIF DEF
jmp denver
ELSE
jmp grapes
ENDIF
In this example, if ABC is non-zero, the first jmp instruction will be assembled but not the second or
third. If ABC is zero and DEF is non-zero, the second jmp will be assembled but the first and third
will not. If both ABC and DEF are zero, the third jmp will be assembled. Conditional assembly blocks
may be nested.
Macro Format 1
Macro Format 2
132
Macro Assembler HI-TECH C Assembly Language
ENDM
The MACRO directive is followed by the macro name (macro_name) and opening
and closing parentheses which contain an optional comma-separated list of formal
parameters (param_list). On the following line the definition of the macro body
begins (macro_body) until it is terminated by the ENDM directive on the last line.
When the macro is used, the macro name should be used in the same manner as a machine opcode,
followed by a list of arguments to be substituted for the formal parameters.
For example:
;macro: storem
;args: arg1 - the NAME of the source variable
; arg2 - the literal value to load
;descr: Loads two registers with the value in the variable:
ldtwo MACRO arg1,arg2
mov a, &arg2
mov [&arg1], a
ENDM
When used, this macro will expand to the 2 instructions in the body of the macro, with the formal
parameters substituted by the arguments. Thus:
storem tempvar,2
expands to:
mov a, 2
mov [tempvar], a
A point to note in the above example: the & character is used to permit the concatenation of macro
parameters with other text, but is removed in the actual expansion. The @ character may also be used
in the same manner. Furthermore occurrences of the @ character immediately followed by a decimal
digit n, will be replaced by the nth argument where n equals 0 refers to the first argument and so on.
A comment may be suppressed within the expansion of a macro (thus saving space in the macro
storage) by opening the comment with a double semicolon, ;;.
When invoking a macro, the argument list must be comma-separated.The exclamation mark, !
may be used to quote a single character. The character immediately following the exclamation mark
will be passed into the macro argument even if it is normally a comment indicator.
If an argument is preceded by a percent sign %, that argument will be evaluated as an expression
and passed as a decimal number, rather than as a string. This is useful if evaluation of the argument
inside the macro body would yield a different result.
The nul operator may be used within a macro to test a macro argument, for example:
133
HI-TECH C Assembly Language Macro Assembler
By default, the assembly list file will show macro in an unexpanded format, i.e. as the macro was
invoked. Expansion of the macro in the listing file can be shown by using the EXPAND assembler
control, see Section 4.3.9.2.
4.3.8.20 LOCAL
The LOCAL directive allows unique labels to be defined for each expansion of a given macro. Any
symbols listed after the LOCAL directive will have a unique assembler generated symbol substituted
for them when the macro is expanded. For example:
when expanded will include a unique assembler generated label in place of more. For example:
down foobar
expands to:
4.3.8.21 ALIGN
The ALIGN directive aligns whatever is following, data storage or code etc., to the specified boundary
in the psect in which the directive is found. The boundary is specified by a number following the
directive and it specifies a number of bytes. For example, to align output to a 2 byte (even) address
within a psect, the following could be used.
134
Macro Assembler HI-TECH C Assembly Language
ALIGN 2
Note, however, that what follows will only begin on an even absolute address if the psect begins on
an even address. The ALIGN directive can also be used to ensure that a psect’s length is a multiple
of a certain number. For example, if the above ALIGN directive was placed at the end of a psect, the
psect would have a length that was always an even number of bytes long.
4.3.8.22 REPT
The REPT directive temporarily defines an unnamed macro, then expands it a number of times as
determined by its argument. For example:
REPT 3
rr [input]
ENDM
will expand to
rr [input]
rr [input]
rr [input]
135
HI-TECH C Assembly Language Macro Assembler
Note that you can use local labels and angle brackets in the same manner as with conventional
macros.
The IRPC directive is similar, except it substitutes one character at a time from a string of non-
space characters.
For example:
PSECT romdata,class=CODE,reloc=256,delta=2
IRPC char,ABC
DB ‘char’
ENDM
PSECT text
PSECT romdata,class=CODE,reloc=256,delta=2
DB ’A’
DB ’B’
DB ’C’
PSECT text
4.3.8.24 INCLUDE
The INCLUDE directive provides the means to textually include an external source file. It is exactly
synonymous with the INCLUDE assembler control in section 4.3.9.3.
4.3.8.25 PROCESSOR
The output of the assembler may vary depending on the target device. The device name is typically
set using the --CHIP option to the command-line driver CPSOC, see Section 2.6.21, or using the
assembler -P option, see Section 4.1, but can also be set with this directive, e.g.
PROCESSOR CY8C29466
4.3.8.26 SIGNAT
This directive is used to associate a 16-bit signature value with a label. At link time the linker checks
that all signatures defined for a particular label are the same and produces an error if they are not. The
SIGNAT directive is used by the HI-TECH C compiler to enforce link time checking of C function
prototypes and calling conventions.
Use the SIGNAT directive if you want to write assembly language routines which are called from
C. For example:
136
Macro Assembler HI-TECH C Assembly Language
SIGNAT _fred,8192
will associate the signature value 8192 with the symbol _fred. If a different signature value for
_fred is present in any object file, the linker will report an error.
OPT EXPAND
4.3.9.1 COND
Any conditional code will be included in the listing output. See also the NOCOND control in Section
4.3.9.5.
4.3.9.2 EXPAND
When EXPAND is in effect, the code generated by macro expansions will appear in the listing output.
See also the NOEXPAND control in Section 4.3.9.6.
137
HI-TECH C Assembly Language Macro Assembler
4.3.9.3 INCLUDE
This control causes the file specified by pathname to be textually included at that point in the
assembly file. The INCLUDE control must be the last control keyword on the line, for example:
The driver does not pass any search paths to the assembler, so if the include file is not located in the
working directory, the pathname must specify the exact location.
See also the driver option -P in Section 2.6.11 which forces the C preprocessor to preprocess
assembly file, thus allowing use of preprocessor directives, such as #include (see Section 3.10.2).
4.3.9.4 LIST
If the listing was previously turned off using the NOLIST control, the LIST control on its own will
turn the listing on.
Alternatively, the LIST control may includes options to control the assembly and the listing. The
options are listed in 4.8.
See also the NOLIST control in Section 4.3.9.7.
4.3.9.5 NOCOND
Using this control will prevent conditional code from being included in the listing output. See also
the COND control in Section 4.3.9.1.
4.3.9.6 NOEXPAND
NOEXPAND disables macro expansion in the listing file. The macro call will be listed instead. See
also the EXPAND control in Section 4.3.9.2. Assembly macro are discussed in Section 4.3.8.19.
138
Macro Assembler HI-TECH C Assembly Language
4.3.9.7 NOLIST
This control turns the listing output off from this point onward. See also the LIST control in Section
4.3.9.4.
4.3.9.8 NOXREF
NOXREF will disable generation of the raw cross reference file. See also the XREF control in Section
4.3.9.13.
4.3.9.9 PAGE
PAGE causes a new page to be started in the listing output. A Control-L (form feed) character will
also cause a new page when encountered in the source.
4.3.9.10 SPACE
The SPACE control will place a number of blank lines in the listing output as specified by its param-
eter.
4.3.9.11 SUBTITLE
SUBTITLE defines a subtitle to appear at the top of every listing page, but under the title. The string
should be enclosed in single or double quotes. See also the TITLE control in Section 4.3.9.12.
4.3.9.12 TITLE
This control keyword defines a title to appear at the top of every listing page. The string should be
enclosed in single or double quotes. See also the SUBTITLE control in Section 4.3.9.11.
4.3.9.13 XREF
XREF is equivalent to the driver command line option --CR (see Section 2.6.23). It causes the assem-
bler to produce a raw cross reference file. The utility CREF should be used to actually generate the
formatted cross-reference listing.
139
Assembler List Files Macro Assembler
4.4.1 Generation
TM
If compilation is being performed via HI-TIDE an assembler list file is generated by default with-
out you having to adjust the compiler options. If you are using the driver from the command line then
you will need to use the --ASMLIST option, see Section 2.6.17. Assembler list files are produced
by the assembler, however are updated by the linker to show absolute address. If the compilation
process is stopped before the assembler is executed, then no assembler list file is produced. If the
linker does not run to completion, then the assembler list file will not be updated to indicate absolute
address.
There will be one assembler list file produced for each assembler input file to the linker. Thus
each assembler source file will produce an assembler list file. There will be one assembler list file
produced for all of the C program (source files and library routines) when using a PRO compiler, or
one assembler list file per C source file if using a STD version compiler.
The filenames for the list files will typically be the basename of the input file and the extension
.lst. In he case of PRO compilers, the assembler list file corresponding to the C source code will
have the basename of the first source file specified on the command-line.
Note that if the --ASMLIST option is not used, files with a .lst extension are still produced.
These are C list files produced the CLIST application that ships with the compiler.
Assembler list files are a debug file intended for human use. They are not true assembler files
and cannot be passed to the assembler for processing.
4.4.2 Contents
An assembly list file can be produced for assembly source files, or for the intermediate assembly
files produced from C source code. Specifically, they shows the following information.
• The original C or assembly code that was contained in the input source file
140
Macro Assembler Assembler List Files
optimizer may remove some assembler directives from the assembler listing file for clarity.
Disable the assembler optimizer if you wish to see all these directives.
• Assembler directives issued by the code generator
• Absolute addresses determined by either the code generator or linker
• The symbol table for this assembly module
The following example shows an extract from an assembly list file for a fictional micro controller.
The depiction here differs slightly in format from that actually produced for reasons of clarity. The
numbers on the top line indicate the column number discussed below.
1 2 3 4 5 6
96 PSECT text
97 003FEA _main
98 003FEA FFFF DW 0FFFFh
99 003FEC 1208 goto f22
100 003FEE f21:
101 GLOBAL _foo
102 ;main.c: 6: foo = 1;
103 003FEE 5501 ldlit r0,01h
104 003FF0 CFE8 F5FF movwd r0,_foo
105 ;main.c: 7: foo++;
106 003FF4 7105 selb _foo > > 8
107 003FF8 1BFF inc _foo&0ffh
108 ;main.c: 8: }
The columns, from left to right, contain:
1. The assembly listing file line number
This number can be used for reference. It has no significance in terms of the source code or
the generated output.
2. The address of any output shown on that line
The address shown is the link address. An address is not shown for comment lines, or direc-
tives that do not produce any code. Labels always show the address at which they represent.
3. The opcode or data values contained at that address
If the instruction or directive produces more than one word of output, these words will typ-
ically be shown on the one line with a space between the words. In the above example, the
movwd instruction, on line 104 (address 3FF0) is a two-word instruction.
141
Assembler List Files Macro Assembler
4. The file name, line number and original code which was translated into the assembly following
These lines are preceded by a semicolon.
5. Assembly labels
6. Assembly instructions, or assembler directives or controls
The above listing shows the situation when then linker has run to completion and the list file has
been updated to show absolute addresses. If the linker does not execute, due to errors or that part of
the compilation process being disabled, the listing file will look similar to the following.
1 2 3 4 5 6
96 PSECT text
97 000000’ _main
98 000000’ FFFF DW 0FFFFh
99 000002’ 1208 goto f22
100 000004’ f21:
101 GLOBAL _foo
102 ;main.c: 6: foo = 1;
103 000004’ 5501 ldlit r0,01h
104 000006’ CFE8 F000’ movwd r0,_foo
105 ;main.c: 7: foo++;
106 00000A’ 7100’ selb _foo > > 8
107 00000C’ 1B00’ inc _foo&0ffh
108 ;main.c: 8: }
The output is similar but tick marks ’ have not been removed by the linker indicating that the ad-
dresses specified are not absolute.
Now, the address column shows the address offset into the current psect.
Note that there are tick marks next to some of the opcodes, which signifies that these opcode are
not absolute. These are opcode that reference the address of a symbol that is allocated memory by
the linker — until the linker has executed, these addresses are unknown and are shown as 0 in the
preliminary assembler listing file.
•
The process of updating the assembler list file by the linker involves the use of a relo-
catable list file (RLF file) that is produced by the assembler along side the assembler
list file. The linker actually updates the RLF file, the result of which is the absolute
assembler list file which is then moved over the original list file.
142
Chapter 5
5.1 Introduction
HI-TECH C incorporates a relocating assembler and linker to permit separate compilation of C
source files. This means that a program may be divided into several source files, each of which
may be kept to a manageable size for ease of editing and compilation, then each source file may be
compiled separately and finally all the object files linked together into a single executable program.
This chapter describes the theory behind and the usage of the linker. Note however that in most
instances it will not be necessary to use the linker directly, as the compiler driver will automatically
invoke the linker with all necessary arguments. Using the linker directly is not simple, and should
be attempted only by those with a sound knowledge of the compiler and linking in general.
If it is absolutely necessary to use the linker directly, the best way to start is to copy the linker
arguments constructed by the compiler driver, and modify them as appropriate. This will ensure that
the necessary startup module and arguments are present.
Note also that the linker supplied with HI-TECH C is generic to a wide variety of compilers for
several different processors. Not all features described in this chapter are applicable to all compilers.
143
Program Sections Linker and Utilities
relocation by the ultimate value of a global symbol, or relocation by psect, i.e. relocation by the
base address of a particular section of code, for example the section of code containing the actual
executable instructions.
144
Linker and Utilities Link and load addresses
as static. These symbols may be referred to by modules other than the one in which they are
defined. It is the linker’s job to match up the definition of a global symbol with the references to it.
Other symbols (local symbols) are passed through the linker to the symbol file, but are not otherwise
processed by the linker.
5.7 Operation
A command to the linker takes the following form:
Options is zero or more linker options, each of which modifies the behaviour of the linker in some
way. Files is one or more object files, and zero or more library names. The options recognised by
the linker are listed in Table 5.1 and discussed in the following paragraphs.
Option Effect
-8 Use 8086 style segment:offset address form
-Aclass=low-high,... Specify address ranges for a class
-Cx Call graph options
continued. . .
145
Operation Linker and Utilities
Option Effect
-Cpsect=class Specify a class name for a global psect
-Cbaseaddr Produce binary output file based at baseaddr
-Dclass=delta Specify a class delta value
-Dsymfile Produce old-style symbol file
-Eerrfile Write error messages to errfile
-F Produce .obj file with only symbol records
-Gspec Specify calculation for segment selectors
-Hsymfile Generate symbol file
-H+symfile Generate enhanced symbol file
-I Ignore undefined symbols
-Jnum Set maximum number of errors before aborting
-K Prevent overlaying function parameter and auto areas
-L Preserve relocation items in .obj file
-LM Preserve segment relocation items in .obj file
-N Sort symbol table in map file by address order
-Nc Sort symbol table in map file by class address order
-Ns Sort symbol table in map file by space address order
-Mmapfile Generate a link map in the named file
-Ooutfile Specify name of output file
-Pspec Specify psect addresses and ordering
-Qprocessor Specify the processor type (for cosmetic reasons only)
-S Inhibit listing of symbols in symbol file
-Sclass=limit[,bound] Specify address limit, and start boundary for a class of psects
-Usymbol Pre-enter symbol in table as undefined
-Vavmap Use file avmap to generate an Avocet format symbol file
-Wwarnlev Set warning level (-9 to 9)
-Wwidth Set map file width (>=10)
-X Remove any local symbols from the symbol file
-Z Remove trivial local symbols from the symbol file
146
Linker and Utilities Operation
5.7.2 -Aclass=low-high,...
Normally psects are linked according to the information given to a -P option (see below) but some-
times it is desired to have a class of psects linked into more than one non-contiguous address range.
This option allows a number of address ranges to be specified for a class. For example:
-ACODE=1020h-7FFEh,8000h-BFFEh
specifies that the class CODE is to be linked into the given address ranges. Note that a contribution
to a psect from one module cannot be split, but the linker will attempt to pack each block from each
module into the address ranges, starting with the first specified.
Where there are a number of identical, contiguous address ranges, they may be specified with a
repeat count, e.g.
-ACODE=0-FFFFhx16
specifies that there are 16 contiguous ranges each 64k bytes in size, starting from zero. Even though
the ranges are contiguous, no code will straddle a 64k boundary. The repeat count is specified as the
character x or * after a range, followed by a count.
5.7.3 -Cx
These options allow control over the call graph information which may be included in the map file
produced by the linker. There are four varients of this option:
Fully expanded callgraph The -Cf option displays the full callgraph information.
Short form callgraph The -Cs option is the default callgraph option which removes some redun-
dant information from the callgraph display. In the case where there are parameters to a func-
tion that involve function calls, the callgraph information associated with the “ARG function”
is only shown the first time it is encountered in the callgraph. See Sections 5.9.1 and 5.10.2.2
for more information on these functions.
Critical path callgraph The -Cc option only include the critical paths of the call graph. A function
call that is marked with a * in a full call graph is on a critical path and only these calls are
included when the -Cc option is used. See Section 5.10.2.2 for more information on critcal
paths.
No callgraph The -Cn option removes the call graph information from the map file.
147
Operation Linker and Utilities
5.7.4 -Cpsect=class
This option will allow a psect to be associated with a specific class. Normally this is not required on
the command line since classes are specified in object files.
5.7.5 -Dclass=delta
This option allows the delta value for psects that are members of the specified class to be defined.
The delta value should be a number and represents the number of bytes per addressable unit of
objects within the psects. Most psects do not need this option as they are defined with a delta value.
5.7.6 -Dsymfile
Use this option to produce an old-style symbol file. An old-style symbol file is an ASCII file, where
each line has the link address of the symbol followed by the symbol name.
5.7.7 -Eerrfile
Error messages from the linker are written to standard error (file handle 2). Under DOS there is no
convenient way to redirect this to a file (the compiler drivers will redirect standard error if standard
output is redirected). This option will make the linker write all error messages to the specified file
instead of the screen, which is the default standard error destination.
5.7.8 -F
Normally the linker will produce an object file that contains both program code and data bytes, and
symbol information. Sometimes it is desired to produce a symbol-only object file that can be used
again in a subsequent linker run to supply symbol values. The -F option will suppress data and code
bytes from the output file, leaving only the symbol records.
This option can be used when producing more than one hex file for situations where the program
is contained in different memory devices located at different addresses. The files for one device are
compiled using this linker option to produce a symbol-only object file; this is then linked with the
files for the other device. The process can then be repeated for the other files and device.
5.7.9 -Gspec
When linking programs using segmented, or bank-switched psects, there are two ways the linker
can assign segment addresses, or selectors, to each segment. A segment is defined as a contiguous
group of psects where each psect in sequence has both its link and load address concatenated with
148
Linker and Utilities Operation
the previous psect in the group. The segment address or selector for the segment is the value derived
when a segment type relocation is processed by the linker.
By default the segment selector will be generated by dividing the base load address of the seg-
ment by the relocation quantum of the segment, which is based on the reloc= flag value given to
psects at the assembler level. This is appropriate for 8086 real mode code, but not for protected mode
or some bank-switched arrangements. In this instance the -G option is used to specify a method for
calculating the segment selector. The argument to -G is a string similar to:
A/10h-4h
where A represents the load address of the segment and / represents division. This means "Take the
load address of the psect, divide by 10 hex, then subtract 4". This form can be modified by substi-
tuting N for A, * for / (to represent multiplication), and adding rather than subtracting a constant.
The token N is replaced by the ordinal number of the segment, which is allocated by the linker. For
example:
N*8+4
means "take the segment number, multiply by 8 then add 4". The result is the segment selector. This
particular example would allocate segment selectors in the sequence 4, 12, 20, ... for the number
of segments defined. This would be appropriate when compiling for 80286 protected mode, where
these selectors would represent LDT entries.
5.7.10 -Hsymfile
This option will instruct the linker to generate a symbol file. The optional argument symfile
specifies a file to receive the symbol file. The default file name is l.sym.
5.7.11 -H+symfile
This option will instruct the linker to generate an enhanced symbol file, which provides, in addition
to the standard symbol file, class names associated with each symbol and a segments section which
lists each class name and the range of memory it occupies. This format is recommended if the code
is to be run in conjunction with a debugger. The optional argument symfile specifies a file to
receive the symbol file. The default file name is l.sym.
5.7.12 -Jerrcount
The linker will stop processing object files after a certain number of errors (other than warnings).
The default number is 10, but the -J option allows this to be altered.
149
Operation Linker and Utilities
5.7.13 -K
For compilers that use a compiled stack, the linker will try and overlay function auto and parameter
areas in an attempt to reduce the total amount of RAM required. For debugging purposes, this feature
can be disabled with this option.
5.7.14 -I
Usually failure to resolve a reference to an undefined symbol is a fatal error. Use of this option will
cause undefined symbols to be treated as warnings instead.
5.7.15 -L
When the linker produces an output file it does not usually preserve any relocation information, since
the file is now absolute. In some circumstances a further "relocation" of the program will be done at
load time, e.g. when running a .exe file under DOS or a .prg file under TOS. This requires that some
information about what addresses require relocation is preserved in the object (and subsequently the
executable) file. The -L option will generate in the output file one null relocation record for each
relocation record in the input.
5.7.16 -LM
Similar to the above option, this preserves relocation records in the output file, but only segment
relocations. This is used particularly for generating .exe files to run under DOS.
5.7.17 -Mmapfile
This option causes the linker to generate a link map in the named file, or on the standard output if
the file name is omitted. The format of the map file is illustrated in Section 5.10.
5.7.19 -Ooutfile
This option allows specification of an output file name for the linker. The default output file name is
l.obj. Use of this option will override the default.
150
Linker and Utilities Operation
5.7.20 -Pspec
Psects are linked together and assigned addresses based on information supplied to the linker via -P
options. The argument to the -P option consists basically of comma-separated sequences thus:
-Ppsect=lnkaddr+min/ldaddr+min,psect=lnkaddr/ldaddr, ...
There are several variations, but essentially each psect is listed with its desired link and load ad-
dresses, and a minimum value. All values may be omitted, in which case a default will apply,
depending on previous values.
The minimum value, min, is preceded by a + sign, if present. It sets a minimum value for the
link or load address. The address will be calculated as described below, but if it is less than the
minimum then it will be set equal to the minimum.
The link and load addresses are either numbers as described above, or the names of other psects
or classes, or special tokens. If the link address is a negative number, the psect is linked in reverse
order with the top of the psect appearing at the specified address minus one. Psects following a
negative address will be placed before the first psect in memory. If a link address is omitted, the
psect’s link address will be derived from the top of the previous psect, e.g.
-Ptext=100h,data,bss
In this example the text psect is linked at 100 hex (its load address defaults to the same). The data
psect will be linked (and loaded) at an address which is 100 hex plus the length of the text psect,
rounded up as necessary if the data psect has a reloc= value associated with it. Similarly, the bss
psect will concatenate with the data psect. Again:
-Ptext=-100h,data,bss
will link in ascending order bss, data then text with the top of text appearing at address 0ffh.
If the load address is omitted entirely, it defaults to the same as the link address. If the slash /
character is supplied, but no address is supplied after it, the load address will concatenate with the
previous psect, e.g.
-Ptext=0,data=0/,bss
will cause both text and data to have a link address of zero, text will have a load address of 0, and
data will have a load address starting after the end of text. The bss psect will concatenate with data
for both link and load addresses.
The load address may be replaced with a dot . character. This tells the linker to set the load
address of this psect to the same as its link address. The link or load address may also be the name of
another (already linked) psect. This will explicitly concatenate the current psect with the previously
specified psect, e.g.
151
Operation Linker and Utilities
-Ptext=0,data=8000h/,bss/. -Pnvram=bss,heap
This example shows text at zero, data linked at 8000h but loaded after text, bss is linked and
loaded at 8000h plus the size of data, and nvram and heap are concatenated with bss. Note here
the use of two -P options. Multiple -P options are processed in order.
If -A options have been used to specify address ranges for a class then this class name may be
used in place of a link or load address, and space will be found in one of the address ranges. For
example:
-ACODE=8000h-BFFEh,E000h-FFFEh
-Pdata=C000h/CODE
This will link data at C000h, but find space to load it in the address ranges associated with CODE.
If no sufficiently large space is available, an error will result. Note that in this case the data psect
will still be assembled into one contiguous block, whereas other psects in the class CODE will be
distributed into the address ranges wherever they will fit. This means that if there are two or more
psects in class CODE, they may be intermixed in the address ranges.
Any psects allocated by a -P option will have their load address range subtracted from any
address ranges specified with the -A option. This allows a range to be specified with the -A option
without knowing in advance how much of the lower part of the range, for example, will be required
for other psects.
5.7.21 -Qprocessor
This option allows a processor type to be specified. This is purely for information placed in the map
file. The argument to this option is a string describing the processor.
5.7.22 -S
This option prevents symbol information relating from being included in the symbol file produced
by the linker. Segment information is still included.
-SCODE=400h
152
Linker and Utilities Operation
Note that to set an upper limit to a psect, this must be set in assembler code (with a limit= flag on
a PSECT directive).
If the bound (boundary) argument is used, the class of psects will start on a multiple of the bound
address. This example places the FARCODE class of psects at a multiple of 1000h, but with an upper
address limit of 6000h:
-SFARCODE=6000h,1000h
5.7.24 -Usymbol
This option will enter the specified symbol into the linker’s symbol table as an undefined symbol.
This is useful for linking entirely from libraries, or for linking a module from a library where the
ordering has been arranged so that by default a later module will be linked.
5.7.25 -Vavmap
To produce an Avocet format symbol file, the linker needs to be given a map file to allow it to
map psect names to Avocet memory identifiers. The avmap file will normally be supplied with the
compiler, or created automatically by the compiler driver as required.
5.7.26 -Wnum
The -W option can be used to set the warning level, in the range -9 to 9, or the width of the map file,
for values of num >= 10.
-W9 will suppress all warning messages. -W0 is the default. Setting the warning level to -9 (-W-9)
will give the most comprehensive warning messages.
5.7.27 -X
Local symbols can be suppressed from a symbol file with this option. Global symbols will always
appear in the symbol file.
5.7.28 -Z
Some local symbols are compiler generated and not of interest in debugging. This option will
suppress from the symbol file all local symbols that have the form of a single alphabetic character,
followed by a digit string. The set of letters that can start a trivial symbol is currently "klfLSu".
The -Z option will strip any local symbols starting with one of these letters, and followed by a digit
string.
153
Invoking the Linker Linker and Utilities
-Z -OX.OBJ -MX.MAP \
-Ptext=0,data=0/,bss,nvram=bss/. \
X.OBJ Y.OBJ Z.OBJ C:\HT-Z80\LIB\Z80-SC.LIB
hlink @x.lnk
hlink < x.lnk
154
Linker and Utilities Compiled Stack Operation
the linker performs additional operations to minimise the memory consumed by the program by
overlaying each function’s APB where possible.
In assembly code variables within a function’s APB are referenced via special symbols, which
marks the start of the auto or parameter area in the block, and an offset. The symbol used to represent
the base address of the parameter area within the function’s APB is the concatenation of ? and the
assembler name of the function. The symbol used to represent the base address of the auto area
within the function’s APB is the concatenation of ?a, in the case of Standard version compilers, or
??, in the case of PRO version compilers, and the assembler name of the function.
For example, a function called foo, for example, will use the assembly symbol ?_foo as the
base address for all its parameters variables that have been allocated memory, and either ?a_foo
(Standard) or ??_foo (PRO) as the base address for auto variables which the function defines. So
the first two-byte auto variable might be referenced in PRO version compiler assembly code as
??_foo; the second auto variable as ??_foo+2, etc. Note that some parameters may be passed in
registers, and may not have memory allocated to them in the parameter area of the APB.
The linker allocates memory for each function’s APB, based on how that function is used in a
program. In particular, the linker determines which functions are, or may be, active at the same
time. If one function calls another, then both are active at the same time. To this end, a call graph
is created from information in the object files being linker. See Section 5.10.2.2 for information on
reading the call graph displayed in the map file. This information is directly related to the FNCALL
assembler directive (see Section ?? for more information) which the code generator places in the
assembler output whenever a C function calls another. Hand-written assembler code should also
contain these directives, if required. Information regarding the size of the auto and parameter areas
within in function’s APB is specified by the FNSIZE assembler directive (see Section ??).
shows that the function input is called to determine the second parameter to the function output.
This information is very important as it indicates areas of the code that must be considered carefully,
lest the code fail due to re-entrancy related issues.
A re-entrant call is typically considered to be the situation in which a function is called and
executed while another instance of the same function is also actively executing. For a compiled
stack program, a function must be considered active as soon as its parameter area has been modified
in preparation for a call, even though code in that function is not yet being executed and a call to
that function has not been made. This is particularly import with functions that accept more than
155
Compiled Stack Operation Linker and Utilities
one parameter as the ANSI standard does not dictate the order in which function parameters must be
evaluated.
Such a condition is best illustrated by an example, which is shown in the following tutorial.
T UT•RIAL
For the highlighted statement, the compiler might evaluate and load the first parameter
to the function B, which is the literal, 5. To do this, the value of 5 is loaded to the loca-
tions ?_B and ?_B+1. Now to evaluate the second parameter value to the function B, the
compiler must first call the function A. So A’s parameters are loaded and the call to func-
tion A is made. Code inside the function A, calls the function B. This involves loading
the parameters to B: the contents of the variable b are loaded to ?_B+2 and ?_B+3, and
the value 9 is loaded to ?_B and ?_B+1, which corrupts the contents of these locations
which were loaded earlier for the still pending call to function B. Function A eventually
returns normally and the the return value is the loaded to the second parameter locations
for the still pending call to function B, back at the highlighted line of source. However,
the value of 5 previously loaded as the first parameter to B has been lost. When the call
to function B is now made, the parameters will not be correct.
Note that the function B is not actively executing code in more than one instance of the
function at the same time, however the code that loads the parameters to function B is.
The linker indicates in the call graph those functions that may have been called to determine param-
eter values to other functions. See Section 5.10.2.2 for information on how this is displayed in the
map file.
156
Linker and Utilities Map Files
5.10.1 Generation
TM
If compilation is being performed via HI-TIDE a map file is generated by default without you
having to adjust the compiler options. If you are using the driver from the command line then you’ll
need to use the -M option, see Section 2.6.8.
Map files are produced by the linker. If the compilation process is stopped before the linker is
executed, then no map file is produced. The linker will still produce a map file even if it encounters
errors, which will allow you to use this file to track down the cause of the errors. However, if the
linker ultimately reports too many errors then it did not run to completion, and the map file will
be either not created or not complete. You can use the --ERRORS option on the command line, or as
an alternate MPLAB IDE setting, to increase the number of errors before the compiler applications
give up. See Section 2.6.26 for more information on this option.
5.10.2 Contents
The sections in the map file, in order of appearance, are as follows:
• The compiler name and version number;
• A copy of the command line used to invoke the linker;
• The version number of the object code in the first file linked;
• The machine type;
• Optionally (dependent on the processor and compiler options selected), the call graph infor-
mation;
• A psect summary sorted by the psect’s parent object file;
• A psect summary sorted by the psect’s CLASS;
• A segment summary;
• Unused address ranges summary; and
• The symbol table
Portions of an example map file, along with explanatory text, are shown in the following sections.
157
Map Files Linker and Utilities
The Linker command line shown is the entire list of options and files that were passed to the linker
for the build recorded by this map file. Remember, these are linker options and not command-line
driver options. Typically the first options relate to general execution of the linker: path and file
names for various input and output support files; and the chip type etc. These are followed by the
memory allocation options, e.g. -A and -p. Last are the input object and library files that will be
linked to form the output.
The linker command line should be used to confirm that driver options that control the link step
have been specified correctly, and at the correct time. It is particularly useful when using the driver
-L- option, see Section 2.6.7.
T UT•RIAL
158
Linker and Utilities Map Files
First the program is compiled without using this option and the following linker class
definition is noted in the linker command line:
-ACODE=0-03FFFhx2
The class name may vary between compilers and the selected target device, however
there is typically a class that is defined to cover the entire memory space used by the
device.
The driver option --ROM=default,-4000-400F is then used and the map file resulting
from the subsequent build shows the following change:
-ACODE=0-03FFFh,04010h-07FFFh
which confirms that the memory option was seen by the linker and that the memory
requested was reserved.
• The functions in the program that are “root” nodes marking the top of a call tree, and which
are not directly called;
• The functions that the linker deemed were called, or may have been called, during program
execution;
• The program’s hierarchy of function calls;
• The size of the auto and parameter areas within each function’s APB;
• The offset of each function’s APB within the program’s auto/parameter psect;
• Which functions’ APBs are consuming memory not overlapped by the APB of any other
function (on the critical path);
• Which functions are called indirectly;
• Which functions are called as part of a parameter expression for another function; and
159
Map Files Linker and Utilities
Call graph:
*_main size 0,4 offset 0
* _byteconv size 0,17 offset 4
float size 3,7 offset 21
ldiv size 8,6 offset 21
_crv ARG size 0 offset 21
_crv size 1 offset 21
ldiv size 8,6 offset 21
_convert size 4,0 offset 33
_srv size 2,10 offset 21
_convert size 4,0 offset 33
* _srv size 2,10 offset 21
* _convert size 4,0 offset 33
_init size 0,4 offset 4
indir_func size 0,0 offset 4
Estimated maximum call depth: 3
*intlevel1 size 0,0 offset 37
* _isr size 0,2 offset 37
* i1ldiv size 8,6 offset 44
Estimated maximum call depth: 2
Each line basically consists of the name of the function in question, and its APB size and offset. The
general form of most entries look like:
Note that the function name will always be the assembly name, thus the function main appears as
_main.
A function printed with no indent is a root function in a call tree. These functions are typically
not called by the C program. Examples include the function main, any any interrupt functions the
program defines. The programmer may also define additional functions that are root functions in the
call tree by using the FNROOT assembler directive, see Section ?? for more information. The code
generator issues an FNROOT directive for each interrupt function encountered, and the runtime
startup code contains the FNROOT directive for the function main.
160
Linker and Utilities Map Files
The functions that the root function calls, or may call, are indented one level and listed below
the root node. If any of these functions call (or might call) other functions, these called functions
are indented and listed below the calling functions. And so the process continues for entire program.
A function’s inclusion into the call graph does not imply the function was called, but there is a
possibility that the function was called. For example, code such as:
int test(int a) {
if(a)
foo();
else
bar();
}
will list foo and bar under test, as either may be called. If a is always true, then clearly the function
bar will never be called. If a function does not appear in the call graph, the linker has determined
that the function cannot possibly be called, and that it is not a root function. For code like:
int test(void) {
int a = 0;
if(a)
foo();
else
bar();
}
161
Map Files Linker and Utilities
purposes, in which case they do not contribute to the function’s parameter size, but increase the size
of the auto area.
The total parameter and auto area for each function is grouped to form an APB. This is then
allocated an address within the program’s auto/parameter psect. The offset value indicates the offset
within the psect for that block. Thus, two APBs with the same offset are mapped over one another.
If a star, *, appears on the very left line of a call tree, this implies that the memory consumed
by the function represented by that line does not fully overlap with that of other functions, and thus
this functions APB directly influences the size of the auto/parameter psect, and hence the total RAM
usage of the program. Such functions are said to be on the critical path. If the RAM usage of a
program needs to be reduced and the number or size of the parameters or auto variables defined by
the starred functions can be reduced, the program’s RAM usage will also be reduced. Reducing the
number or size of the parameters or auto variables defined by the functions that are not starred will
have no effect on the program’s total RAM usage.
PRO compilers track the values assigned to function pointers and maintains a list of all functions
that could be called via the function pointer. Functions called indirectly are listed in the call graph
along with those functions which are directly called.
If the ARG flag appears after a function’s name, this implies that the call to this “ARG function”
involves other function calls to determine the parameter values for this function. For example, if
input and output are both functions that take two int parameters and and both return an int, the
following:
shows that the function input is called to determine the second parameter to the function output.
The ARG function’s name is listed again under the line which actually shows the ARG flag, and
any functions this function calls appear here, indented in the usual way. Under this is listed every
function (regardless of its depth in the call tree) that could be called to determine a parameter value
to the ARG function throughout the program. If any of these functions call other functions, they
also list called functions below, indented in the usual way. For example the following annotated call
graph snippet illustrates the ARG function one.
After each tree in call tree, there is an indication of the maximum call depth that might be realised
162
Linker and Utilities Map Files
by that tree. This may be used as a guide to the stack usage of the program. No definitive value can
be given for the program’s total stack usage for several reasons:
• Certain parts of the call tree may never be reached, reducing that tree’s stack usage;
• The contribution of interrupt (or other) trees to the tree associated with the main function
cannot be determined as the point in main’s call tree at which the interrupt (or other function
invocation) will occur cannot be known;
• Any additional stack usage by functions, particularly interrupt functions, cannot be known;
and
• The assembler optimizer may have replaced function calls with jumps to functions, reducing
that tree’s stack usage.
The code generator also produces a warning if the maximum stack depth appears to have been
exceeded. For the above reasons, this warning, too, is intended to be a guide to potential stack
problems.
The above call graph example is analysed in the following tutorial.
T UT•RIAL
I NTERPRETING A PRO COMPILER CALL GRAPH The graph graph shown above
indicates that the program compiled consists of two call trees, rooted at the functions
main, which can have up 3 levels of stack used, and intlevel1, which can use up to two
levels of stack. In the example above, the symbol _main is associated with the function
main, and intlevel1 associated with an interrupt function (with an interrupt level
of 1).
Here, the function main takes no parameters and defines 4 bytes of auto variables. The
total size of the APB for main is 4, and this was placed at an offset of 0 in the program’s
auto/parameter psect. The function main may call a function called init. This function
also uses a total of 4 bytes of auto variables. The function main is still active when init
is active so their APBs must occupy distinct memory. (NB main will always be active
during program execution, by definition.) The block for init follows immediately after
that of main’s at address offset 4. The function init does not call any other functions.
The main function may also call the function byteconv. This function defines a total of
17 bytes of auto variables. It is called when main is still active, but it is never active at
the same time as init is active, so its APB can overlap with that of init and is placed
at offset 4 within the auto/parameter psect.
The function byteconv may call several functions: float, ldiv, crv and srv. (Any
function name that does not start with an underscore must be an assembly routine.
163
Map Files Linker and Utilities
The routine float and ldiv in this case relating to floating point and long division
library routines.) All these functions have their APB placed at the same offset in the
auto/parameter psect. Of these functions, srv also may call convert.
The call to crv from byteconv indicates that other functions might be called to obtain
crv’s parameter values. Those other functions are listed in a “flattened” call list below
the ARG function line which shows every possible function that might be called,
regardless of call depth. The functions which might be called are: ldiv, convert and
srv. The function srv, which also calls convert still indicates this fact by also listing
convert below and indented in the more conventional call graph format. The two lines
of C code that produced this outcome were:
if(crv((my_long%10)) != 5) // ...
if(crv(srv(8)) != 6) // ...
where crv accepts one char parameter and returns a char. The call to srv is obvious;
the other call come from the modulus operator, calling ldiv.
The other call tree rooted at intlevel1 relates to the interrupt function. intlevel1
is not a real function, but is used to represent the interrupt level associated with the
interrupt function. There is no call from intlevel1 to the function isr and no stack
usage. Note that an additional level of call depth is indicated for interrupt functions.
This is used to mark the place of the return address of the stack. The selected device
may use a differing number of stack locations when interrupts occur and this needs to
be factored into any stack calculations.
Notice that the interrupt function isr calls a function called i1ldiv. This is a du-
plicate of the ldiv routine that is callable by functions under the intlevel1 call tree.
Having duplicate routines means that these implicitly called assembly library routines
can safely be called from both code under the main call tree and code under the interrupt
tree. PRO compilers will have as many duplicates of these routines as there are interrupt
levels.
The call graph shows that the functions: main, byteconv, srv, convert, isr and
i1ldiv are all consuming APB memory that does not fully overlap with that of other
functions. Reducing the auto/parameter memory requirements for these functions will
reduce the program’s memory requirements. The call graph reveals that 82 bytes of
memory are required by the program for autos and parameters, but that only 58 are re-
served and used by the program. The difference shows the amount of memory saved by
overlapping of these blocks by the linker.
164
Linker and Utilities Map Files
Under this on the far left is a list of object files. These object files include both files generated from
source modules and those that were extracted from object library files. In the case of those from
library files, the name of the library file is printed before the object file list.
This section shows all the psects (under the Name column) that were linked into the program
from each object file, and information regarding that psect. This only deals with object files linked
by the linker. P-code modules derived from p-code library files are handled by the code generator,
and do not appear in the map file.
The Link address indicates the address at which this psect will be located when the program
is running. (The Load address is also shown for those psects that may reside in the HEX file at
a different location and which are mapped before program execution.) The Length of the psect is
shown (in units suitable for that psect). The Selector is less commonly used, but the Space field is
important as it indicates the memory space in which the psect was placed. For Harvard architecture
machines, with separate memory spaces, this field must be used in conjunction with the address to
specify an exact storage location. The Scale of a psect indicates the number of address units per byte
— this is left blank if the scale is 1 — and typically this will show 8 for psects that hold bit objects.
The Load address of psects that hold bits is used to display the link address converted into units of
bytes, rather than the load address.
T UT•RIAL
This indicates that one of the files that the linker processed was called ext.obj. (This
may have been derived from ext.c or ext.as.) This object file contained a text psect,
as well as psects called bss and rbit. The psect text was linked at address 3A and
bss at address 4B. At first glance, this seems to be a problem given that text is 22 words
long, however note that they are in different memory areas, as indicated by the Space
flag (0 for text and 1 for bss), and so do not occupy the same memory. The psect
165
Map Files Linker and Utilities
rbit contains bit objects, as indicated by its Scale value (its name is a bit of a giveaway
too). Again, at first glance there seems there could be an issue with rbit linked over
the top of bss. Their Space flags are the same, but since rbit contains bit objects, all
the addresses shown are bit addresses, as indicated by the Scale value of 8. Note that
the Load address field of rbit psect displays the Link address converted to byte units,
i.e. 50h/8 => Ah.
The list of files, that make up the program, indicated in this section of the map file will typically
consist of one or more object files derived from input source code. The map file produced by PRO
compilers will show one object file derived from all C source modules, however Standard version
compilers will show one object file per C source module.
In addition, there will typically be the runtime startup module. The runtime startup code is
precompiled into an object file, in the case of Standard version compilers, or is a compiler-written
assembler source file, which is then compiled along with the remainder of the program. In either
case, an object file module will be listed in this section, along with those psects which it defines.
If the startup module is not being deleted after compilation (see the --RUNTIME option in Section
2.6.48) then the module name will be startup.obj, otherwise this module will have a system-
dependent temporary file name, stored in a system-dependent location.
Modules derived from library files area also shown in this list. The name of the library file is
printed as a header, followed by a list of the modules that contributed to the output. Only mod-
ules that define symbols that are referenced are included in the program output. For example, the
following:
indicates that both the i1aldiv.obj and aldiv.obj modules were linked in from the library file
pic86l-c.lib.
Underneath the library file contributions, there may be a label COMMON. This shows the con-
tribution to the program from program-wide psects, in particular that used by the compiled stack
auto/parameter area.
This information in this section of the map file can be used to observe several details;
• To confirm that a module is making a contribution to the output file by ensuring that the
module appears in the module list;
166
Linker and Utilities Map Files
• For cases where a user-defined routine, with the same name as a library routine, is present in
the programs source file list, to confirm that the user-defined routine was linked in preference
to the library routine.
The next section in the map file is the same psect information listed by module, but this time grouped
into the psects’ class.
This section is heralded by the line that contains the headings:
Under this are the class names followed by those psects which belong to this class. These psects are
the same as those listed by module in the above section; there is no new information contained in
this section.
The class listing in the map file is followed by a listing of segments. A segment is conceptual
grouping of contiguous psects, and are used by the linker as an aid in psect placement. There is no
segment assembler directive and segments cannot be controlled in any way.
This section is heralded by the line that contains the headings:
The name of a segment is derived from the psect in the contiguous group with the lowest link address.
This can lead to confusion with the psect with the same name. Do not read psect information from
this section of the map file.
Typically this section of the map file can be ignored by the user.
The last of the memory summaries Just before the symbol table in the map file is a list of memory
which was not allocated by the linker. This memory is thus unused. The linker is aware of any
memory allocated by the code generator (for absolute variables), and so this free space is accurate.
This section follows the heading:
167
Map Files Linker and Utilities
and is followed by a list of classes and the memory still available in each class defined in the program.
If there is more than one range in a class, each range is printed on a separate line. Any paging
boundaries within a class are ignored and not displayed in any way.
Note that classes often define memory that is also covered by other classes, thus the total free
space in a memory area is not simply the addition of the size of all the ranges indicated. For example
if there are two classes the cover the RAM memory — RAM and BANKRAM — and the first 100h
out of 500h bytes are used, then both will indicate 000100-0004FF as the unused memory.
Symbol Table
and is followed by two columns in which the symbols are alphabetically listed. As always with the
linker, any C derived symbol is shown with its assembler equivalent symbol name. The symbols
listed in this table are:
Assembly symbols are made global via the GLOBAL assembler directive, see Section 4.3.8.1 for more
information. linker-defined symbols act like EQU directives, however they are defined by the linker
during the link process, and no definition for them will appear in any source or intermediate file.
Non-static C functions, and non-auto and non-static C variables directly map to assembly
labels. The name of the label will be the C identifier with a leading underscore character. The linker-
defined symbols include symbols used to mark the bounds of psects. See Section ??. The symbols
used to mark the base address of each functions’ auto and parameter block are also shown. Although
these symbols are used to represent the local autos and parameters of a function, they themselves
must be globally accessible to allow each calling function to load their contents. The C auto and
parameter variable identifiers are local symbols that only have scope in the function in which they
are defined.
Each symbol is shown with the psect in which they are placed, and the address which the symbol
has been assigned. There is no information encoded into a symbol to indicate whether it represents
code or variables, nor in which memory space it resides.
If the psect of a symbol is shown as (abs), this implies that the symbol is not directly associated
with a psect as is the case with absolute C variables. Linker-defined symbols showing this as the
168
Linker and Utilities Librarian
psect name may be symbols that have never been used throughout the program, or relate to symbols
that are not directly associated with a psect.
Note that a symbol table is also shown in each assembler list file. (See Section 2.6.17 for in-
formation on generating these files.) These differ to that shown in the map file in that they list
all symbols, whether they be of global or local scope, and they only list the symbols used in the
module(s) associated with that list file.
5.11 Librarian
The librarian program, LIBR, has the function of combining several object files into a single file
known as a library. The purposes of combining several such object modules are several.
In order to make the library concept useful, it is necessary for the linker to treat modules in a library
differently from object files. If an object file is specified to the linker, it will be linked into the final
linked module. A module in a library, however, will only be linked in if it defines one or more
symbols previously known, but not defined, to the linker. Thus modules in a library will be linked
only if required. Since the choice of modules to link is made on the first pass of the linker, and
the library is searched in a linear fashion, it is possible to order the modules in a library to produce
special effects when linking. More will be said about this later.
169
Librarian Linker and Utilities
Interpreting this, LIBR is the name of the program, options is zero or more librarian options which
affect the output of the program. k is a key letter denoting the function requested of the librarian
(replacing, extracting or deleting modules, listing modules or symbols), file.lib is the name of
the library file to be operated on, and file.obj is zero or more object file names.
The librarian options are listed in Table 5.2.
The key letters are listed in Table 5.3.
When replacing or extracting modules, the file.obj arguments are the names of the modules
to be replaced or extracted. If no such arguments are supplied, all the modules in the library will be
replaced or extracted respectively. Adding a file to a library is performed by requesting the librarian
to replace it in the library. Since it is not present, the module will be appended to the library. If the
r key is used and the library does not exist, it will be created.
Under the d key letter, the named object files will be deleted from the library. In this instance, it
is an error not to give any object file names.
The m and s key letters will list the named modules and, in the case of the s keyletter, the symbols
defined or referenced within (global symbols only are handled by the librarian). As with the r and x
key letters, an empty list of modules means all the modules in the library.
The o key takes a list of module names and re-orders the matching modules in the library file so
they have the same order as that listed on the command line. Modules which are not listed are left
in their existing order, and will appear after the re-ordered modules.
170
Linker and Utilities Librarian
5.11.3 Examples
Here are some examples of usage of the librarian. The following lists the global symbols in the
modules a.obj, b.obj and c.obj:
LIBR s file.lib a.obj b.obj c.obj
This command deletes the object modules a.obj, b.obj and c.obj from the library file.lib:
LIBR d file.lib a.obj b.obj c.obj
171
Objtohex Linker and Utilities
5.12 Objtohex
The HI-TECH linker is capable of producing simple binary files, or object files as output. Any other
format required must be produced by running the utility program OBJTOHEX. This allows conversion
of object files as produced by the linker into a variety of different formats, including various hex
formats. The program is invoked thus:
All of the arguments are optional. If outputfile is omitted it defaults to l.hex or l.bin depend-
ing on whether the -b option is used. The inputfile defaults to l.obj.
The options for OBJTOHEX are listed in Table 5.4. Where an address is required, the format is the
same as for HLINK.
All of addr1, addr2, where1, where2 and offset are hex numbers, without the usual H suffix.
Such a specification says that the bytes at addr1 through to addr2 inclusive should be summed
172
Linker and Utilities Objtohex
173
Cref Linker and Utilities
and the sum placed in the locations where1 through where2 inclusive. For an 8 bit checksum
these two addresses should be the same. For a checksum stored low byte first, where1 should be less
than where2, and vice versa. The +offset is optional, but if supplied, the value offset will be used
to initialise the checksum. Otherwise it is initialised to zero. For example:
This will sum the bytes in 5 through 1FFFH inclusive, then add 1FFFH to the sum. The 16 bit
checksum will be placed in locations 3 and 4, low byte in 3. The checksum is initialised with 1FFFH
to provide protection against an all zero ROM, or a ROM misplaced in memory. A run time check of
this checksum would add the last address of the ROM being checksummed into the checksum. For
the ROM in question, this should be 1FFFH. The initialization value may, however, be used in any
desired fashion.
5.13 Cref
The cross reference list utility CREF is used to format raw cross-reference information produced by
the compiler or the assembler into a sorted listing. A raw cross-reference file is produced with the
--CR option to the compiler. The assembler will generate a raw cross-reference file with a -C option
(most assemblers) or by using an OPT CRE directive (6800 series assemblers) or a XREF control line
(PIC assembler). The general form of the CREF command is:
where options is zero or more options as described below and files is one or more raw cross-
reference files. CREF takes the options listed in Table 5.5.
Each option is described in more detail in the following paragraphs.
5.13.1 -Fprefix
It is often desired to exclude from the cross-reference listing any symbols defined in a system header
file, e.g. <stdio.h>. The -F option allows specification of a path name prefix that will be used to
exclude any symbols defined in a file whose path name begins with that prefix. For example, -F\
will exclude any symbols from all files with a path name starting with \.
5.13.2 -Hheading
The -H option takes a string as an argument which will be used as a header in the listing. The default
heading is the name of the first raw cross-ref information file specified.
174
Linker and Utilities Cref
5.13.3 -Llen
Specify the length of the paper on which the listing is to be produced, e.g. if the listing is to be
printed on 55 line paper you would use a -L55 option. The default is 66 lines.
5.13.4 -Ooutfile
Allows specification of the output file name. By default the listing will be written to the standard
output and may be redirected in the usual manner. Alternatively outfile may be specified as the
output file name.
5.13.5 -Pwidth
This option allows the specification of the width to which the listing is to be formatted, e.g. -P132
will format the listing for a 132 column printer. The default is 80 columns.
5.13.6 -Sstoplist
The -S option should have as its argument the name of a file containing a list of symbols not to be
listed in the cross-reference. Multiple stoplists may be supplied with multiple -S options.
5.13.7 -Xprefix
The -X option allows the exclusion of symbols from the listing, based on a prefix given as argument
to -X. For example if it was desired to exclude all symbols starting with the character sequence xyz
then the option -Xxyz would be used. If a digit appears in the character sequence then this will match
175
Cromwell Linker and Utilities
any digit in the symbol, e.g. -XX0 would exclude any symbols starting with the letter X followed by
a digit.
CREF will accept wildcard filenames and I/O redirection. Long command lines may be supplied
by invoking CREF with no arguments and typing the command line in response to the cref> prompt.
A backslash at the end of the line will be interpreted to mean that more command lines follow.
5.14 Cromwell
The CROMWELL utility converts code and symbol files into different formats. The formats available
are shown in Table 5.6.
The general form of the CROMWELL command is:
where options can be any of the options shown in Table 5.7. Output_file (optional) is the
name of the output file. The input_files are typically the HEX and SYM file. CROMWELL
automatically searches for the SDB files and reads those if they are found. The options are further
described in the following paragraphs.
5.14.1 -Pname[,architecture]
The -P options takes a string which is the name of the processor used. CROMWELL may use this in the
generation of the output format selected. Note that to produce output in COFF format an additional
176
Linker and Utilities Cromwell
argument to this option which also specifies the processor architecture is required. Hence for this
format the usage of this option must take the form: -Pname,architecture. Table 5.8 enumerates
the architectures supported for producing COFF files.
5.14.2 -N
To produce some output file formats (e.g. COFF), Cromwell requires that the names of the program
memory space psect classes be provided. The names of the classes are given as a comma separated
list. For example, in the DSPIC C compiler these classes are typically “CODE” and “NEARCODE”,
i.e. -NCODE,NEARCODE.
5.14.3 -D
The -D option is used to display to the screen details about the named input file in a readable format.
The input file can be one of the file types as shown in Table 5.6.
5.14.4 -C
This option will attempt to identify if the specified input files are one of the formats as shown in
Table 5.6. If the file is recognised, a confirmation of its type will be displayed.
177
Cromwell Linker and Utilities
5.14.5 -F
When generating a COD file, this option can be used to force all local symbols to be represented as
global symbols. The may be useful where an emulator cannot read local symbol information from
the COD file.
5.14.6 -Okey
This option specifies the format of the output file. The key can be any of the types listed in Table
5.6.
5.14.7 -Ikey
This option can be used to specify the default input file format. The key can be any of the types
listed in Table 5.6.
5.14.8 -L
Use this option to show what file format types are supported. A list similar to that given in Table 5.6
will be shown.
5.14.9 -E
Use this option to tell CROMWELL to ignore any filename extensions that were given. The default
extension will be used instead.
178
Linker and Utilities Hexmate
5.14.10 -B
In formats that support different endian types, use this option to specify big-endian byte ordering.
5.14.11 -M
When generating COD files this option will remove the preceding underscore character from sym-
bols.
5.14.12 -V
Turns on verbose mode which will display information about operations CROMWELL is performing.
5.15 Hexmate
The Hexmate utility is a program designed to manipulate Intel HEX files. Hexmate is a post-link
stage utility that provides the facility to:
• Calculating a checksum over a range of program memory and storing its value in program
memory or EEPROM
179
Hexmate Linker and Utilities
• Filling unused memory locations with an instruction to send the PC to a known location if it
gets lost.
• Storage of a serial number at a fixed address.
• Storage of a string (e.g. time stamp) at a fixed address.
• Store initial values at a particular memory address (e.g. initialise EEPROM)
• Detecting usage of a buggy/restricted instruction
• Adjusting hex file to meet requirements of particular bootloaders
5.15.1.1 specifications,filename.hex
Intel hex files that can be processed by hexmate should be in either INHX32 or INHX8M format.
Additional specifications can be applied to each hex file to put restrictions or conditions on how this
file should be processed. If any specifications are used they must precede the filename. The list of
specifications will then be separated from the filename by a comma.
A range restriction can be applied with the specification rStart-End. A range restriction will
cause only the address data falling within this range to be used. For example:
r100-1FF,myfile.hex
will use myfile.hex as input, but only process data which is addressed within the range 100h-1FFh
(inclusive) to be read from myfile.hex.
An address shift can be applied with the specification sOffset . If an address shift is used, data
read from this hex file will be shifted (by the Offset) to a new address when generating the output.
The offset can be either positive or negative. For example:
180
Linker and Utilities Hexmate
181
Hexmate Linker and Utilities
r100-1FFs2000,myfile.hex
will shift the block of data from 100h-1FFh to the new address range 2100h-21FFh.
Be careful when shifting sections of executable code. Program code shouldn’t be shifted unless it
can be guaranteed that no part of the program relies upon the absolute location of this code segment.
5.15.1.2 + Prefix
When the + operator precedes a parameter or input file, the data obtained from that parameter will
be forced into the output file and will overwrite other data existing within its address range. For
example:
Ordinarily, hexmate will issue an error if two sources try to store differing data at the same location.
Using the + operator informs hexmate that if more than one data source tries to store data to the same
address, the one specified with a ’+’ will take priority.
5.15.1.3 -ADDRESSING
By default, all address parameters in hexmate options expect that values will be entered as byte
addresses. In some device architectures the native addressing format may be something other than
byte addressing. In these cases it would be much simpler to be able to enter address-components
in the device’s native format. To facilitate this, the -ADDRESSING option is used. This option takes
exactly one parameter which configures the number of bytes contained per address location. If for
example a device’s program memory naturally used a 16-bit (2 byte) word-addressing format, the
option -ADDRESSING=2 will configure hexmate to interpret all command line address fields as word
addresses. The affect of this setting is global and all hexmate options will now interpret addresses
according to this setting. This option will allow specification of addressing modes from one byte-
per-address to four bytes-per-address.
5.15.1.4 -BREAK
This option takes a comma separated list of addresses. If any of these addresses are encountered
in the hex file, the current data record will conclude and a new data record will recommence from
the nominated address. This can be useful to use new data records to force a distinction between
functionally different areas of program space. Some hex file readers depend on this.
182
Linker and Utilities Hexmate
5.15.1.5 -CK
The -CK option is for calculating a checksum. The usage of this option is:
-CK=start-end@destination[+offset][wWidth][tCode][gAlogithm]
where:
• Start and End specify the address range that the checksum will be calculated over.
• Destination is the address where to store the checksum result. This value cannot be within the
range of calculation.
• Offset is an optional initial value to add to the checksum result. Width is optional and specifies
the byte-width of the checksum result. Results can be calculated for byte-widths of 1 to 4
bytes. If a positive width is requested, the result will be stored in big-endian byte order. A
negative width will cause the result to be stored in little-endian byte order. If the width is left
unspecified, the result will be 2 bytes wide and stored in little-endian byte order.
• Code is a hexadecimal code that will trail each byte in the checksum result. This can allow
each byte of the checksum result to be embedded within an instruction.
• Algorithm is an integer to select which hexmate algorithm to use to calculate the checksum
result. A list of selectable algorithms are given in Table 5.10. If unspecified, the default
checksum algorithm used is 8 bit addition.
-CK=0-1FFF@2FFE+2100w2
This will calculate a checksum over the range 0-1FFFh and program the checksum result at address
2FFEh, checksum value will apply an initial offset of 2100h. The result will be two bytes wide.
5.15.1.6 -FILL
The -FILL option is used for filling unused memory locations with a known value. The usage of this
option is:
-FILL=Code@Start-End[,data]
where:
• Code is the opcode that will be programmed to unused locations in memory. Multi-byte codes
should be entered in little endian order.
183
Hexmate Linker and Utilities
• Start and End specify the address range that this fill will apply to.
For example:
-FILL=3412@0-1FFF,data
will program opcode 1234h in all unused addresses from program memory address 0 to 1FFFh (Note
the endianism). -FILL accepts whole bytes of hexadecimal data from 1 to 8 bytes in length.
Adding the ,data flag to this option is not required. If the data flag has been specified, hexmate
will only perform ROM filling to records that actually contain data. This means that these records
will be padded out to the default data record length or the width specified in the -FORMAT option.
Records will also begin on addresses which are multiples of the data record length used. The default
data record length is 16 bytes. This facility is particularly useful or is a requirement for some
bootloaders that expect that all data records will be of a particular length and address alignment.
5.15.1.7 -FIND
This option is used to detect and log occurrences of an opcode or partial code sequence. The usage
of this option is:
-FIND=Findcode[mMask]@Start-End[/Align][w][t”Title”]
where:
• Findcode is the hexadecimal code sequence to search for and is entered in little endian byte
order.
184
Linker and Utilities Hexmate
• Mask is optional. It allows a bit mask over the Findcode value and is entered in little endian
byte order.
• Start and End limit the address range to search through.
• Align is optional. It specifies that a code sequence can only match if it begins on an address
which is a multiple of this value. w, if present will cause hexmate to issue a warning whenever
the code sequence is detected.
• Title is optional. It allows a title to be given to this code sequence. Defining a title will make
log-reports and messages more descriptive and more readable. A title will not affect the actual
search results.
T UT•RIAL
Let’s look at some examples. The option -FIND=3412@0-7FFF/2w will detect the code
sequence 1234h when aligned on a 2 (two) byte address boundary, between 0h and
7FFFh. w indicates that a warning will be issued each time this sequence is found.
Another example, -FIND=3412M0F00@0-7FFF/2wt"ADDXY" is same as last example
but the code sequence being matched is masked with 000Fh, so hexmate will search for
123xh. If a byte-mask is used, is must be of equal byte-width to the opcode it is applied
to. Any messaging or reports generated by hexmate will refer to this opcode by the
name, ADDXY as this was the title defined for this search.
If hexmate is generating a log file, it will contain the results of all searches. -FIND accepts whole
bytes of hex data from 1 to 8 bytes in length. Optionally, -FIND can be used in conjunction with
,REPLACE or ,DELETE (as described below).
5.15.1.8 -FIND...,DELETE
If DELETE is used in conjunction with a -FIND option and a sequence is found that matches the
-FIND criteria, it will be removed. This function should be used with extreme caution and is not
recommended for removal of executable code.
5.15.1.9 -FIND...,REPLACE
REPLACE Can only be used in conjunction with a -FIND option. Code sequences that matched the
-FIND criteria can be replaced or partially replaced with new codes. The usage for this sub-option
is:
-FIND...,REPLACE=Code[mMask]
185
Hexmate Linker and Utilities
where:
• Code is a little endian hexadecimal code to replace the sequences that match the -FIND crite-
ria.
• Mask is an optional bit mask to specify which bits within Code will replace the code sequence
that has been matched. This may be useful if, for example, it is only necessary to modify 4
bits within a 16-bit instruction. The remaining 12 bits can masked and be left unchanged.
5.15.1.10 -FORMAT
The -FORMAT option can be used to specify a particular variant of INHX format or adjust maximum
record length. The usage of this option is:
-FORMAT=Type[,Length]
where:
T UT•RIAL
Consider this case. A bootloader trying to download an INHX32 file fails succeed
because it cannot process the extended address records which are part of the INHX32
standard. You know that this bootloader can only program data addressed within the
range 0 to 64k, and that any data in the hex file outside of this range can be safely
disregarded. In this case, by generating the hex file in INHX8M format the operation
might succeed. The hexmate option to do this would be -FORMAT=INHX8M.
Now consider this. What if the same bootloader also required every data record to
contain eight bytes of data, no more, no less? This is possible by combining -FORMAT
with -FILL. Appropriate use of -FILL can ensure that there are no gaps in the data
for the address range being programmed. This will satisfy the minimum data length
requirement. To set the maximum length of data records to eight bytes, just modify the
previous option to become -FORMAT=INHX8M,8.
The possible types that are supported by this option are listed in Table 5.11. Note that INHX032 is
not an actual INHX format. Selection of this type generates an INHX32 file but will also initialize
the upper address information to zero. This is a requirement of some device programmers.
186
Linker and Utilities Hexmate
5.15.1.11 -HELP
Using -HELP will list all hexmate options. By entering another hexmate option as a parameter of
-HELP will show a detailed help message for the given option. For example:
-HELP=string
will show additional help for the -STRING hexmate option.
5.15.1.12 -LOGFILE
The -LOGFILE option saves hex file statistics to the named file. For example:
-LOGFILE=output.log
will analyse the hex file that hexmate is generating and save a report to a file named output.log.
5.15.1.13 -MASK
Use this option to logically AND a memory range with a particular bitmask. This is used to ensure
that the unimplemented bits in program words (if any) are left blank. The usage of this option is as
follows:
-MASK=hexcode@start-end
Where hexcode is a hexadecimal value that will be ANDed with data within the start-end
address range. Multibyte mask values can be entered in little endian byte order.
5.15.1.14 -Ofile
The generated Intel hex output will be created in this file. For example:
-Oprogram.hex
will save the resultant output to program.hex. The output file can take the same name as one of its
input files, but by doing so, it will replace the input file entirely.
187
Hexmate Linker and Utilities
5.15.1.15 -SERIAL
This option will store a particular hex value at a fixed address. The usage of this option is:
-SERIAL=Code[+/-Increment]@Address[+/-Interval][rRepetitions]
where:
• Code is a hexadecimal value to store and is entered in little endian byte order.
• Increment is optional and allows the value of Code to change by this value with each repetition
(if requested).
• Address is the location to store this code, or the first repetition thereof.
• Interval is optional and specifies the address shift per repetition of this code.
• Repetitions is optional and specifies the number of times to repeat this code.
For example:
-SERIAL=000001@EFFE
-SERIAL=0000+2@1000+10r5
will store 5 codes, beginning with value 0000 at address 1000h. Subsequent codes will appear at
address intervals of +10h and the code value will change in increments of +2h.
5.15.1.16 -SIZE
Using the -SIZE option will report the number of bytes of data within the resultant hex image to
standard output. The size will also be recorded in the log file if one has been requested.
5.15.1.17 -STRING
The -STRING option will embed an ASCII string at a fixed address. The usage of this option is:
-STRING@Address[tCode]=”Text”
where:
188
Linker and Utilities Hexmate
For example:
will store the ASCII data for the string, My favourite string (including null terminator) at ad-
dress 1000h.
Another example:
will store the same string with every byte in the string being trailed with the hex code 34h.
5.15.1.18 -STRPACK
This option performs the same function as -STRING but with two important differences. Firstly, only
the lower seven bits from each character are stored. Pairs of 7 bit characters are then concatenated
and stored as a 14 bit word rather than in separate bytes. This is usually only useful for devices where
program space is addressed as 14 bit words. The second difference is that -STRING’s t specifier is
not applicable with -STRPACK.
189
Hexmate Linker and Utilities
190
Appendix A
Library Functions
The functions within the standard compiler library are listed in this chapter. Each entry begins with
the name of the function. This is followed by information decomposed into the following categories.
Synopsis the C declaration of the function, and the header file in which it is declared.
Example an example of the use of the function. It is usually a complete small program that illus-
trates the function.
Data types any special data types (structures etc.) defined for use with the function. These data
types will be defined in the header file named under Synopsis.
Return value the type and nature of the return value of the function, if any. Information on error
returns is also included
Only those categories which are relevant to each function are used.
191
Library Functions
ABS
Synopsis
#include <stdlib.h>
Description
The abs() function returns the absolute value of j.
Example
#include <stdio.h>
#include <stdlib.h>
void
main (void)
{
int a = -5;
See Also
labs(), fabs()
Return Value
The absolute value of j.
192
Library Functions
ACOS
Synopsis
#include <math.h>
Description
The acos() function implements the inverse of cos(), i.e. it is passed a value in the range -1 to +1,
and returns an angle in radians whose cosine is equal to that value.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
float i, a;
See Also
sin(), cos(), tan(), asin(), atan(), atan2()
Return Value
An angle in radians, in the range 0 to π
193
Library Functions
ASCTIME
Synopsis
#include <time.h>
Description
The asctime() function takes the time broken down into the struct tm structure, pointed to by its
argument, and returns a 26 character string describing the current date and time in the format:
Sun Sep 16 01:03:52 1973\n\0
Note the newline at the end of the string. The width of each field in the string is fixed. The
example gets the current time, converts it to a struct tm pointer with localtime(), it then converts
this to ASCII and prints it. The time() function will need to be provided by the user (see time() for
details).
Example
#include <stdio.h>
#include <time.h>
void
main (void)
{
time_t clock;
struct tm * tp;
time(&clock);
tp = localtime(&clock);
printf("%s", asctime(tp));
}
See Also
194
Library Functions
Return Value
A pointer to the string.
Note
The example will require the user to provide the time() routine as it cannot be supplied with the
compiler.. See time() for more details.
195
Library Functions
ASIN
Synopsis
#include <math.h>
Description
The asin() function implements the converse of sin(), i.e. it is passed a value in the range -1 to +1,
and returns an angle in radians whose sine is equal to that value.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
float i, a;
See Also
sin(), cos(), tan(), acos(), atan(), atan2()
Return Value
An angle in radians, in the range - π
196
Library Functions
ASSERT
Synopsis
#include <assert.h>
Description
This macro is used for debugging purposes; the basic method of usage is to place assertions liberally
throughout your code at points where correct operation of the code depends upon certain conditions
being true initially. An assert() routine may be used to ensure at run time that an assumption holds
true. For example, the following statement asserts that the pointer tp is not equal to NULL:
assert(tp);
If at run time the expression evaluates to false, the program will abort with a message identifying
the source file and line number of the assertion, and the expression used as an argument to it. A fuller
discussion of the uses of assert() is impossible in limited space, but it is closely linked to methods
of proving program correctness.
Example
void
ptrfunc (struct xyz * tp)
{
assert(tp != 0);
}
Note
When required for ROM based systems, the underlying routine _fassert(...) will need to be imple-
mented by the user.
197
Library Functions
ATAN
Synopsis
#include <math.h>
Description
This function returns the arc tangent of its argument, i.e. it returns an angle e in the range - π
Example
#include <stdio.h>
#include <math.h>
void
main (void)
{
printf("%f\n", atan(1.5));
}
See Also
sin(), cos(), tan(), asin(), acos(), atan2()
Return Value
The arc tangent of its argument.
198
Library Functions
ATAN2
Synopsis
#include <math.h>
Description
This function returns the arc tangent of y/x.
Example
#include <stdio.h>
#include <math.h>
void
main (void)
{
printf("%f\n", atan2(10.0, -10.0));
}
See Also
sin(), cos(), tan(), asin(), acos(), atan()
Return Value
The arc tangent of y/x.
199
Library Functions
ATOF
Synopsis
#include <stdlib.h>
Description
The atof() function scans the character string passed to it, skipping leading blanks. It then converts
an ASCII representation of a number to a double. The number may be in decimal, normal floating
point or scientific notation.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
char buf[80];
double i;
gets(buf);
i = atof(buf);
printf("Read %s: converted to %f\n", buf, i);
}
See Also
atoi(), atol(), strtod()
Return Value
A double precision floating point number. If no number is found in the string, 0.0 will be returned.
200
Library Functions
ATOI
Synopsis
#include <stdlib.h>
Description
The atoi() function scans the character string passed to it, skipping leading blanks and reading an
optional sign. It then converts an ASCII representation of a decimal number to an integer.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
char buf[80];
int i;
gets(buf);
i = atoi(buf);
printf("Read %s: converted to %d\n", buf, i);
}
See Also
xtoi(), atof(), atol()
Return Value
A signed integer. If no number is found in the string, 0 will be returned.
201
Library Functions
ATOL
Synopsis
#include <stdlib.h>
Description
The atol() function scans the character string passed to it, skipping leading blanks. It then converts
an ASCII representation of a decimal number to a long integer.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
char buf[80];
long i;
gets(buf);
i = atol(buf);
printf("Read %s: converted to %ld\n", buf, i);
}
See Also
atoi(), atof()
Return Value
A long integer. If no number is found in the string, 0 will be returned.
202
Library Functions
BSEARCH
Synopsis
#include <stdlib.h>
Description
The bsearch() function searches a sorted array for an element matching a particular key. It uses a
binary search algorithm, calling the function pointed to by compar to compare elements in the array.
Example
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct value {
char name[40];
int value;
} values[100];
int
val_cmp (const void * p1, const void * p2)
{
return strcmp(((const struct value *)p1)->name,
((const struct value *)p2)->name);
}
void
main (void)
{
char inbuf[80];
int i;
struct value * vp;
203
Library Functions
i = 0;
while(gets(inbuf)) {
sscanf(inbuf,"%s %d", values[i].name, &values[i].value);
i++;
}
qsort(values, i, sizeof values[0], val_cmp);
vp = bsearch("fred", values, i, sizeof values[0], val_cmp);
if(!vp)
printf("Item ’fred’ was not found\n");
else
printf("Item ’fred’ has value %d\n", vp->value);
}
See Also
qsort()
Return Value
A pointer to the matched array element (if there is more than one matching element, any of these
may be returned). If no match is found, a null pointer is returned.
Note
The comparison function must have the correct prototype.
204
Library Functions
CEIL
Synopsis
#include <math.h>
Description
This routine returns the smallest whole number not less than f.
Example
#include <stdio.h>
#include <math.h>
void
main (void)
{
double j;
scanf("%lf", &j);
printf("The ceiling of %lf is %lf\n", j, ceil(j));
}
205
Library Functions
CGETS
Synopsis
#include <conio.h>
Description
The cgets() function will read one line of input from the console into the buffer passed as an ar-
gument. It does so by repeated calls to getche(). As characters are read, they are buffered, with
backspace deleting the previously typed character, and ctrl-U deleting the entire line typed so far.
Other characters are placed in the buffer, with a carriage return or line feed (newline) terminating
the function. The collected string is null terminated.
Example
#include <conio.h>
#include <string.h>
char buffer[80];
void
main (void)
{
for(;;) {
cgets(buffer);
if(strcmp(buffer, "exit") == 0)
break;
cputs("Type ’exit’ to finish\n");
}
}
See Also
206
Library Functions
Return Value
The return value is the character pointer passed as the sole argument.
207
Library Functions
COS
Synopsis
#include <math.h>
Description
This function yields the cosine of its argument, which is an angle in radians. The cosine is calculated
by expansion of a polynomial series approximation.
Example
#include <math.h>
#include <stdio.h>
#define C 3.141592/180.0
void
main (void)
{
double i;
See Also
sin(), tan(), asin(), acos(), atan(), atan2()
Return Value
A double in the range -1 to +1.
208
Library Functions
#include <math.h>
Description
These functions are the implement hyperbolic equivalents of the trigonometric functions; cos(), sin()
and tan().
Example
#include <stdio.h>
#include <math.h>
void
main (void)
{
printf("%f\n", cosh(1.5));
printf("%f\n", sinh(1.5));
printf("%f\n", tanh(1.5));
}
Return Value
The function cosh() returns the hyperbolic cosine value.
The function sinh() returns the hyperbolic sine value.
The function tanh() returns the hyperbolic tangent value.
209
Library Functions
CPUTS
Synopsis
#include <conio.h>
Description
The cputs() function writes its argument string to the console, outputting carriage returns before
each newline in the string. It calls putch() repeatedly. On a hosted system cputs() differs from puts()
in that it writes to the console directly, rather than using file I/O. In an embedded system cputs() and
puts() are equivalent.
Example
#include <conio.h>
#include <string.h>
char buffer[80];
void
main (void)
{
for(;;) {
cgets(buffer);
if(strcmp(buffer, "exit") == 0)
break;
cputs("Type ’exit’ to finish\n");
}
}
See Also
cputs(), puts(), putch()
210
Library Functions
CTIME
Synopsis
#include <time.h>
Description
The ctime() function converts the time in seconds pointed to by its argument to a string of the same
form as described for asctime(). Thus the example program prints the current time and date.
Example
#include <stdio.h>
#include <time.h>
void
main (void)
{
time_t clock;
time(&clock);
printf("%s", ctime(&clock));
}
See Also
gmtime(), localtime(), asctime(), time()
Return Value
A pointer to the string.
Note
The example will require the user to provide the time() routine as one cannot be supplied with the
compiler. See time() for more detail.
211
Library Functions
DIV
Synopsis
#include <stdlib.h>
Description
The div() function computes the quotient and remainder of the numerator divided by the denomina-
tor.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
div_t x;
x = div(12345, 66);
printf("quotient = %d, remainder = %d\n", x.quot, x.rem);
}
See Also
udiv(), ldiv(), uldiv()
Return Value
Returns the quotient and remainder into the div_t structure.
212
Library Functions
EVAL_POLY
Synopsis
#include <math.h>
Description
The eval_poly() function evaluates a polynomial, whose coefficients are contained in the array d, at
x, for example:
Example
#include <stdio.h>
#include <math.h>
void
main (void)
{
double x, y;
double d[3] = {1.1, 3.5, 2.7};
x = 2.2;
y = eval_poly(x, d, 2);
printf("The polynomial evaluated at %f is %f\n", x, y);
}
Return Value
A double value, being the polynomial evaluated at x.
213
Library Functions
EXIT
Synopsis
#include <stdlib.h>
Description
This contains an endless loop which will resut in the function never returning and the program to
mark time. The status is not checked.
Example
#include <stdlib.h>
void
main (void)
{
/* my work is done */
exit(0);
}
Return Value
Never returns.
214
Library Functions
EXP
Synopsis
#include <math.h>
Description
The exp() routine returns the exponential function of its argument, i.e. e to the power of f.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
double f;
See Also
log(), log10(), pow()
215
Library Functions
FABS
Synopsis
#include <math.h>
Description
This routine returns the absolute value of its double argument.
Example
#include <stdio.h>
#include <math.h>
void
main (void)
{
printf("%f %f\n", fabs(1.5), fabs(-1.5));
}
See Also
abs(), labs()
216
Library Functions
FLASH_READBLOCK
Synopsis
#include <psoc.h>
bit flash_readBlock(void * dst, unsigned int blockno)
Description
This function uses the system ROM SSC function to read data from the flash memory. The first
parameter is a pointer to a block of RAM memory to be filled in with the data read from flash. Each
block occupies 64 bytes. The second parameter is the linear block number. This will automatically
be decomposed into a bank number and a block number within the bank, for chips that have more
than one bank of flash. The return value is true if the read succeeded.
217
Library Functions
FLASH_WRITEBLOCK
Synopsis
#include <psoc.h>
bit flash_writeBlock(const void * src, unsigned int blockno)
Description
This function uses the system ROM SSC function to write data to the flash memory. The first
parameter is a pointer to a block of data to be written. Each block occupies 64 bytes. The second
parameter is the linear block number. This will automatically be decomposed into a bank number
and a block number within the bank, for chips that have more than one bank of flash. The return
value is true if the write succeeded.
The function assumes that the CPU is running at a speed of 12MHz. The appropriate timing pa-
rameters are calculated based on this value and a default chip temperature of 16C. It is recommended
that you set the chip clock speed to 12MHz before calling the function, however you can also override
the delay timing by setting certain global variables. The unsigned char variable _flash_delay can
be pre-set to the calculated DELAY value used by the SSC routine, and the variable _flash_temp
can be set to the current chip temperature if known. Consult the PSoC Technical Reference Manual
for more information on these parameters.
218
Library Functions
FMOD
Synopsis
#include <math.h>
Description
The function fmod returns the remainder of x/y as a floating point quantity.
Example
#include <math.h>
void
main (void)
{
double rem, x;
x = 12.34;
rem = fmod(x, 2.1);
}
Return Value
The floating-point remainder of x/y.
219
Library Functions
FLOOR
Synopsis
#include <math.h>
Description
This routine returns the largest whole number not greater than f.
Example
#include <stdio.h>
#include <math.h>
void
main (void)
{
printf("%f\n", floor( 1.5 ));
printf("%f\n", floor( -1.5));
}
220
Library Functions
FREXP
Synopsis
#include <math.h>
Description
The frexp() function breaks a floating point number into a normalized fraction and an integral power
of 2. The integer is stored into the int object pointed to by p. Its return value x is in the interval (0.5,
1.0) or zero, and f equals x times 2 raised to the power stored in *p. If f is zero, both parts of the
result are zero.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
double f;
int i;
f = frexp(23456.34, &i);
printf("23456.34 = %f * 2^%d\n", f, i);
}
See Also
ldexp()
221
Library Functions
FTOA
Synopsis
#include <stdlib.h>
Description
The function ftoa converts the contents of f into a string which is stored into a buffer which is then
return.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
char * buf;
float input = 12.34;
int status;
buf = ftoa(input, &status);
printf("The buffer holds %s\n", buf);
}
See Also
strtol(), itoa(), utoa(), ultoa()
Return Value
This routine returns a reference to the buffer into which the result is written.
222
Library Functions
GETCH, GETCHE
Synopsis
#include <conio.h>
Description
The getch() function reads a single character from the console keyboard and returns it without echo-
ing. The getche() function is similar but does echo the character typed.
In an embedded system, the source of characters is defined by the particular routines supplied.
By default, the library contains a version of getch() that will interface to the Lucifer Debugger. The
user should supply an appropriate routine if another source is desired, e.g. a serial port.
The module getch.c in the SOURCES directory contains model versions of all the console I/O
routines. Other modules may also be supplied, e.g. ser180.c has routines for the serial port in a
Z180.
Example
#include <conio.h>
void
main (void)
{
char c;
See Also
cgets(), cputs(), ungetch()
223
Library Functions
GETCHAR
Synopsis
#include <stdio.h>
Description
The getchar() routine is a getc(stdin) operation. It is a macro defined in stdio.h. Note that under
normal circumstances getchar() will NOT return unless a carriage return has been typed on the
console. To get a single character immediately from the console, use the function getch().
Example
#include <stdio.h>
void
main (void)
{
int c;
See Also
getc(), fgetc(), freopen(), fclose()
Note
This routine is not usable in a ROM based system.
224
Library Functions
GETS
Synopsis
#include <stdio.h>
Description
The gets() function reads a line from standard input into the buffer at s, deleting the newline (cf.
fgets()). The buffer is null terminated. In an embedded system, gets() is equivalent to cgets(), and
results in getche() being called repeatedly to get characters. Editing (with backspace) is available.
Example
#include <stdio.h>
void
main (void)
{
char buf[80];
See Also
fgets(), freopen(), puts()
Return Value
It returns its argument, or NULL on end-of-file.
225
Library Functions
GMTIME
Synopsis
#include <time.h>
Description
This function converts the time pointed to by t which is in seconds since 00:00:00 on Jan 1, 1970,
into a broken down time stored in a structure as defined in time.h. The structure is defined in the
’Data Types’ section.
Example
#include <stdio.h>
#include <time.h>
void
main (void)
{
time_t clock;
struct tm * tp;
time(&clock);
tp = gmtime(&clock);
printf("It’s %d in London\n", tp->tm_year+1900);
}
See Also
226
Library Functions
Return Value
Returns a structure of type tm.
Note
The example will require the user to provide the time() routine as one cannot be supplied with the
compiler. See time() for more detail.
227
Library Functions
Description
These macros, defined in ctype.h, test the supplied character for membership in one of several over-
lapping groups of characters. Note that all except isascii() are defined for c, if isascii(c) is true or if
c = EOF.
228
Library Functions
Example
#include <ctype.h>
#include <stdio.h>
void
main (void)
{
char buf[80];
int i;
gets(buf);
i = 0;
while(isalnum(buf[i]))
i++;
buf[i] = 0;
printf("’%s’ is the word\n", buf);
}
See Also
toupper(), tolower(), toascii()
229
Library Functions
ISDIG
Synopsis
#include <ctype.h>
Description
The isdig() function tests the input character c to see if is a decimal digit (0 – 9) and returns true is
this is the case; false otherwise.
Example
#include <ctype.h>
void
main (void)
{
char buf[] = "1998a";
if(isdig(buf[0]))
printf("valid type detected\n");
}
See Also
isdigit() (listed un isalnum())
Return Value
Zero if the character is a decimal digit; a non-zero value otherwise.
230
Library Functions
ITOA
Synopsis
#include <stdlib.h>
Description
The function itoa converts the contents of val into a string which is stored into buf. The conversion
is performed according to the radix specified in base. buf is assumed to reference a buffer which has
sufficent space allocated to it.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
char buf[10];
itoa(buf, 1234, 16);
printf("The buffer holds %s\n", buf);
}
See Also
strtol(), utoa(), ltoa(), ultoa()
Return Value
This routine returns a copy of the buffer into which the result is written.
231
Library Functions
LABS
Synopsis
#include <stdlib.h>
Description
The labs() function returns the absolute value of long value j.
Example
#include <stdio.h>
#include <stdlib.h>
void
main (void)
{
long int a = -5;
See Also
abs()
Return Value
The absolute value of j.
232
Library Functions
LDEXP
Synopsis
#include <math.h>
Description
The ldexp() function performs the inverse of frexp() operation; the integer i is added to the exponent
of the floating point f and the resultant returned.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
double f;
f = ldexp(1.0, 10);
printf("1.0 * 2^10 = %f\n", f);
}
See Also
frexp()
Return Value
The return value is the integer i added to the exponent of the floating point value f.
233
Library Functions
LDIV
Synopsis
#include <stdlib.h>
Description
The ldiv() routine divides the numerator by the denominator, computing the quotient and the remain-
der. The sign of the quotient is the same as that of the mathematical quotient. Its absolute value is
the largest integer which is less than the absolute value of the mathematical quotient.
The ldiv() function is similar to the div() function, the difference being that the arguments and
the members of the returned structure are all of type long int.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
ldiv_t lt;
lt = ldiv(1234567, 12345);
printf("Quotient = %ld, remainder = %ld\n", lt.quot, lt.rem);
}
See Also
div(), uldiv(), udiv()
Return Value
Returns a structure of type ldiv_t
234
Library Functions
LOCALTIME
Synopsis
#include <time.h>
Description
The localtime() function converts the time pointed to by t which is in seconds since 00:00:00 on Jan
1, 1970, into a broken down time stored in a structure as defined in time.h. The routine localtime()
takes into account the contents of the global integer time_zone. This should contain the number of
minutes that the local time zone is westward of Greenwich. On systems where it is not possible to
predetermine this value, localtime() will return the same result as gmtime().
Example
#include <stdio.h>
#include <time.h>
char * wday[] = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
void
main (void)
{
time_t clock;
struct tm * tp;
time(&clock);
tp = localtime(&clock);
printf("Today is %s\n", wday[tp->tm_wday]);
}
235
Library Functions
See Also
ctime(), asctime(), time()
Return Value
Returns a structure of type tm.
Note
The example will require the user to provide the time() routine as one cannot be supplied with the
compiler. See time() for more detail.
236
Library Functions
LOG, LOG10
Synopsis
#include <math.h>
Description
The log() function returns the natural logarithm of f. The function log10() returns the logarithm to
base 10 of f.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
double f;
See Also
exp(), pow()
Return Value
Zero if the argument is negative.
237
Library Functions
LONGJMP
Synopsis
#include <setjmp.h>
Description
The longjmp() function, in conjunction with setjmp(), provides a mechanism for non-local goto’s.
To use this facility, setjmp() should be called with a jmp_buf argument in some outer level function.
The call from setjmp() will return 0.
To return to this level of execution, longjmp() may be called with the same jmp_buf argument
from an inner level of execution. Note however that the function which called setjmp() must still be
active when longjmp() is called. Breach of this rule will cause disaster, due to the use of a stack
containing invalid data. The val argument to longjmp() will be the value apparently returned from
the setjmp(). This should normally be non-zero, to distinguish it from the genuine setjmp() call.
Example
#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
jmp_buf jb;
void
inner (void)
{
longjmp(jb, 5);
}
void
main (void)
{
int i;
238
Library Functions
if(i = setjmp(jb)) {
printf("setjmp returned %d\n", i);
exit(0);
}
printf("setjmp returned 0 - good\n");
printf("calling inner...\n");
inner();
printf("inner returned - bad!\n");
}
See Also
setjmp()
Return Value
The longjmp() routine never returns.
Note
The function which called setjmp() must still be active when longjmp() is called. Breach of this rule
will cause disaster, due to the use of a stack containing invalid data.
239
Library Functions
LTOA
Synopsis
#include <stdlib.h>
Description
The function itoa converts the contents of val into a string which is stored into buf. The conversion
is performed according to the radix specified in base. buf is assumed to reference a buffer which has
sufficent space allocated to it.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
char buf[10];
utoi(buf, 12345678L, 16);
printf("The buffer holds %s\n", buf);
}
See Also
strtol(), itoa(), utoa(), ultoa()
Return Value
This routine returns a copy of the buffer into which the result is written.
240
Library Functions
MEMCHR
Synopsis
#include <string.h>
Description
The memchr() function is similar to strchr() except that instead of searching null terminated strings,
it searches a block of memory specified by length for a particular byte. Its arguments are a pointer
to the memory to be searched, the value of the byte to be searched for, and the length of the block.
A pointer to the first occurrence of that byte in the block is returned.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
char * cp;
See Also
strchr()
241
Library Functions
Return Value
A pointer to the first byte matching the argument if one exists; NULL otherwise.
242
Library Functions
MEMCMP
Synopsis
#include <string.h>
Description
The memcmp() function compares two blocks of memory, of length n, and returns a signed value
similar to strncmp(). Unlike strncmp() the comparison does not stop on a null character.
Example
#include <stdio.h>
#include <string.h>
void
main (void)
{
int buf[10], cow[10], i;
buf[0] = 1;
buf[2] = 4;
cow[0] = 1;
cow[2] = 5;
buf[1] = 3;
cow[1] = 3;
i = memcmp(buf, cow, 3*sizeof(int));
if(i < 0)
printf("less than\n");
else if(i > 0)
printf("Greater than\n");
else
printf("Equal\n");
}
243
Library Functions
See Also
strncpy(), strncmp(), strchr(), memset(), memchr()
Return Value
Returns negative one, zero or one, depending on whether s1 points to string which is less than, equal
to or greater than the string pointed to by s2 in the collating sequence.
244
Library Functions
MEMCPY
Synopsis
#include <string.h>
Description
The memcpy() function copies n bytes of memory starting from the location pointed to by s to
the block of memory pointed to by d. The result of copying overlapping blocks is undefined. The
memcpy() function differs from strcpy() in that it copies a specified number of bytes, rather than all
bytes up to a null terminator.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
char buf[80];
See Also
strncpy(), strncmp(), strchr(), memset()
Return Value
The memcpy() routine returns its first argument.
245
Library Functions
MEMSET
Synopsis
#include <string.h>
Description
The memset() function fills n bytes of memory starting at the location pointed to by s with the byte
c.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
char abuf[20];
See Also
strncpy(), strncmp(), strchr(), memcpy(), memchr()
246
Library Functions
MKTIME
Synopsis
#include <time.h>
Description
The mktime() function converts the local calendar time referenced by the tm structure pointer tmptr
into a time being the number of seconds passed since Jan 1st 1970, or -1 if the time cannot be
represented.
Example
#include <time.h>
#include <stdio.h>
void
main (void)
{
struct tm birthday;
birthday.tm_year = 1955;
birthday.tm_mon = 2;
birthday.tm_mday = 24;
birthday.tm_hour = birthday.tm_min = birthday.tm_sec = 0;
printf("you have been alive approximately %ld seconds\n", mktime(&birthday));
}
See Also
ctime(), asctime()
Return Value
The time contained in the tm structure represented as the number of seconds since the 1970 Epoch,
or -1 if this time cannot be represented.
247
Library Functions
MODF
Synopsis
#include <math.h>
Description
The modf() function splits the argument value into integral and fractional parts, each having the
same sign as value. For example, -3.17 would be split into the integral part (-3) and the fractional
part (-0.17).
The integral part is stored as a double in the object pointed to by iptr.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
double i_val, f_val;
Return Value
The signed fractional part of value.
248
Library Functions
PERSIST_CHECK, PERSIST_VALIDATE
Synopsis
#include <sys.h>
Description
The persist_check() function is used with non-volatile RAM variables, declared with the persistent
qualifier. It tests the nvram area, using a magic number stored in a hidden variable by a previous call
to persist_validate() and a checksum also calculated by persist_validate(). If the magic number and
checksum are correct, it returns true (non-zero). If either are incorrect, it returns zero. In this case it
will optionally zero out and re-validate the non-volatile RAM area (by calling persist_validate()).
This is done if the flag argument is true.
The persist_validate() routine should be called after each change to a persistent variable. It will
set up the magic number and recalculate the checksum.
Example
#include <sys.h>
#include <stdio.h>
void
main (void)
{
if(!persist_check(1))
printf("Reset count invalid - zeroed\n");
else
printf("Reset number %ld\n", reset_count);
reset_count++; /* update count */
persist_validate(); /* and checksum */
for(;;)
continue; /* sleep until next reset */
249
Library Functions
Return Value
FALSE (zero) if the NVRAM area is invalid; TRUE (non-zero) if the NVRAM area is valid.
250
Library Functions
POW
Synopsis
#include <math.h>
Description
The pow() function raises its first argument, f, to the power p.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
double f;
See Also
log(), log10(), exp()
Return Value
f to the power of p.
251
Library Functions
PRINTF, VPRINTF
Synopsis
#include <stdio.h>
#include <stdio.h>
#include <stdarg.h>
Description
The printf() function is a formatted output routine, operating on stdout. There are corresponding
routines operating on a given stream (fprintf()) or into a string buffer (sprintf()). The printf() routine
is passed a format string, followed by a list of zero or more arguments. In the format string are
conversion specifications, each of which is used to print out one of the argument list values.
Each conversion specification is of the form %m.nc where the percent symbol % introduces
a conversion, followed by an optional width specification m. The n specification is an optional
precision specification (introduced by the dot) and c is a letter specifying the type of the conversion.
A minus sign (’-’) preceding m indicates left rather than right adjustment of the converted value
in the field. Where the field width is larger than required for the conversion, blank padding is per-
formed at the left or right as specified. Where right adjustment of a numeric conversion is specified,
and the first digit of m is 0, then padding will be performed with zeroes rather than blanks. For
integer formats, the precision indicates a minimum number of digits to be output, with leading zeros
inserted to make up this number if required.
A hash character (#) preceding the width indicates that an alternate format is to be used. The
nature of the alternate format is discussed below. Not all formats have alternates. In those cases, the
presence of the hash character has no effect.
The floating point formats require that the appropriate floating point library is linked. From
within HPD this can be forced by selecting the "Float formats in printf" selection in the options
menu. From the command line driver, use the option -LF.
If the character * is used in place of a decimal constant, e.g. in the format %*d, then one integer
argument will be taken from the list to provide that value. The types of conversion are:
f
Floating point - m is the total width and n is the number of digits after the decimal point. If n is
252
Library Functions
omitted it defaults to 6. If the precision is zero, the decimal point will be omitted unless the alternate
format is specified.
e
Print the corresponding argument in scientific notation. Otherwise similar to f.
g
Use e or f format, whichever gives maximum precision in minimum width. Any trailing zeros after
the decimal point will be removed, and if no digits remain after the decimal point, it will also be
removed.
oxXud
Integer conversion - in radices 8, 16, 16, 10 and 10 respectively. The conversion is signed in the
case of d, unsigned otherwise. The precision value is the total number of digits to print, and may be
used to force leading zeroes. E.g. %8.4x will print at least 4 hex digits in an 8 wide field. Preceding
the key letter with an l indicates that the value argument is a long integer. The letter X prints out
hexadecimal numbers using the upper case letters A-F rather than a-f as would be printed when using
x. When the alternate format is specified, a leading zero will be supplied for the octal format, and a
leading 0x or 0X for the hex format.
s
Print a string - the value argument is assumed to be a character pointer. At most n characters from
the string will be printed, in a field m characters wide.
c
The argument is assumed to be a single character and is printed literally.
Any other characters used as conversion specifications will be printed. Thus % will produce a
single percent sign.
The vprintf() function is similar to printf() but takes a variable argument list pointer rather than
a list of arguments. See the description of va_start() for more information on variable argument lists.
An example of using vprintf() is given below.
Example
253
Library Functions
printf("xx%*d", 3, 4)
yields ’xx 4’
/* vprintf example */
#include <stdio.h>
int
error (char * s, ...)
{
va_list ap;
va_start(ap, s);
printf("Error: ");
vprintf(s, ap);
putchar(’\n’);
va_end(ap);
}
void
main (void)
{
int i;
i = 3;
error("testing 1 2 %d", i);
}
See Also
fprintf(), sprintf()
Return Value
The printf() and vprintf() functions return the number of characters written to stdout.
254
Library Functions
PUTCH
Synopsis
#include <conio.h>
Description
The putch() function outputs the character c to the console screen, prepending a carriage return if
the character is a newline. In a CP/M or MS-DOS system this will use one of the system I/O calls.
In an embedded system this routine, and associated others, will be defined in a hardware dependent
way. The standard putch() routines in the embedded library interface either to a serial port or to the
Lucifer Debugger.
Example
#include <conio.h>
void
main (void)
{
char * cp;
cp = x;
while(*x)
putch(*x++);
putch(’\n’);
}
See Also
cgets(), cputs(), getch(), getche()
255
Library Functions
PUTCHAR
Synopsis
#include <stdio.h>
Description
Example
#include <stdio.h>
void
main (void)
{
char * cp;
cp = x;
while(*x)
putchar(*x++);
putchar(’\n’);
}
See Also
Return Value
256
Library Functions
Note
This routine is not usable in a ROM based system.
257
Library Functions
PUTS
Synopsis
#include <stdio.h>
Description
The puts() function writes the string s to the stdout stream, appending a newline. The null character
terminating the string is not copied.
Example
#include <stdio.h>
void
main (void)
{
puts("Hello, world!");
}
See Also
fputs(), gets(), freopen(), fclose()
Return Value
EOF is returned on error; zero otherwise.
258
Library Functions
QSORT
Synopsis
#include <stdlib.h>
Description
The qsort() function is an implementation of the quicksort algorithm. It sorts an array of nel items,
each of length width bytes, located contiguously in memory at base. The argument func is a pointer
to a function used by qsort() to compare items. It calls func with pointers to two items to be com-
pared. If the first item is considered to be greater than, equal to or less than the second then func
should return a value greater than zero, equal to zero or less than zero respectively.
Example
#include <stdio.h>
#include <stdlib.h>
int aray[] = {
567, 23, 456, 1024, 17, 567, 66
};
int
sortem (const void * p1, const void * p2)
{
return *(int *)p1 - *(int *)p2;
}
void
main (void)
{
register int i;
259
Library Functions
Note
The function parameter must be a pointer to a function of type similar to:
i.e. it must accept two const void * parameters, and must be prototyped.
260
Library Functions
RAND
Synopsis
#include <stdlib.h>
Description
The rand() function is a pseudo-random number generator. It returns an integer in the range 0
to 32767, which changes in a pseudo-random fashion on each call. The algorithm will produce a
deterministic sequence if started from the same point. The starting point is set using the srand() call.
The example shows use of the time() function to generate a different starting point for the sequence
each time.
Example
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void
main (void)
{
time_t toc;
int i;
time(&toc);
srand((int)toc);
for(i = 0 ; i != 10 ; i++)
printf("%d\t", rand());
putchar(’\n’);
}
See Also
srand()
261
Library Functions
Note
The example will require the user to provide the time() routine as one cannot be supplied with the
compiler. See time() for more detail.
262
Library Functions
ROUND
Synopsis
#include <math.h>
Description
The round function round the argument to the nearest integer value, but in floating-point format.
Values midway between integer values are rounded up.
Example
#include <math.h>
void
main (void)
{
double input, rounded;
input = 1234.5678;
rounded = round(input);
}
See Also
trunc()
263
Library Functions
SCANF, VSCANF
Synopsis
#include <stdio.h>
#include <stdio.h>
#include <stdarg.h>
Description
The scanf() function performs formatted input ("de-editing") from the stdin stream. Similar func-
tions are available for streams in general, and for strings. The function vscanf() is similar, but takes
a pointer to an argument list rather than a series of additional arguments. This pointer should have
been initialised with va_start().
The input conversions are performed according to the fmt string; in general a character in the
format string must match a character in the input; however a space character in the format string will
match zero or more "white space" characters in the input, i.e. spaces, tabs or newlines.
A conversion specification takes the form of the character %, optionally followed by an assign-
ment suppression character (’*’), optionally followed by a numerical maximum field width, followed
by a conversion specification character. Each conversion specification, unless it incorporates the as-
signment suppression character, will assign a value to the variable pointed at by the next argument.
Thus if there are two conversion specifications in the fmt string, there should be two additional
pointer arguments.
The conversion characters are as follows:
oxd
Skip white space, then convert a number in base 8, 16 or 10 radix respectively. If a field width was
supplied, take at most that many characters from the input. A leading minus sign will be recognized.
f
Skip white space, then convert a floating number in either conventional or scientific notation. The
field width applies as above.
s
Skip white space, then copy a maximal length sequence of non-white-space characters. The pointer
264
Library Functions
argument must be a pointer to char. The field width will limit the number of characters copied. The
resultant string will be null terminated.
c
Copy the next character from the input. The pointer argument is assumed to be a pointer to char. If a
field width is specified, then copy that many characters. This differs from the s format in that white
space does not terminate the character sequence.
The conversion characters o, x, u, d and f may be preceded by an l to indicate that the corre-
sponding pointer argument is a pointer to long or double as appropriate. A preceding h will indicate
that the pointer argument is a pointer to short rather than int.
Example
scanf("%d %s", &a, &c)
with input " 12s"
will assign 12 to a, and "s" to s.
See Also
fscanf(), sscanf(), printf(), va_arg()
Return Value
The scanf() function returns the number of successful conversions; EOF is returned if end-of-file
was seen before any conversions were performed.
265
Library Functions
SETJMP
Synopsis
#include <setjmp.h>
Description
The setjmp() function is used with longjmp() for non-local goto’s. See longjmp() for further infor-
mation.
Example
#include <stdio.h>
#include <setjmp.h>
#include <stdlib.h>
jmp_buf jb;
void
inner (void)
{
longjmp(jb, 5);
}
void
main (void)
{
int i;
if(i = setjmp(jb)) {
printf("setjmp returned %d\n", i);
exit(0);
}
printf("setjmp returned 0 - good\n");
printf("calling inner...\n");
266
Library Functions
inner();
printf("inner returned - bad!\n");
}
See Also
longjmp()
Return Value
The setjmp() function returns zero after the real call, and non-zero if it apparently returns after a call
to longjmp().
267
Library Functions
SIN
Synopsis
#include <math.h>
Description
This function returns the sine function of its argument.
Example
#include <math.h>
#include <stdio.h>
#define C 3.141592/180.0
void
main (void)
{
double i;
See Also
cos(), tan(), asin(), acos(), atan(), atan2()
Return Value
Sine vale of f.
268
Library Functions
SPRINTF, VSPRINTF
Synopsis
#include <stdio.h>
#include <stdio.h>
#include <stdarg.h>
Description
The sprintf() function operates in a similar fashion to printf(), except that instead of placing the
converted output on the stdout stream, the characters are placed in the buffer at buf. The resultant
string will be null terminated, and the number of characters in the buffer will be returned.
The vsprintf() function is similar to sprintf() but takes a variable argument list pointer rather
than a list of arguments. See the description of va_start() for more information on variable argument
lists.
See Also
printf(), sscanf()
Return Value
Both these routines return the number of characters placed into the buffer.
269
Library Functions
SQRT
Synopsis
#include <math.h>
Description
The function sqrt(), implements a square root routine using Newton’s approximation.
Example
#include <math.h>
#include <stdio.h>
void
main (void)
{
double i;
See Also
exp()
Return Value
Returns the value of the square root.
Note
A domain error occurs if the argument is negative.
270
Library Functions
SRAND
Synopsis
#include <stdlib.h>
Description
The srand() function initializes the random number generator accessed by rand() with the given
seed. This provides a mechanism for varying the starting point of the pseudo-random sequence
yielded by rand(). On the Z80, a good place to get a truly random seed is from the refresh register.
Otherwise timing a response from the console will do, or just using the system time.
Example
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void
main (void)
{
time_t toc;
int i;
time(&toc);
srand((int)toc);
for(i = 0 ; i != 10 ; i++)
printf("%d\t", rand());
putchar(’\n’);
}
See Also
rand()
271
Library Functions
SSCANF, VSSCANF
Synopsis
#include <stdio.h>
#include <stdio.h>
#include <stdarg.h>
int vsscanf (const char * buf, const char * fmt, va_list ap)
Description
The sscanf() function operates in a similar manner to scanf(), except that instead of the conversions
being taken from stdin, they are taken from the string at buf.
The vsscanf() function takes an argument pointer rather than a list of arguments. See the de-
scription of va_start() for more information on variable argument lists.
See Also
scanf(), fscanf(), sprintf()
Return Value
Returns the value of EOF if an input failure occurs, else returns the number of input items.
272
Library Functions
STRCAT
Synopsis
#include <string.h>
Description
This function appends (concatenates) string s2 to the end of string s1. The result will be null termi-
nated. The argument s1 must point to a character array big enough to hold the resultant string.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
char buffer[256];
char * s1, * s2;
See Also
strcpy(), strcmp(), strncat(), strlen()
Return Value
The value of s1 is returned.
273
Library Functions
STRCHR, STRICHR
Synopsis
#include <string.h>
Description
The strchr() function searches the string s for an occurrence of the character c. If one is found, a
pointer to that character is returned, otherwise NULL is returned.
The strichr() function is the case-insensitive version of this function.
Example
#include <strings.h>
#include <stdio.h>
void
main (void)
{
static char temp[] = "Here it is...";
char c = ’s’;
if(strchr(temp, c))
printf("Character %c was found in string\n", c);
else
printf("No character was found in string");
}
See Also
strrchr(), strlen(), strcmp()
Return Value
A pointer to the first match found, or NULL if the character does not exist in the string.
274
Library Functions
Note
Although the function takes an integer argument for the character, only the lower 8 bits of the value
are used.
275
Library Functions
STRCMP, STRICMP
Synopsis
#include <string.h>
Description
The strcmp() function compares its two, null terminated, string arguments and returns a signed
integer to indicate whether s1 is less than, equal to or greater than s2. The comparison is done with
the standard collating sequence, which is that of the ASCII character set.
The stricmp() function is the case-insensitive version of this function.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
int i;
See Also
276
Library Functions
Return Value
A signed integer less than, equal to or greater than zero.
Note
Other C implementations may use a different collating sequence; the return value is negative, zero
or positive, i.e. do not test explicitly for negative one (-1) or one (1).
277
Library Functions
STRCPY
Synopsis
#include <string.h>
Description
This function copies a null terminated string s2 to a character array pointed to by s1. The destination
array must be large enough to hold the entire string, including the null terminator.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
char buffer[256];
char * s1, * s2;
See Also
strncpy(), strlen(), strcat(), strlen()
Return Value
The destination buffer pointer s1 is returned.
278
Library Functions
STRCSPN
Synopsis
#include <string.h>
Description
The strcspn() function returns the length of the initial segment of the string pointed to by s1 which
consists of characters NOT from the string pointed to by s2.
Example
#include <stdio.h>
#include <string.h>
void
main (void)
{
static char set[] = "xyz";
See Also
strspn()
Return Value
Returns the length of the segment.
279
Library Functions
STRLEN
Synopsis
#include <string.h>
Description
The strlen() function returns the number of characters in the string s, not including the null termina-
tor.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
char buffer[256];
char * s1, * s2;
Return Value
The number of characters preceding the null terminator.
280
Library Functions
STRNCAT
Synopsis
#include <string.h>
Description
This function appends (concatenates) string s2 to the end of string s1. At most n characters will be
copied, and the result will be null terminated. s1 must point to a character array big enough to hold
the resultant string.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
char buffer[256];
char * s1, * s2;
See Also
281
Library Functions
Return Value
The value of s1 is returned.
282
Library Functions
STRNCMP, STRNICMP
Synopsis
#include <string.h>
Description
The strncmp() function compares its two, null terminated, string arguments, up to a maximum of n
characters, and returns a signed integer to indicate whether s1 is less than, equal to or greater than s2.
The comparison is done with the standard collating sequence, which is that of the ASCII character
set.
The strnicmp() function is the case-insensitive version of this function.
Example
#include <stdio.h>
#include <string.h>
void
main (void)
{
int i;
i = strcmp("abcxyz", "abcxyz");
if(i == 0)
printf("Both strings are equal\n");
else if(i > 0)
printf("String 2 less than string 1\n");
else
printf("String 2 is greater than string 1\n");
}
See Also
strlen(), strcmp(), strcpy(), strcat()
283
Library Functions
Return Value
A signed integer less than, equal to or greater than zero.
Note
Other C implementations may use a different collating sequence; the return value is negative, zero
or positive, i.e. do not test explicitly for negative one (-1) or one (1).
284
Library Functions
STRNCPY
Synopsis
#include <string.h>
Description
This function copies a null terminated string s2 to a character array pointed to by s1. At most
n characters are copied. If string s2 is longer than n then the destination string will not be null
terminated. The destination array must be large enough to hold the entire string, including the null
terminator.
Example
#include <string.h>
#include <stdio.h>
void
main (void)
{
char buffer[256];
char * s1, * s2;
See Also
285
Library Functions
Return Value
The destination buffer pointer s1 is returned.
286
Library Functions
STRPBRK
Synopsis
#include <string.h>
Description
The strpbrk() function returns a pointer to the first occurrence in string s1 of any character from
string s2, or a null pointer if no character from s2 exists in s1.
Example
#include <stdio.h>
#include <string.h>
void
main (void)
{
char * str = "This is a string.";
while(str != NULL) {
printf( "%s\n", str );
str = strpbrk( str+1, "aeiou" );
}
}
Return Value
Pointer to the first matching character, or NULL if no character found.
287
Library Functions
STRRCHR, STRRICHR
Synopsis
#include <string.h>
Description
The strrchr() function is similar to the strchr() function, but searches from the end of the string
rather than the beginning, i.e. it locates the last occurrence of the character c in the null terminated
string s. If successful it returns a pointer to that occurrence, otherwise it returns NULL.
The strrichr() function is the case-insensitive version of this function.
Example
#include <stdio.h>
#include <string.h>
void
main (void)
{
char * str = "This is a string.";
while(str != NULL) {
printf( "%s\n", str );
str = strrchr( str+1, ’s’);
}
}
See Also
strchr(), strlen(), strcmp(), strcpy(), strcat()
Return Value
A pointer to the character, or NULL if none is found.
288
Library Functions
STRSPN
Synopsis
#include <string.h>
Description
The strspn() function returns the length of the initial segment of the string pointed to by s1 which
consists entirely of characters from the string pointed to by s2.
Example
#include <stdio.h>
#include <string.h>
void
main (void)
{
printf("%d\n", strspn("This is a string", "This"));
printf("%d\n", strspn("This is a string", "this"));
}
See Also
strcspn()
Return Value
The length of the segment.
289
Library Functions
STRSTR, STRISTR
Synopsis
#include <string.h>
Description
The strstr() function locates the first occurrence of the sequence of characters in the string pointed
to by s2 in the string pointed to by s1.
The stristr() routine is the case-insensitive version of this function.
Example
#include <stdio.h>
#include <string.h>
void
main (void)
{
printf("%d\n", strstr("This is a string", "str"));
}
Return Value
Pointer to the located string or a null pointer if the string was not found.
290
Library Functions
STRTOD
Synopsis
#include <stdlib.h>
Description
Parse the string s converting it to a double floating point type. This function converts the first
occurence of a substring of the input that is made up of characters of the expected form after skipping
leading white-space characters. If res is not NULL, it will be made to point to the first character after
the converted sub-string.
Example
#include <stdio.h>
#include <strlib.h>
void
main (void)
{
char buf[] = " 35.7 23.27 ";
char * end;
double in1, in2;
See Also
atof()
291
Library Functions
Return Value
Returns a double representing the floating-point value of the converted input string.
292
Library Functions
STRTOL
Synopsis
#include <stdlib.h>
Description
Parse the string s converting it to a long integer type. This function converts the first occurence of
a substring of the input that is made up of characters of the expected form after skipping leading
white-space characters. The radix of the input is determined from base. If this is zero, then the
radix defaults to base 10. If res is not NULL, it will be made to point to the first character after the
converted sub-string.
Example
#include <stdio.h>
#include <strlib.h>
void
main (void)
{
char buf[] = " 0X299 0x792 ";
char * end;
long in1, in2;
See Also
strtod()
293
Library Functions
Return Value
Returns a long int representing the value of the converted input string using the specified base.
294
Library Functions
STRTOK
Synopsis
#include <string.h>
Description
A number of calls to strtok() breaks the string s1 (which consists of a sequence of zero or more text
tokens separated by one or more characters from the separator string s2) into its separate tokens.
The first call must have the string s1. This call returns a pointer to the first character of the first
token, or NULL if no tokens were found. The inter-token separator character is overwritten by a null
character, which terminates the current token.
For subsequent calls to strtok(), s1 should be set to a null pointer. These calls start searching
from the end of the last token found, and again return a pointer to the first character of the next token,
or NULL if no further tokens were found.
Example
#include <stdio.h>
#include <string.h>
void
main (void)
{
char * ptr;
char buf[] = "This is a string of words.";
char * sep_tok = ".,?! ";
295
Library Functions
Return Value
Returns a pointer to the first character of a token, or a null pointer if no token was found.
Note
The separator string s2 may be different from call to call.
296
Library Functions
TAN
Synopsis
#include <math.h>
Description
The tan() function calculates the tangent of f.
Example
#include <math.h>
#include <stdio.h>
#define C 3.141592/180.0
void
main (void)
{
double i;
See Also
sin(), cos(), asin(), acos(), atan(), atan2()
Return Value
The tangent of f.
297
Library Functions
TIME
Synopsis
#include <time.h>
Description
This function is not provided as it is dependant on the target system supplying the current time. This
function will be user implemented. When implemented, this function should return the current time
in seconds since 00:00:00 on Jan 1, 1970. If the argument t is not equal to NULL, the same value is
stored into the object pointed to by t.
Example
#include <stdio.h>
#include <time.h>
void
main (void)
{
time_t clock;
time(&clock);
printf("%s", ctime(&clock));
}
See Also
Return Value
This routine when implemented will return the current time in seconds since 00:00:00 on Jan 1,
1970.
298
Library Functions
Note
The time() routine is not supplied, if required the user will have to implement this routine to the
specifications outlined above.
299
Library Functions
#include <ctype.h>
Description
The toupper() function converts its lower case alphabetic argument to upper case, the tolower()
routine performs the reverse conversion and the toascii() macro returns a result that is guaranteed
in the range 0-0177. The functions toupper() and tolower() return their arguments if it is not an
alphabetic character.
Example
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void
main (void)
{
char * array1 = "aBcDE";
int i;
See Also
islower(), isupper(), isascii(), et. al.
300
Library Functions
TRUNC
Synopsis
#include <math.h>
Description
The trunc function rounds the argument to the nearest integer value, in floating-point format, that is
not larger in magniture than the argument.
Example
#include <math.h>
void
main (void)
{
double input, rounded;
input = 1234.5678;
rounded = trunc(input);
}
See Also
round()
301
Library Functions
UDIV
Synopsis
#include <stdlib.h>
Description
The udiv() function calculate the quotient and remainder of the division of number and denom,
storing the results into a udiv_t structure which is returned.
Example
#include <stdlib.h>
void
main (void)
{
udiv_t result;
unsigned num = 1234, den = 7;
See Also
uldiv(), div(), ldiv()
Return Value
Returns the the quotient and remainder as a udiv_t structure.
302
Library Functions
ULDIV
Synopsis
#include <stdlib.h>
Description
The uldiv() function calculate the quotient and remainder of the division of number and denom,
storing the results into a uldiv_t structure which is returned.
Example
#include <stdlib.h>
void
main (void)
{
uldiv_t result;
unsigned long num = 1234, den = 7;
See Also
ldiv(), udiv(), div()
Return Value
Returns the the quotient and remainder as a uldiv_t structure.
303
Library Functions
UNGETCH
Synopsis
#include <conio.h>
Description
The ungetch() function will push back the character c onto the console stream, such that a subse-
quent getch() operation will return the character. At most one level of push back will be allowed.
See Also
getch(), getche()
304
Library Functions
UTOA
Synopsis
#include <stdlib.h>
Description
The function itoa converts the unsigned contents of val into a string which is stored into buf. The
conversion is performed according to the radix specified in base. buf is assumed to reference a
buffer which has sufficent space allocated to it.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
char buf[10];
utoi(buf, 1234, 16);
printf("The buffer holds %s\n", buf);
}
See Also
strtol(), itoa(), ltoa(), ultoa()
Return Value
This routine returns a copy of the buffer into which the result is written.
305
Library Functions
#include <stdarg.h>
Description
These macros are provided to give access in a portable way to parameters to a function represented in
a prototype by the ellipsis symbol (...), where type and number of arguments supplied to the function
are not known at compile time.
The rightmost parameter to the function (shown as parmN) plays an important role in these
macros, as it is the starting point for access to further parameters. In a function taking variable num-
bers of arguments, a variable of type va_list should be declared, then the macro va_start() invoked
with that variable and the name of parmN. This will initialize the variable to allow subsequent calls
of the macro va_arg() to access successive parameters.
Each call to va_arg() requires two arguments; the variable previously defined and a type name
which is the type that the next parameter is expected to be. Note that any arguments thus accessed
will have been widened by the default conventions to int, unsigned int or double. For example if a
character argument has been passed, it should be accessed by va_arg(ap, int) since the char will
have been widened to int.
An example is given below of a function taking one integer parameter, followed by a number
of other parameters. In this example the function expects the subsequent parameters to be pointers
to char, but note that the compiler is not aware of this, and it is the programmers responsibility to
ensure that correct arguments are supplied.
Example
#include <stdio.h>
#include <stdarg.h>
void
pf (int a, ...)
{
306
Library Functions
va_list ap;
va_start(ap, a);
while(a--)
puts(va_arg(ap, char *));
va_end(ap);
}
void
main (void)
{
pf(3, "Line 1", "line 2", "line 3");
}
307
Library Functions
XTOI
Synopsis
#include <stdlib.h>
Description
The xtoi() function scans the character string passed to it, skipping leading blanks reading an optional
sign, and converts an ASCII representation of a hexadecimal number to an integer.
Example
#include <stdlib.h>
#include <stdio.h>
void
main (void)
{
char buf[80];
int i;
gets(buf);
i = xtoi(buf);
printf("Read %s: converted to %x\n", buf, i);
}
See Also
atoi()
Return Value
A signed integer. If no number is found in the string, zero will be returned.
308
Appendix B
This chapter lists most error, warning and advisory messages from all HI-TECH C compilers, with
an explanation of each message. Most messages have been assigned a unique number which appears
in brackets before each message in this chapter, and which is also printed by the compiler when the
message is issued. The messages shown here are sorted by their number. Un-numbered messages
appear toward the end and are sorted alphabetically.
The name of the application(s) that could have produced the messages are listed in brackets
opposite the error message. In some cases examples of code or options that could trigger the error
are given. The use of * in the error message is used to represent a string that the compiler will
substitute that is specific to that particular error.
Note that one problem in your C or assembler source code may trigger more than one error
message.
309
Error and Warning Messages
#ifdef FOO
result = foo;
#else
result = bar;
#elif defined(NEXT) /* the #else above terminated the #if */
result = next(0);
#endif
#ifdef FOO
result = foo;
#endif
result = bar;
#elif defined(NEXT) /* the #endif above terminated the #if */
result = next(0);
#endif
310
Error and Warning Messages
void cleardog(void)
{
clrwdt
#endasm /* this ends the in-line assembler, only where did it begin? */
}
#asm
move r0, #0aah
#asm ; the previous #asm must be closed before opening another
sleep
#endasm
311
Error and Warning Messages
(110) too many file arguments; usage: cpp [input [output]] (Preprocessor)
CPP should be invoked with at most two file arguments. Contact HI-TECH Support if the preproces-
sor is being executed by a compiler driver.
#define ONE 1
/* elsewhere: */
/* Is this correct? It will overwrite the first definition. */
#define ONE one
312
Error and Warning Messages
(116) end of file within preprocessor macro argument from line * (Preprocessor)
A macro argument has not been terminated. This probably means the closing parenthesis has been
omitted from a macro invocation. The line number given is the line where the macro argument
started, e.g.:
#if FOO BAR /* oops -- did you mean: #if FOO == BAR ? */
313
Error and Warning Messages
An operator has been encountered in a #if expression that is incorrectly placed, e.g. two binary
operators are not separated by a value, e.g.:
Expressions in #if lines are evaluated using a stack with a size of 128. It is possible for very complex
expressions to overflow this. Simplify the expression.
The evaluation of a #if expression found mismatched parentheses. Check the expression for correct
parenthesisation, e.g.:
A colon operator has been encountered in a #if expression that does not match up with a corre-
sponding ? operator, e.g.:
#if XXX : YYY /* did you mean: #if COND ? XXX : YYY */
There is a character in a #if expression that has no business being there. Valid characters are the
letters, digits and those comprising the acceptable operators, e.g.:
314
Error and Warning Messages
315
Error and Warning Messages
316
Error and Warning Messages
/* Here is the start of a comment. I’m not sure where I end, though
}
(140) can’t open * file "*": * (Driver, Preprocessor, Code Generator, Assembler)
The command file specified could not be opened for reading. Confirm the spelling and path of the
file specified on the command line, e.g.:
picc @communds
picc @commands
317
Error and Warning Messages
318
Error and Warning Messages
319
Error and Warning Messages
#if defined(END)
#define NEXT
#endif END /* END would be better in a comment here */
The #include file name had to be converted to lowercase before it could be opened, e.g.:
(165) #include filename "*" does not match actual name (check upper/lower case) (Prepro-
cessor)
In Windows versions this means the file to be included actually exists and is spelt the same way as
the #include filename, however the case of each does not exactly match. For example, specifying
#include “code.c” will include Code.c if it is found. In Linux versions this warning could occur
if the file wasn’t found.
The list of values to the preprocessor (CPP) -S option is incomplete. This should not happen if the
preprocessor is being invoked by the compiler driver. The values passes to this option represent the
sizes of char, short, int, long, float and double types.
(167) too many values specified with -S option; "*" unused (Preprocessor)
There were too many values supplied to the -S preprocessor option. See the Error Message -s, too
few values specified in * on page 320.
This option given to the component which caused the error is not recognized.
320
Error and Warning Messages
The symbol supplied as argument to #undef was not already defined. This warning may be disabled
with some compilers. This warning can be avoided with code like:
#ifdef SYM
#undef SYM /* only undefine if defined */
#endif
(171) wrong number of preprocessor macro arguments for "*" (* instead of *)(Preprocessor)
A macro has been invoked with the wrong number of arguments, e.g.:
The stringization operator # (not to be confused with the leading # used for preprocessor control
lines) must be followed by a formal macro parameter, e.g.:
If you need to stringize a token, you will need to define a special macro to do it, e.g.
#define __mkstr__(x) #x
then use __mkstr__(token) wherever you need to convert a token into a string.
A symbol on a #if expression was not a defined preprocessor macro. For the purposes of this
expression, its value has been taken as zero. This warning may be disabled with some compilers.
Example:
321
Error and Warning Messages
Multi-byte constants are not portable, and in fact will be rejected by later passes of the compiler,
e.g.:
Inside a #if expression, there is a division by zero which has been treated as yielding zero, e.g.:
A new line is missing at the end of the line. Each line, including the last line, must have a new line
at the end. This problem is normally introduced by editors.
A macro name specified in a -U option to the preprocessor was not initially defined, and thus cannot
be undefined.
This warning is issued when nested comments are found. A nested comment may indicate that a
previous closing comment marker is missing or malformed, e.g.:
Comments begun inside an included file must end inside the included file.
322
Error and Warning Messages
Note that even if a structure only contains an int, for example, it cannot be assigned to an int
variable, and vice versa.
int a, b, c, d;
a = b(c+d); /* b is not a function -- did you mean a = b*(c+d) ? */
int get_value(void);
void main(void)
{
323
Error and Warning Messages
int input;
input = get_value(6); /* oops -- the parameter should not be here */
}
int a;
switch(input) {
case a: /* oops! you cannot use a variable as part of a case label */
input++;
}
int i, array[10];
i = array[3.5]; /* oops -- exactly which element do you mean? */
324
Error and Warning Messages
int a;
a.b = 9; /* oops -- a is not a structure */
325
Error and Warning Messages
int array[10];
int * ip;
char c;
array = ip; /* array is not a variable, it cannot be written to */
326
Error and Warning Messages
*(int *)&c = 1
bit b;
int * ip;
ip = &b; /* oops -- cannot take the address of a bit object */
void run(void)
{
step();
return 1; /* either run should not be void, or remove the 1 */
}
327
Error and Warning Messages
int * ip;
char * cp, * cp2;
cp = flag ? ip : cp2; /* result of ? : will either be int * or char * */
This is an internal compiler error. Contact HI-TECH Software technical support with details.
It is illegal to use the sizeof operator with the HI-TECH C bit type. When used against a type the
sizeof operator gives the number of bytes required to store an object that type. Therefore its usage
with the bit type make no sense and is an illegal operation.
The pragma pack requires a decimal number as argument. This specifies the alignment of each
member within the structure. Use this with caution as some processors enforce alignment and will
not operate correctly if word fetches are made on odd boundaries, e.g.:
#pragma pack 2
328
Error and Warning Messages
Pragmas for all the standard printf-like function are already contained in <stdio.h>.
329
Error and Warning Messages
A floating point constant must have at least one digit after the e or E., e.g.:
float f;
f = 1.234e; /* oops -- what is the exponent? */
After 0x should follow at least one of the hex digits 0-9 and A-F or a-f, e.g.:
A digit in this number is out of range of the radix for the number, e.g. using the digit 8 in an octal
number, or hex digits A-F in a decimal number. An octal number is denoted by the digit string
commencing with a zero, while a hex number starts with "0X" or "0x". For example:
An illegal # preprocessor has been detected. Likely a directive has been misspelt in your code
somewhere.
330
Error and Warning Messages
331
Error and Warning Messages
332
Error and Warning Messages
There are too many initializers for this object. Check the number of initializers against the object
definition (array or structure), e.g.:
The initialisation of this object is syntactically incorrect. Check for the correct placement and num-
ber of braces and commas, e.g.:
A switch operation must have an expression that is either an integral type or an enumerated value,
e.g:
double d;
switch(d) { /* oops -- this must be integral */
case ’1.0’:
d = 0;
}
A break or continue statement has been found that is not enclosed in an appropriate control struc-
ture. A continue can only be used inside a while, for or do while loop, while break can only be
used inside those loops or a switch statement, e.g.:
switch(input) {
case 0:
if(output == 0)
input = 0xff;
} /* oops! this shouldn’t be here and closed the switch */
break; /* this should be inside the switch */
333
Error and Warning Messages
There is only allowed to be one default label in a switch statement. You have more than one, e.g.:
switch(a) {
default: /* if this is the default case... */
b = 9;
break;
default: /* then what is this? */
b = 10;
break;
A label has been encountered called default but it is not enclosed by a switch statement. A
default label is only legal inside the body of a switch statement.
If there is a switch statement before this default label, there may be one too many closing
braces in the switch code which would prematurely terminate the switch statement. See example
for Error Message ’case’ not in switch on page 334.
A case label has been encountered, but there is no enclosing switch statement. A case label may
only appear inside the body of a switch statement.
If there is a switch statement before this case label, there may be one too many closing braces
in the switch code which would prematurely terminate the switch statement, e.g.:
switch(input) {
case ’0’:
count++;
break;
case ’1’:
if(count>MAX)
count= 0;
} /* oops -- this shouldn’t be here */
break;
case ’2’: /* error flagged here */
334
Error and Warning Messages
The same name is used for a label more than once in this function. Note that the scope of labels is
the entire function, not just the block that encloses a label, e.g.:
start:
if(a > 256)
goto end;
start: /* error flagged here */
if(a == 0)
goto start; /* which start label do I jump to? */
An else keyword has been encountered that cannot be associated with an if statement. This may
mean there is a missing brace or other syntactic error, e.g.:
The compiler has encountered what looks like a function or other declaration, but the preceding
function has not been ended with a closing brace. This probably means that a closing brace has been
omitted from somewhere in the previous function, although it may well not be the last one, e.g.:
void set(char a)
{
PORTA = a;
/* the closing brace was left out here */
void clear(void) /* error flagged here */
{
PORTA = 0;
}
335
Error and Warning Messages
336
Error and Warning Messages
struct {
int a, b, c;
} data;
if(data.d) /* oops -- there is no member d in this structure */
return;
The only storage class allowed for a function parameter is register, e.g.:
There are two occurrences of the same qualifier in this type specification. This can occur either
directly or through the use of a typedef. Remove the redundant qualifier. For example:
far near int spooky; /* oops -- choose either far or near, not both */
337
Error and Warning Messages
struct {
int a;
int b;
int a; /* oops -- a different name is required here */
} input;
struct {
int a;
} ms;
struct {
int a;
} ms; /* was this meant to be the same name as above? */
struct {
int a;
int get(int); /* this should be a pointer: int (*get)(int); */
} object;
struct FREG {
char b0:1; /* oops -- these must be part of an int, not char */
char :6;
char b7:1;
} freg;
338
Error and Warning Messages
A colon appearing after a member name in a structure declaration indicates that the member is a
bitfield. An integral constant must appear after the colon to define the number of bits in the bitfield,
e.g.:
struct {
unsigned first: /* oops -- should be: unsigned first; */
unsigned second;
} my_struct;
If this was meant to be a structure with bitfields, then the following illustrates an example:
struct {
unsigned first : 4; /* 4 bits wide */
unsigned second: 4; /* another 4 bits */
} my_struct;
A structure or union member may not be given a storage class. Its storage class is determined by the
storage class of the structure, e.g.:
struct {
/* no additional qualifiers may be present with members */
static int first;
} ;
The code generator has encountered a variable definition whose storage class is invalid, e.g.:
339
Error and Warning Messages
340
Error and Warning Messages
int calc(int a, int a) /* you cannot have two parameters called “a” */
341
Error and Warning Messages
342
Error and Warning Messages
int a;
void b; /* this makes no sense */
343
Error and Warning Messages
const char ccrv(void) /* oops! did you mean const * char ccrv(void) ? */
{ /* error flagged here */
return ccip;
}
int process(input)
int unput; /* oops -- that should be int input; */
{
}
344
Error and Warning Messages
#asm
mov r0, #55
mov [r1], r0
} /* oops -- where is the #endasm */
void main(void)
{
init();
run(); /* is that it? What about the close brace */
345
Error and Warning Messages
while(a) {
b = a-- /* oops -- where is the semicolon? */
} /* error is flagged here */
346
Error and Warning Messages
Note: Omitting a semicolon from statements not preceding a close brace or keyword typically results
in some other error being issued for the following code which the parser assumes to be part of the
original statement.
An opening brace was expected here. This error may be the result of a function definition missing
the opening brace, e.g.:
A closing brace was expected here. This error may be the result of a initialized array missing the
closing brace, e.g.:
An opening parenthesis, (, was expected here. This must be the first token after a while, for, if,
do or asm keyword, e.g.:
347
Error and Warning Messages
do {
func(i++);
} /* do the block while what condition is true? */
if(i > 5) /* error flagged here */
end();
switch(input) {
case 0; /* oops -- that should have been: case 0: */
state = NEW;
if(a)
goto 20; /* this is not BASIC -- a valid C label must follow a goto */
struct {
int a;
} my_struct;
348
Error and Warning Messages
(327) long long int argument required in printf-style format string (Parser)
A long long argument is required for this format specifier. Check the number and order of format
specifiers and corresponding arguments, e.g.:
Note that not all HI-TECH C compilers provide support for a long long integer type.
349
Error and Warning Messages
350
Error and Warning Messages
char * cp = “hi”
“there”; /* this is okay, but is it what you had intended? */
extern int other = 99; /* if it’s extern and not allocated storage,
how can it be initialized? */
351
Error and Warning Messages
int get_value(void)
{
if(flag)
return val++;
return; /* what is the return value in this instance? */
}
352
Error and Warning Messages
{
int input; /* local blockscope input */
a = input; /* this will use the local variable. Is this right? */
int process(int a)
{
extern int away; /* this would be better outside the function */
return away + a;
}
int process(input)
int input; /* warning flagged here */
{
}
353
Error and Warning Messages
354
Error and Warning Messages
will perform a sign extension of the char variable to the longer type. If you do not want this to take
place, use a cast, e.g.:
ui = (unsigned char)sc;
double dd;
int i;
i = dd; /* is this really what you meant? */
If you do intend to use an expression like this, then indicate that this is so by a cast:
i = (int)dd;
int * ip;
int i;
ip = i; /* oops -- did you mean ip = &i ? */
If you do intend to use an expression like this, then indicate that this is so by a cast:
ip = (int *)i;
355
Error and Warning Messages
int * ip;
int i;
i = ip; /* oops -- did you mean i = *ip ? */
If you do intend to use an expression like this, then indicate that this is so by a cast:
i = (int)ip;
A pointer of one type (i.e. pointing to a particular kind of object) has been converted into a pointer
of a different type. This will usually mean you have used the wrong variable, but if this is genuinely
what you want to do, use a typecast to inform the compiler that you want the conversion and the
warning will be suppressed, e.g.:
long input;
char * cp;
cp = &input; /* is this correct? */
This is common way of accessing bytes within a multi-byte variable. To indicate that this is the
intended operation of the program, use a cast:
This warning may also occur when converting between pointers to objects which have the same type,
but which have different qualifiers, e.g.:
char * cp;
/* yes, but what sort of characters? */
cp = “I am a string of characters”;
If the default type for string literals is const char *, then this warning is quite valid. This should
be written:
Omitting a qualifier from a pointer type is often disastrous, but almost certainly not what you intend.
356
Error and Warning Messages
357
Error and Warning Messages
char * get_addr(void)
{
char c;
/* returning this is dangerous; the pointer could be dereferenced */
return &c;
}
358
Error and Warning Messages
void main(void)
{
/* at this point the compiler assumes set is extern... */
set(10L, 6);
}
static void set(long a, int b) /* now it finds out otherwise */
{
PORTA = a + b;
}
struct {
signed int sign: 1; /* this must be unsigned */
signed int value: 15;
} ;
359
Error and Warning Messages
This declaration does not include a basic type, so int has been assumed. This declaration is not
illegal, but it is preferable to include a basic type to make it clear what is intended, e.g.:
char c;
i; /* don’t let the compiler make assumptions, use : int i */
func(); /* ditto, use: extern int func(int); */
A comma was expected here. This could mean you have left out the comma between two identifiers
in a declaration list. It may also mean that the immediately preceding type name is misspelled, and
has thus been interpreted as an identifier, e.g.:
unsigned char a;
/* thinks: chat & b are unsigned, but where is the comma? */
unsigned chat b;
An unsigned type was expected where a signed type was given and was implicitly cast to unsigned,
e.g.:
The basic type of a cast to a qualified basic type was missing and assumed to be int., e.g.:
This is an internal compiler error. Contact HI-TECH Software technical support with details.
360
Error and Warning Messages
361
Error and Warning Messages
The map file name has been specified to the linker for a second time. This should not occur if you
are using a compiler driver. If invoking the linker manually, ensure that only one instance of this
option is present on the command line. See Section 5.7.9 for information on the correct syntax for
this option.
This linker -o flag is illegal, or another -o option has been encountered. A -o option to the linker
must be immediately followed by a filename with no intervening space.
There have been too many -p options passed to the linker, or a -p option was not followed by any
arguments. The arguments of separate -p options may be combined and separated by commas.
The symbol file name has been specified to the linker for a second time. This should not occur if you
are using a compiler driver. If invoking the linker manually, ensure that only one instance of either
of these options is present on the command line.
The maximum number of errors before aborting must be specified following the -j linker option.
362
Error and Warning Messages
363
Error and Warning Messages
364
Error and Warning Messages
365
Error and Warning Messages
-GA/f0+10
-GA/f0h+10
366
Error and Warning Messages
-SCODE=f000
-SCODE=f000h
-DCODE
What is the delta value for this class? Maybe you meant something like:
-DCODE=2
-ACODE
-ACODE=0h-1fffh
367
Error and Warning Messages
368
Error and Warning Messages
-AENTRY=0-0FFh-1FF
-AENTRY=0-0FFh-1FFh
-ACODE=0h-3fffh/a000
-ACODE=0h-3fffh/a000h
-AENTRY=0-0FFhxf
-AENTRY=0-0FFhxfh
369
Error and Warning Messages
-pbss=f000
-pbss=f000h
-pbss=data+f000
-pbss=data+f000h
(454) link and load address can’t both be set to "." in -P option (Linker)
The link and load address of a psect have both been specified with a dot character. Only one of these
addresses may be specified in this manner, e.g.:
-Pmypsect=1000h/.
-Pmypsect=./1000h
Both of these options are valid and equivalent, however the following usage is ambiguous:
-Pmypsect=./.
370
Error and Warning Messages
371
Error and Warning Messages
int test(int a)
{
if(a == 5) {
/* recursion may not be supported by some compilers */
return test(a++);
}
return 0;
}
(472) non-reentrant function "*" appears in multiple call graphs: rooted at "*" and "*"
(Linker)
This function can be called from both main-line code and interrupt code. Use the reentrant key-
word, if this compiler supports it, or recode to avoid using local variables or parameters, or duplicate
the function, e.g.:
372
Error and Warning Messages
void process(int a)
{
scan(a); /* scan is also called from main-line code */
}
(476) fixup overflow referencing * * (location 0x* (0x*+*), size *, value 0x*) (Linker)
The linker was asked to relocate (fixup) an item that would not fit back into the space after relocation.
See the following error message (477) for more information..
(477) fixup overflow in expression (location 0x* (0x*+*), size *, value 0x*) (Linker)
Fixup is the process conducted by the linker of replacing symbolic references to variables etc, in an
assembler instruction with an absolute value. This takes place after positioning the psects (program
sections or blocks) into the available memory on the target device. Fixup overflow is when the
value determined for a symbol is too large to fit within the allocated space within the assembler
instruction. For example, if an assembler instruction has an 8-bit field to hold an address and the
linker determines that the symbol that has been used to represent this address has the value 0x110,
then clearly this value cannot be inserted into the instruction.
The causes for this can be many, but hand-written assembler code is always the first suspect.
Badly written C code can also generate assembler that ultimately generates fixup overflow errors.
Consider the following error message.
This indicates that the file causing the problem was main.obj. This would be typically be the output
of compiling main.c or main.as. This tells you the file in which you should be looking. The next
373
Error and Warning Messages
number (8 in this example) is the record number in the object file that was causing the problem. If
you use the DUMP utility to examine the object file, you can identify the record, however you do not
normally need to do this.
The location (loc) of the instruction (0x1FD), the size (in bytes) of the field in the instruction
for the value (1) , and the value which is the actual value the symbol represents, is typically the only
information needed to track down the cause of this error. Note that a size which is not a multiple of
8 bits will be rounded up to the nearest byte size, i.e. a 7 bit space in an instruction will be shown as
1 byte.
Generate an assembler list file for the appropriate module. Look for the address specified in the
error message.
and to confirm, look for the symbol referenced in the assembler instruction at this address in the
symbol table at the bottom of the same file.
In this example, the instruction causing the problem takes an 8-bit offset into a bank of memory, but
clearly the address 0x1FC exceeds this size. Maybe the instruction should have been written as:
movwf (_foo&0ffh)
which masks out the top bits of the address containing the bank information.
If the assembler instruction that caused this error was generated by the compiler, in the assem-
bler list file look back up the file from the instruction at fault to determine which C statement has
generated this instruction. You will then need to examine the C code for possible errors. incorrectly
qualified pointers are an common trigger.
(478) * range check failed (location 0x* (0x*+*), value 0x* > limit 0x*) (Linker)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
374
Error and Warning Messages
375
Error and Warning Messages
psect spdata,class=RAM,space=0
ds 6
; elsewhere:
psect spdata,class=RAM,space=1
psect final,class=CODE,delta=2
finish:
; elsewhere:
psect final,class=CODE,delta=1
376
Error and Warning Messages
(491) can’t find 0x* words for psect "*" in segment "*" (Linker)
One of the main tasks the linker performs is positioning the blocks (or psects) of code and data that
is generated from the program into the memory available for the target device. This error indicates
that the linker was unable to find an area of free memory large enough to accommodate one of the
psects. The error message indicates the name of the psect that the linker was attempting to position
and the segment name which is typically the name of a class which is defined with a linker -A option.
Section 3.7.1 lists each compiler-generated psect and what it contains. Typically psect names
which are, or include, text relate to program code. Names such as bss or data refer to variable
blocks. This error can be due to two reasons.
First, the size of the program or the program’s data has exceeded the total amount of space on
the selected device. In other words, some part of your device’s memory has completely filled. If this
is the case, then the size of the specified psect must be reduced.
The second cause of this message is when the total amount of memory needed by the psect being
positioned is sufficient, but that this memory is fragmented in such a way that the largest contiguous
block is too small to accommodate the psect. The linker is unable to split psects in this situation.
That is, the linker cannot place part of a psect at one location and part somewhere else. Thus, the
linker must be able to find a contiguous block of memory large enough for every psect. If this is the
cause of the error, then the psect must be split into smaller psects if possible.
To find out what memory is still available, generate and look in the map file, see Section 2.6.8 for
information on how to generate a map file. Search for the string UNUSED ADDRESS RANGES. Under
this heading, look for the name of the segment specified in the error message. If the name is not
present, then all the memory available for this psect has been allocated. If it is present, there will be
one address range specified under this segment for each free block of memory. Determine the size
of each block and compare this with the number of words specified in the error message.
Psects containing code can be reduced by using all the compiler’s optimizations, or restructuring
the program. If a code psect must be split into two or more small psects, this requires splitting a
function into two or more smaller functions (which may call each other). These functions may need
to be placed in new modules.
Psects containing data may be reduced when invoking the compiler optimizations, but the effect
is less dramatic. The program may need to be rewritten so that it needs less variables. Section
5.10.2.2 has information on interpreting the map file’s call graph if the compiler you are using uses
a compiled stack. (If the string Call graph: is not present in the map file, then the compiled
code uses a hardware stack.) If a data psect needs to be split into smaller psects, the definitions
for variables will need to be moved to new modules or more evenly spread in the existing modules.
Memory allocation for auto variables is entirely handled by the compiler. Other than reducing the
number of these variables used, the programmer has little control over their operation. This applies
whether the compiled code uses a hardware or compiled stack.
For example, after receiving the message:
377
Error and Warning Messages
Can’t find 0x34 words (0x34 withtotal) for psect text in segment CODE
(error)
In the CODE segment, there is 0x1c (0x25f-0x244+1) bytes of space available in one block and 0x30
available in another block. Neither of these are large enough to accommodate the psect text which
is 0x34 bytes long. Notice, however, that the total amount of memory available is larger than 0x34
bytes.
-Ptext=10g0h
-Ptext=10f0h
378
Error and Warning Messages
The psect has more bytes in it than the maximum allowed as specified using the size psect flag.
The maximum address of the psect exceeds the limit placed on it using the limit psect flag. Either
the psect needs to be linked at a different location or there is too much code/data in the psect.
The symbol following is undefined at link time. This could be due to spelling error, or failure to link
an appropriate module.
A list of symbols follows that were undefined at link time. These errors could be due to spelling
error, or failure to link an appropriate module.
There is more than one entry point defined in the object files given the linker. End entry point is
specified after the END directive. The runtime startup code defines the entry point, e.g.:
powerup:
goto start
END powerup ; end of file and define entry point
; other files that use END should not define another entry point
An object file contained a record with an illegal size. This probably means the file is truncated or
not an object file. Contact HI-TECH Support with details.
The object files passed to the linker do not have matching ident records. This means they are for
different processor types.
379
Error and Warning Messages
380
Error and Warning Messages
The linker has been asked to perform complex relocation that is not syntactically correct. Probably
means an object file is corrupted.
An object file contained a relocation record with an illegal relocation type. This probably means the
file is corrupted or not an object file. Contact HI-TECH Support with details if the object file was
created by the compiler.
This is an internal compiler error. Contact HI-TECH Software technical support with details.
This is an internal compiler error. Contact HI-TECH Software technical support with details.
This function is never called. This may not represent a problem, but space could be saved by remov-
ing it. If you believe this function should be called, check your source code. Some assembler library
routines are never called, although they are actually execute. In this case, the routines are linked in
a special sequence so that program execution falls through from one routine to the next.
The call graph shows that functions are nested to a depth greater than specified.
This library is badly ordered. It will still link correctly, but it will link faster if better ordered.
The argument to the linker option -w is out of range. This option controls two features. For warning
levels, the range is -9 to 9. For the map file width, the range is greater than or equal to 10.
381
Error and Warning Messages
(525) too many address (memory) spaces; space (*) ignored (Linker)
The limit to the number of address spaces (specified with the PSECT assembler directive) is currently
16.
(526) psect "*" not specified in -P option (first appears in "*") (Linker)
This psect was not specified in a -P or -A option to the linker. It has been linked at the end of the
program, which is probably not where you wanted it.
(593) can’t find 0x* words (0x* withtotal) for psect "*" in segment "*" (Linker)
See error (491) on Page 377.
382
Error and Warning Messages
383
Error and Warning Messages
384
Error and Warning Messages
385
Error and Warning Messages
(629) bad storage class "*" in SDB file "*" line * column * (Cromwell)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
(630) invalid syntax for prefix list in SDB file "*" (Cromwell)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
(631) syntax error at token "*" in SDB file "*" line * column * (Cromwell)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
(636) checksum error in Intel HEX file "*" on line * (Cromwell, Hexmate)
A checksum error was found at the specified line in the specified Intel hex file. The HEX file may
be corrupt.
386
Error and Warning Messages
(668) prefix list did not match any SDB types (Cromwell)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
(669) prefix list matched more than one SDB type (Cromwell)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
387
Error and Warning Messages
(682) this architecture is not supported by the PICC Lite compiler (Code Generator)
A target device other than baseline, midrange or highend was specified. This compiler only supports
devices from these architecture families.
(683) bank 1 variables are not supported by the PICC Lite compiler (Code Generator)
A variable with an absolute address located in bank 1 was detected. This compiler does not support
code generation of variables in this bank.
(684) bank 2 and 3 variables are not supported by the PICC Lite compiler (Code Generator)
A variable with an absolute address located in bank 2 or 3 was detected. This compiler does not
support code generation of variables in these banks.
switch(in) {
case ’0’: /* if this is case ’0’... */
b++;
break;
case ’0’: /* then what is this case? */
b--;
break;
}
388
Error and Warning Messages
switch(input) {
} /* there is nothing to match the value of input */
389
Error and Warning Messages
390
Error and Warning Messages
391
Error and Warning Messages
392
Error and Warning Messages
struct {
unsigned flag : 1;
unsigned value : 12;
unsigned cont : 6; /* oops -- that makes a total of 19 bits */
} object;
void fn1(void)
{
fn3( 7, fn2(3), fn2(9)); /* Offending call */
}
char fn2(char fred)
{
return fred + fn3(5,1,0);
}
char fn3(char one, char two, char three)
{
return one+two+three;
}
393
Error and Warning Messages
where fn1 is calling fn3, and two arguments are evaluated by calling fn2, which in turn calls fn3.
The program structure should be modified to prevent this type of call sequence.
(746) object "*" qualified const, but not initialized (Code Generator)
An object has been qualified as const, but there is no initial value supplied at the definition. As this
object cannot be written by the C program, this may imply the intial value was accidently omitted.
void main(void)
{
int a;
if(a) /* oops -- a has never been assigned a value */
process();
}
394
Error and Warning Messages
{
int a;
a = 6;
if(a || b) /* a is 6, therefore this is always true */
b++;
signed char c;
c = 0xFF;
As a signed 8-bit quantity, c can only be assigned values -128 to 127. The constant is equal to 255
and is outside this range. If you mean to set all bits in this variable, then use either of:
c = ~0x0;
c = -1;
which will set all the bits in the variable regardless of the size of the variable and without warning.
This warning can also be triggered by intermediate values overflowing. For example:
A quick check with your calculator reveals that 240 * 137 is 32880 which can easily be stored in
an unsigned int, but a warning is produced. Why? Because 240 and 137 and both signed int
values. Therefore the result of the multiplication must also be a signed int value, but a signed
int cannot hold the value 32880. (Both operands are constant values so the code generator can
evaluate this expression at compile time, but it must do so following all the ANSI rules.) The
following code forces the multiplication to be performed with an unsigned result:
395
Error and Warning Messages
Truncation may occur in this expression as the lvalue is of shorter type than the rvalue, e.g.:
char a;
int b, c;
a = b + c; /* conversion of int to char may result in truncation */
An attempt has been made to shift a value by a number of bits equal to or greater than the number of
bits in the data type. This will produce an undefined result on many processors. This is non-portable
code and is flagged as having undefined results by the C Standard, e.g.:
int input;
input < <= 33; /* oops -- that shifts the entire value out of input */
This is the result of comparing a bitfield with a value when the value is out of range of the bitfield.
For example, comparing a 2-bit bitfield to the value 5 will never be true as a 2-bit bitfield has a range
from 0 to 3, e.g.:
struct {
unsigned mask : 2; /* mask can hold values 0 to 3 */
} value;
int compare(void)
{
return (value.mask == 6); /* test can
}
A constant expression that was being evaluated involved a division by zero, e.g.:
396
Error and Warning Messages
A conditional branch (generated by an if, for, while statement etc.) always follows the same path.
This will be some sort of comparison involving a variable and a constant expression. For the code
generator to issue this message, the variable must have local scope (either auto or static local) and
the global optimizer must be enabled, possibly at higher level than 1, and the warning level threshold
may need to be lower than the default level of 0.
The global optimizer keeps track of the contents of local variables for as long as is possible during
a function. For C code that compares these variables to constants, the result of the comparison can
be deduced at compile time and the output code hard coded to avoid the comparison, e.g.:
{
int a, b;
a = 5;
/* this can never be false; always perform the true statement */
if(a == 4)
b = 6;
will produce code that sets a to 5, then immediately sets b to 6. No code will be produced for the
comparison if(a == 4). If a was a global variable, it may be that other functions (particularly
interrupt functions) may modify it and so tracking the variable cannot be performed.
This warning may indicate more than an optimization made by the compiler. It may indicate an
expression with missing or badly placed parentheses, causing the evaluation to yield a value different
to what you expected.
This warning may also be issued because you have written something like while(1). To produce
an infinite loop, use for(;;).
A similar situation arises with for loops, e.g.:
{
int a, b;
for(a=0; a!=10; a++) /* this loop must iterate at least once */
b = func(a);
In this case the code generator can again pick up that a is assigned the value 0, then immediately
checked to see if it is equal to 10. Because a is modified during the for loop, the comparison
code cannot be removed, but the code generator will adjust the code so that the comparison is not
performed on the first pass of the loop; only on the subsequent passes. This may not reduce code
size, but it will speed program execution.
397
Error and Warning Messages
(758) constant conditional branch: possible use of "=" instead of "==" (Code Generator)
There is an expression inside an if or other conditional construct, where a constant is being assigned
to a variable. This may mean you have inadvertently used an assignment = instead of a compare ==,
e.g.:
int a, b;
/* this can never be false; always perform the true statement */
if(a = 4)
b = 6;
will assign the value 4 to a, then , as the value of the assignment is always true, the comparison can
be omitted and the assignment to b always made. Did you mean:
int fred;
fred; /* this is valid, but has no effect at all */
Some devices require that special function register need to be read to clear hardware flags. To
accommodate this, in some instances the code generator does produce code for a statement which
only consists of a variable ID. This may happen for variables which are qualified as volatile.
Typically the output code will read the variable, but not do anything with the value read.
int a, b, c;
a = b,c; /* “b” has no effect, was that meant to be a comma? */
398
Error and Warning Messages
struct INPUT {
unsigned a : 3;
unsigned b : 5;
} input_grp;
input_grp.a = 0x12; /* 12h cannot possibly fit into a 3-bit wide object */
unsigned char c;
if(c > 300) /* oops -- how can this be true? */
close();
unsigned char c;
if(c >= 0)
will always be true, because an unsigned value can never be less than zero.
399
Error and Warning Messages
400
Error and Warning Messages
(777) can’t allocate space for opnd structure within object "*", (offs: *) (Assembler)
The assembler has run out of memory.
psect my_text,local,class=CODE,with=basecode
which will define a psect called my_text and place this in the same page as the psect basecode.
401
Error and Warning Messages
There are too many temporary labels in this assembler file. The assembler allows a maximum of
2000 temporary labels.
This is an internal compiler error. Contact HI-TECH Software technical support with details.
A number contained a character that was not part of the range 0-9 or 0-F.
END-of-FILE was encountered while scanning for an "endif" to match a previous "if".
An argument to a macro is not terminated. Note that angle brackets ("< >") are used to quote macro
arguments.
The syntax of a number is invalid. This can be, e.g. use of 8 or 9 in an octal number, or other
malformed numbers.
The LOCAL directive is only legal inside macros. It defines local labels that will be unique for each
invocation of the macro.
A symbol defined using the LOCAL assembler directive in an assembler macro is syntactically incor-
rect. Ensure that all symbols and all other assembler identifiers conform with the assembly language
of the target device.
402
Error and Warning Messages
mmm macro a1
move r0, #a1
LOCAL a1 ; oops -- the macro parameter cannot be used with local
ENDM
403
Error and Warning Messages
This is an internal compiler error. Contact HI-TECH Software technical support with details.
This is an internal compiler error. Contact HI-TECH Software technical support with details.
This is an internal compiler error. Contact HI-TECH Software technical support with details.
This is an internal compiler error. Contact HI-TECH Software technical support with details.
(816) duplicate ARCH specification in chipinfo file "*" at line * (Assembler, Driver)
The chipinfo file has a processor section with multiple ARCH values. Only one ARCH value is
allowed. If you have not manually edited the chip info file, contact HI-TECH Support with details.
An chip architecture (family) that is unknown was encountered when reading the chip INI file.
The chipinfo file has a processor section with multiple ZEROREG values. Only one ZEROREG
value is allowed. If you have not manually edited the chip info file, contact HI-TECH Support with
details.
404
Error and Warning Messages
405
Error and Warning Messages
_next:
move r0, #55
move [r1], r0
_next: ; oops -- choose a different name
The linker will issue this warning if the symbol (C or assembler) was defined multiple times in
different modules. The names of the modules are given in the error message. Note that C identifiers
often have an underscore prepended to their name after compilation.
406
Error and Warning Messages
The global flag is the default for a psect if its scope is not explicitly stated.
(864) argument to "size" psect flag must specify a positive constant (Assembler)
The parameter to the PSECT assembler directive’s size option must be a positive constant number,
e.g.:
psect spdata,class=RAM,size=400
; elsewhere:
psect spdata,class=RAM,size=500
407
Error and Warning Messages
The reloc flag to the PSECT assembler directive is different from a previous PSECT directive, e.g.:
psect spdata,class=RAM,reloc=4
; elsewhere:
psect spdata,class=RAM,reloc=8
(868) argument to "delta" psect flag must specify a positive constant (Assembler)
The parameter to the PSECT assembler directive’s DELTA option must be a positive constant number,
e.g.:
The ’DELTA’ option of a psect has been redefined more than once in the same module.
(870) argument to "pad" psect flag must specify a positive constant (Assembler)
The parameter to the PSECT assembler directive’s ’PAD’ option must be a non-zero positive integer.
(871) argument to "space" psect flag must specify a positive constant (Assembler)
The parameter to the PSECT assembler directive’s space option must be a positive constant number,
e.g.:
The space flag to the PSECT assembler directive is different from a previous PSECT directive, e.g.:
psect spdata,class=RAM,space=0
; elsewhere:
psect spdata,class=RAM,space=1
408
Error and Warning Messages
(880) invalid number of parameters. Use "* –HELP" for help (Driver)
Improper command-line usage of the of the compiler’s driver.
(884) please ensure you have write permissions to the configuration file (Driver)
The compiler was not successfully setup using the --setup driver option because the driver was
unable to access the XML configuration file. Ensure that you have write permission to this file. The
driver will search the following configuration files in order:
409
Error and Warning Messages
• the file /etc/htsoft.xml if the directory ’/etc’ is writable and there is no .htsoft.xml file
in your home directory
If none of the files can be located then the above error will occur.
(890) contact HI-TECH Software to purchase and re-activate this compiler (Driver)
The evaluation period of this demo installation of the compiler has expired. You will need to pur-
chase the compiler to re-activate it. If however you sincerely believe the evaluation period has ended
prematurely please contact HI-TECH technical support.
410
Error and Warning Messages
(895) can’t request and specify options in the one command (Driver)
The usage of the driver options --getoption and --setoption is mutually exclusive.
No on-chip or external memory ranges have been specified for the data space memory for the device
specified.
No on-chip or external memory ranges have been specified for the program space memory for the
device specified.
(899) can’t open option file "*" for application "*": * (Driver)
An option file specified by a --getoption or --setoption driver option could not be opened. If
you are using the --setoption option ensure that the name of the file is spelt correctly and that
it exists. If you are using the --getoption option ensure that this file can be created at the given
location or that it is not in use by any other application.
The subcomponent listed failed to execute. Does the file exist? Try re-installing the compiler.
(902) no chip name specified; use "* –CHIPINFO" to see available chip names (Driver)
The driver was invoked without selecting what chip to build for. Running the driver with the –
CHIPINFO option will display a list of all chips that could be selected to build for.
The usage of this option was incorrect. Confirm correct usage with –HELP or refer to the part of the
manual that discusses this option.
The application given to this option is not understood or does not belong to the compiler.
411
Error and Warning Messages
(907) unknown memory space tag "*" in "*" option specification (Driver)
A parameter to this memory option was a string but did not match any valid tags. Refer to the section
of this manual that describes this option to see what tags (if any) are valid for this device.
(913) "*" option may cause compiler errors in some standard header files (Driver)
Using this option will invalidate some of the qualifiers used in the standard header files resulting in
errors. This issue and its solution are detailed in the section of this manual that specifically discusses
this option.
(915) no room for arguments (Preprocessor, Parser, Code Generator, Linker, Objtohex)
The code generator could not allocate any more memory.
412
Error and Warning Messages
413
Error and Warning Messages
(949) start of checksum range must be less than end of range (Hexmate)
The -CKSUM option has been given a range where the start is greater than the end. The parameters
may be incomplete or entered in the wrong order.
(951) start of fill range must be less than end of range (Hexmate)
The -FILL option has been given a range where the start is greater than the end. The parameters may
be incomplete or entered in the wrong order.
414
Error and Warning Messages
(965) -STRPACK option not yet implemented, option will be ignored (Hexmate)
This option currently is not available and will be ignored.
415
Error and Warning Messages
(972) only modifiers "h" and "l" valid with this format (Parser)
Only modifiers h (short) and l (long) are legal with this printf format specifier.
416
Error and Warning Messages
struct IN {
int a, b;
};
enum IN {ONE=1, TWO}; /* oops -- IN is already defined */
union IN {
int a, b;
};
enum IN {ONE=1, TWO}; /* oops -- IN is already defined */
417
Error and Warning Messages
int a;
char a; /* oops -- what is the correct type? */
418
Error and Warning Messages
#define ZERO 0
#if FOO%ZERO /* this will have an assumed result of 0 */
#define INTERESTING
#endif
(994) some command-line options are disabled and compilation is delayed (Driver)
The compiler is operating in demo mode. Some command-line options are disabled, the compilation
speed will be slower.
(995) some command-line options are disabled, code size is limited to 16kB, compilation is
delayed (Driver)
The compiler is operating in demo mode. Some command-line options are disabled, the compilation
speed will be slower, and the maximum allowed code size is limited to 16kB.
419
Error and Warning Messages
(1016) missing argument* to "*" specification in chipinfo file "*" at line * (Driver)
(1017) extraneous argument* to "*" specification in chipinfo file "*" at line * (Driver)
There are too many attributes for the the listed specification in the chip configuration file.
(1018) illegal number of "*" specification* (* found; * expected) in chipinfo file "*" at line *
(Driver)
This attribute was expected to appear a certain number of times but it did not for this chip.
This attribute can only be defined once but has been defined more than once for this chip.
The chip configuration file contains an attribute that is not understood by this version of the com-
piler. Has the chip configuration file or the driver been replaced with an equivalent component from
another version of this compiler?
(1021) syntax error reading "*" value in chipinfo file "*" at line * (Driver)
The chip configuration file incorrectly defines the specified value for this device. If you are modify-
ing this file yourself, take care and refer to the comments at the beginning of this file for a description
on what type of values are expected here.
(1022) syntax error reading "*" range in chipinfo file "*" at line * (Driver)
The chip configuration file incorrectly defines the specified range for this device. If you are modify-
ing this file yourself, take care and refer to the comments at the beginning of this file for a description
on what type of values are expected here.
The chip configuration file contains a syntax error at the line specified.
420
Error and Warning Messages
(1032) use –HELP=<option> for usage of these command line options (Hexmate)
More detailed information is available for a specific option by passing that option to the HELP
option.
421
Error and Warning Messages
It looks like you need help. This advisory suggests how to get more information about the options
available to this application or the usage of these options.
The number of arguments to a function is unreasonable. This is an internal compiler error. Contact
HI-TECH Software technical support with details.
The length of the optional header in this COFF file was of an incorrect length.
When reading the type of data indicated in this message, it terminated before reaching its specified
length.
The specified length of the COFF string table is less than the minimum.
The number of symbols in the symbol table has exceeded the number indicated in the COFF header.
A record of the type specified failed to match its own checksum value.
While reading a file, one of the file’s records ended short of its specified length.
The type indicator of this record did not match any valid types for this file format.
422
Error and Warning Messages
423
Error and Warning Messages
(1088) function pointer "*" is used but never assigned a value (Code Generator)
A function call involving a function pointer was made, but the pointer was never assigned a target
address, e.g.:
void (*fp)(int);
fp(23); /* oops -- what function does fp point to? */
424
Error and Warning Messages
(1098) conflicting declarations for variable "*" (*:*) (Parser, Code Generator)
Differing type information has been detected in the declarations for a variable, or between a declaratin
and the definition of a variable, e.g.:
425
Error and Warning Messages
(1178) the "*" option has been removed and has no effect (Driver)
This option no longer exists in this version of the compiler and has been ignored. Use the compiler’s
–help option or refer to the manual to find a replacement option.
(1179) interrupt level for function "*" may not exceed * (Code Generator)
The interrupt level for the function specified is too high. Each interrupt function is assigned a
unique interrupt level. This level is considered when analysing the call graph and re-entrantly called
functions. If using the interrupt_level pragma, check the value specified.
426
Error and Warning Messages
(1190) FAE license only - not for use in commercial applications (Driver)
Indicates that this compiler has been activated with an FAE licence. This licence does not permit the
product to be used for the development of commercial applications.
427
Error and Warning Messages
A command line option that accepts additional parameters was given inappropriate data or insuffi-
cient data. For example an option may expect two parameters with both being integers. Passing a
string as one of these parameters or supplying only one parameter could result in this error.
This option has been specified too many times. If possible, try performing these operations over
several command lines.
The trial period for this compiler has expired. The compiler is now inoperable until activated with
a valid serial number. Contact HI-TECH Software to purchase this software and obtain a serial
number.
The code sequence specified in a -FIND option has been found at this address.
All find, replace and mask attributes in this option must be of the same byte width. Check the
parameters supplied to this option. For example finding 1234h (2 bytes) masked with FFh (1 byte)
will result in an error, but masking with 00FFh (2 bytes) will be Ok.
An unknown or unsupported INHX format has been requested. Refer to documentation for supported
INHX formats.
Data to this option was not entered as whole bytes. Perhaps the data was incomplete or a leading
zero was omitted. For example the value Fh contains only four bits of significant data and is not a
whole byte. The value 0Fh contains eight bits of significant data and is a whole byte.
428
Error and Warning Messages
An illegal length of data was given to this option. The value provided to this option exceeds the
maximum or minimum bounds required by this option.
(1205) using the configuration file *; you may override this with the environment variable
HTC_XML (Driver)
This is the compiler configuration file selected during compiler setup. This can be changed via
the HTC_XML environment variable. This file is used to determine where the compiler has been
installed.
(1207) some of the command line options you are using are now obsolete (Driver)
Some of the command line options passed to the driver have now been discontinued in this version
of the compiler, however during a grace period these old options will still be processed by the driver.
(1208) use –help option or refer to the user manual for option details (Driver)
An obsolete option was detected. Use –help or refer to the manual to find a replacement option that
will not result in this advisory message.
(1210) Visit the HI-TECH Software website (www.htsoft.com) for a possible update (Driver)
Visit our website to see if an update is available to address the issue(s) listed in the previous compiler
message. Please refer to the on-line self-help facilities such as the Frequently asked Questions or
search the On-line forums. In the event of no details being found here, contact HI-TECH Software
for further information.
The code sequence specified in a -FIND option has been found at this address.
The chipinfo file has a processor section with multiple ARCH values. Only one ARCH value is
allowed. If you have not manually edited the chip info file, contact HI-TECH Support with details.
429
Error and Warning Messages
430
Error and Warning Messages
void (*fp)(int);
fp(23); /* oops -- what function does fp point to? */
431
Error and Warning Messages
(1248) symbol (*) encountered with undefined type size (Code Generator)
The code generator was asked to position a variable, but the size of the variable is not known. This
is an internal compiler error. Contact HI-TECH Software technical support with details.
The compiler has been given contradictory paths for the output directory via any of the -O or
--OUTDIR options, e.g.
--outdir=../../ -o../main.hex
A token which could either be interpreted as a symbol or a hexadecimal value does not match any
previously defined symbol and so will be interpreted as the latter. Use a leading zero to avoid the
ambiguity, or use an alternate radix sepcifier such as 0x. For example:
mov a, F7h ; is this the symbol F7h, or the hex number 0xF7?
(1257) local variable "*" is used but never given a value (Code Generator)
An auto variable has been defined and used in an expression, but it has not been assigned a value
in the C code before its first use. Auto variables are not cleared on startup and their initial value is
undefined. For example:
void main(void) {
double src, out;
out = sin(src); /* oops -- what value were you expecting in src? */
The driver has been given contradictory options of compile for speed and compile for space, e.g.
--opt=speed,space
432
Error and Warning Messages
More than one definition for a macro with the same name has been encountered, e.g.
MACRO fin
ret
ENDM
MACRO fin ; oops -- was this meant to be a different macro?
reti
ENDM
A variable has been positioned such that it does not lie within any memory space for the device you
have selected. Either the address specified was incorrect, or the wrong device is selected, e.g.
(1263) multiple variables inside single #pragma abs_address block will overlap (Parser)
More than one variable definition has been placed inside a #pragma abs_address construct. Both
these variables will be assigned the same absolute address which may not have been the intention.
Is the end_abs_address misplaced? For example:
433
Error and Warning Messages
struct ONE {
unsigned a;
long b; /* ! */
} one;
struct TWO {
unsigned a;
unsigned b; /* ! */
} two;
struct ONE * oneptr;
oneptr = & two; /* oops -- was ONE meant to be the same struct as TWO? */
434
Error and Warning Messages
libr d c:\ht-pic\lib\pic704-c.lib
libr r lcd.lib
This command needs the name of a module (.obj file) after the library name.
435
Error and Warning Messages
436
Appendix C
Chip Information
437
Chip Information
438
Chip Information
439
Chip Information
440
Chip Information
441
Chip Information
442
Index
443
INDEX INDEX
444
INDEX INDEX
445
INDEX INDEX
446
INDEX INDEX
447
INDEX INDEX
448
INDEX INDEX
449
INDEX INDEX
450
INDEX INDEX
451
INDEX INDEX
452
INDEX INDEX
453
INDEX INDEX
454
INDEX INDEX
455
INDEX INDEX
456
INDEX INDEX
457
INDEX INDEX
458
INDEX INDEX
459
INDEX INDEX
460