Manual
Manual
PIC18 MCUs
Microchip Technology Inc.
Copyright (C) 2011 Microchip Technology Inc.
All Rights Reserved. Printed in Australia.
Produced on: September 27, 2011
Australian Design Centre
45 Colebard Street West
Acacia Ridge QLD 4110
Australia
web: http://www.microchip.com
Contents
Table of Contents 3
List of Tables 17
1 Introduction 19
1.1 Typographic conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3
CONTENTS CONTENTS
4
CONTENTS CONTENTS
5
CONTENTS CONTENTS
3 C Language Features 83
3.1 ANSI Standard Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
3.1.1 Divergence from the ANSI C Standard . . . . . . . . . . . . . . . . . . . . 83
3.1.2 Implementation-defined behaviour . . . . . . . . . . . . . . . . . . . . . . . 83
3.1.3 Non-ANSI Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.1.4 C18 Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.2 Processor-related Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.2.1 Processor Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.2.2 Device Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.2.3 Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.2.4 Configuration Fuses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.2.5 ID Locations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.2.6 Bit Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.2.7 EEPROM and Flash Runtime Access . . . . . . . . . . . . . . . . . . . . . 89
3.2.7.1 EEPROM Access . . . . . . . . . . . . . . . . . . . . . . . . . . 89
3.2.7.2 Flash Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
3.2.8 Using SFRs From C Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.2.8.1 Multi-byte SFRs . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.3 Supported Data Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.3.1 Radix Specifiers and Constants . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.3.2 Bit Data Types and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.3.3 Using Bit-Addressable Registers . . . . . . . . . . . . . . . . . . . . . . . . 96
3.3.4 8-Bit Integer Data Types and Variables . . . . . . . . . . . . . . . . . . . . 96
6
CONTENTS CONTENTS
7
CONTENTS CONTENTS
8
CONTENTS CONTENTS
9
CONTENTS CONTENTS
10
CONTENTS CONTENTS
11
CONTENTS CONTENTS
12
CONTENTS CONTENTS
13
CONTENTS CONTENTS
EXP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
FABS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
FLASH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
FMOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
FLOOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
FREXP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
GETCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
GETCHAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
GETS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
GMTIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
IDLOC_READ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
ISALNUM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
ISDIG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
ITOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
LABS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
LDEXP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
LDIV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
LOCALTIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
LOG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
LONGJMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
LTOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
MEMCMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
MEMMOVE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
MKTIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
MODF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
NOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
OS_TSLEEP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
POW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
PRINTF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
PUTCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
PUTCHAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
PUTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
QSORT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
RAND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
READTIMER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
RESET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
ROUND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
SETJMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
SIN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
14
CONTENTS CONTENTS
SLEEP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
SQRT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
SRAND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
STRCAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
STRCHR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
STRCMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
STRCPY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
STRCSPN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
STRLEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
STRNCAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
STRNCMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
STRNCPY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
STRPBRK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
STRRCHR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
STRSPN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
STRSTR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
STRTOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
STRTOL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
STRTOK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
TAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
TIME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
TOLOWER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
TRUNC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
UDIV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
ULDIV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
UNGETCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
UTOA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
VA_START . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
WRITETIMER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
XTOI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
15
CONTENTS CONTENTS
398... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
443... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
487... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
595... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
668... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
720... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
764... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
817... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
866... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
923... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
982... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
1039... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
1185... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
1234... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
1289... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
1350... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
0... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
Index 515
16
List of Tables
17
LIST OF TABLES LIST OF TABLES
18
Chapter 1
Introduction
19
Typographic conventions Introduction
20
Chapter 2
PICC18 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 Compiler for PIC18 MCUs 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”), PICC18, 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.
21
Invoking the Compiler PICC18 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.7, can also be used to specify library files to search.
PICC18 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
22
PICC18 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=18F242 -m \
--opt=all -g \
main.c isr.c
After it is saved, the compiler may be invoked with the command:
PICC18 @xyz.cmd
23
The Compilation Sequence PICC18 Command-line Driver
code -S
.as
generator
.lst --ASMLIST -C
assembler .obj
HLINK
24
PICC18 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.14 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.
25
The Compilation Sequence PICC18 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.
PICC18 --chip=18F242 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.
26
PICC18 Command-line Driver The Compilation Sequence
M ULTI - STEP COMPILATION The files in the previous example are to be compiled
using a multi-step compilation. The following could be used.
PICC18 --chip=18F242 --pass1 main.c
PICC18 --chip=18F242 --pass1 io.c
PICC18 --chip=18F242 -c mdef.as
PICC18 --chip=18F242 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.
27
Runtime Files PICC18 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.
28
PICC18 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.
29
Runtime Files PICC18 Command-line Driver
The C standard libraries contain a standardised collection of functions, such as string, math and
input/output routines. The range of these functions are described in Appendix A.
These libraries also contain C routines that are implicitly called by the compiler and which
typically perform tasks such as floating point operations or type conversions.
The standard library name format is stdlib-compat_mode-option.lpp, where compat_mode
is the compatibility mode: htc or c18; and option is any option that was used when building the
library, for example d32 for 32-bit doubles.
In addition to the C standard libraries, PICC18 automatically passes to the code generator a set of
p-code libraries which contain functions that are device dependent. Such routines may, for example,
access the EEPROM, or flash memory of the device.
The general form of the utility library names is picfamily-xp.lpp. The meaning of each
field is described by:
• The family name may be the same as a specific device name or be generic, e.g. pic18f4550
or pic18fxx31.
• The configuration digit, x, relates to errata information; each bit has the meaning:
– bit #0 is true for devices implementing EEDATA errata workaround for EEPROM reads.
– bit #1 is true for devices that implement additional NOPs when reading beyond program
space at -40C.
• The library type, p, is f for flash libraries and e for eeprom libraries. The library extension is
always lpp.
HI-TECH C Compiler for PIC18 MCUs has support for the MPLAB C18 peripheral library API. A
native HI-TECH library is linked when the compatibility mode is the default setting (see 3.1.4), and
a C18 version of this library is linked if the compiler is being run in C18 compatibility mode. These
two libraries are functionally identical and conform to the same API, but differ in the source syntax.
These libraries are linked in by default. To prevent them from being searched, the --RUNTIME=-plib
option must be used. See Section 2.6.55.
30
PICC18 Command-line Driver Runtime Files
Rather than the traditional method of linking in a generic, precompiled routine, HI-TECH C Com-
piler for PIC18 MCUs 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 out-
put of which is used to determine the requirements of the program. From this information PICC18
then “writes” the assembler code which will perform the startup sequence.
Both the driver and code generator are involved in generating the runtime startup code. The
driver takes care of device setup and this code is placed into a separate assembly startup file. The
code generator handles initialization of the C environment, such as clearing uninitialized C variables
and copying initialized C variables. This code is output along with the rest of the C program.
The runtime startup code is generated automatically on every compilation. If required, the as-
sembler file which contains some of the runtime startup code can be deleted after compilation by
using the driver option:
--RUNTIME=default,-keep
If the startup module is kept, it 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. The code produced by the code generator will be shown in the assembly list file
associated with the project.
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.55
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.
31
Runtime Files PICC18 Command-line Driver
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 psects used for storing these components are described in 3.8.1.
The runtime startup code will copy all the blocks of initial values from program memory to RAM
so the variables will contain the correct values before main() is executed. This action can 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
will fail.
•
Since auto objects are dynamically created, they require code to be positioned in the
function in which they are defined to perform their initialization. It is also possible that
their initial value changes on each instance of the function. As a result, initialized auto
objects do not use the data psects and are not considered by the runtime startup code.
Variables whose contents should be preserved over a reset, or even power off, should be qualified
with persistent, see Section 3.3.11.1. Such variables are linked at a different area of memory and are
not altered by the runtime startup code in any way.
32
PICC18 Command-line Driver Runtime Files
int output;
void main(void) { ...
Such uninitialized objects will only require space to be reserved in RAM where they will reside and
be accessed during program execution (runtime).
The psects used for storing these components are described in Section 3.8.1 and typically have a
name based on the initialism “bss” (Block Started by Symbol).
The runtime startup code will clear all the memory location occupied by uninitialized variables
so they will contain zero before main() is executed.
Variables whose contents should be preserved over a reset should be qualified with persistent.
See Section 3.3.11.1 for more information. Such variables are linked at a different area of memory
and are not altered by the run- time startup code in any way.
The block clear of all the bss psects (including the memory allocated by the code generator) can
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.
33
Runtime Files PICC18 Command-line Driver
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.
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
34
PICC18 Command-line Driver Debugging Information
the compiler cannot determine the exact format string, but can see that there are no
additional arguments to printf following the format string represented by mes. Thus,
the only valid format strings will not contain placeholders that print any arguments,
and a minimal version of printf will be generated and compiled. If the above code
was rewritten as:
the compiler will detect that the argument being printed has double type, thus the only
valid placeholders would be those that print floating point types, for example %e, %f and
%g.
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.
35
Compiler Messages PICC18 Command-line Driver
where * indicates the message number that was generated, will be printed, otherwise the message in
the requested language will be displayed.
36
PICC18 Command-line Driver Compiler Messages
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.
37
Compiler Messages PICC18 Command-line Driver
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.
38
PICC18 Command-line Driver Compiler Messages
The message environment variables, in turn, may be overridden by the driver options: --MSGFORMAT,
--WARNFORMAT and --ERRFORMAT, see Sections 2.6.31, 2.6.43 and 2.6.65. These options take a
string as their argument. The option strings are formatted, and can use the same placeholders, as
their variable counterparts.
T UT•RIAL
39
Compiler Messages PICC18 Command-line Driver
Notice that now all message follow a more uniform format and are displayed on a single
line.
The user now sets the environment variable HTC_WARN_FORMAT to be the following
string. (Under Windows, this can be performed via the Control Panel’s System panel.)
%a %n %l %f %s
and the project recompiled. The following output will be displayed.
parser 362 12 main.c redundant "&" applied to array (492)
attempt to position absolute psect "text" is illegal (error)
Notice that the format of the warning was changed, but that of the error message was
not. The warning format now follows the specification of the environment variable. The
application name (parser) was substituted for the %a placeholder, the message number
(362) substituted the %n placeholder, etc.
The option --ERRFORMAT="%a %n %l %f %s" is then added to the driver command
line and the following output is observed.
parser 362 12 main.c redundant "&" applied to array
linker 492 attempt to position absolute psect "text" is illegal
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.
40
PICC18 Command-line Driver PICC18 Driver Option Descriptions
Warnings may also be disabled by using the --MSGDISABLE option, see Section 2.6.42. This
option takes a comma-separated list of message numbers. Any warnings which are listed are disabled
and will never be issued, regardless of any warning level threshold in place. This option cannot be
used to disable error messages.
Some warning messages can also be disabled by using the warning disable pragma. This
pragma will only affect warnings that are produced by either parser or the code generator, i.e. errors
directly associated with C code. See Section 3.11.4.6 for more information on this pragma.
Error messages can also be disabled, however a slighty more verbose form of the command is
required to confirm the action required. To specify an error message number in the --MSGDISABLE
command, the number must be followed by :off to ensure that it is actually disabled. For example:
--MSGDISABLE=195:off will disable error number 195.
•
Disabling error or warning messages in no way fixes any potential problems reported
by the message. Always use caution when exercising this option.
41
PICC18 Driver Option Descriptions PICC18 Command-line Driver
Multi-letter, or word, options have two leading dash characters, e.g. --ASMLIST. (Because of the
double dash, you can determine that the option --ASMLIST, for example, is not a -A option followed
by the argument SMLIST.)
Some of these options define suboptions which typically appear as a comma-separated list fol-
lowing an equal character, =, e.g. --OUTPUT=hex,cof. The exact format of the options varies and
are described in detail in the following sections.
Some commonly used suboptions include default, which represent the default specification
that would be used if this option was absent altogether; all, which indicates that all the available
suboptions should be enabled as if they had each been listed; and none, which indicates that all
suboptions should be disabled. Some suboptions may be prefixed with a plus character, +, to indicate
that they are in addition to the other suboptions present, or a minus character “-”, to indicate that
they should be excluded. In the following sections, angle brackets, < >, are used to indicate optional
parts of the command.
See the –HELP option, Section 2.6.36, for more information about options and suboptions.
#define macro 1
placed at the top of each module compiled using this option, or -Dmacro=text which is equivalent
to:
will compile test.c with macros defined exactly as if the C source code had included the directives:
42
PICC18 Command-line Driver PICC18 Driver Option Descriptions
#define debug 1
#define buffers 10
The -E option also allows errors to be appended to an existing file by specifying an addition charac-
ter, +, at the start of the error filename, for example:
If you wish to compile several files and combine all of the errors generated into a single text file, use
the -E option to create the file then use -E+ when compiling all the other source files. For example,
to compile a number of files with all errors combined into a file called project.err, you could use
the -E option as follows:
Section 2.5 has more information regarding this option as well as an overview of the messaging
system and other related driver options.
43
PICC18 Driver Option Descriptions PICC18 Command-line Driver
the project name (see Section 2.1), and an extension of .sym. For example the option -Gtest.sym
generates a symbol file called test.sym. Symbol files generated using the -G option include source-
level information for use with source-level debuggers.
Note that all source files for which source-level debugging is required should be compiled with
the -G option. The option is also required at the link stage, if this is performed separately. For
example:
The --IDE option, see Section 2.6.38 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).
It is strongly advised not to use -I to add the compiler’s default include path, not only because
it is unnecessary but in the event that the build tool changes, the path specified here will be searched
prior to searching the new compiler’s default path.
This option has no effect for files that are included into assembly source using the INCLUDE
directive. See Section 4.3.11.4.
See Section 2.7 for use of this option in MPLAB IDE.
44
PICC18 Command-line Driver PICC18 Driver Option Descriptions
and passed to the code generator and linker, respectively. The case of the string following the option
is important for environments where filenames are case sensitive.
Thus the option -Lt when compiling for a 18F452 will, for example, specify the library filenames
pic86l-t.lpp and pic86l-t.lib. The option -Lxx will specify libraries called pic86l-xx.lpp
and pic86l-xx.lib. All libraries must be located in the LIB subdirectory of the compiler installa-
tion directory.
If you wish the linker to scan libraries whose names do not follow the above naming conven-
tion or whose locations are not in the LIB subdirectory, simply include the libraries’ names on the
command line along with your source files.
The commonly-used PICC-18 Standard compiler options -Ll, -Lf and -Lw should not
be used for altering the behaviour of the printf function. The library files correspond-
ing to these opptions are not provided with the PRO version of this compiler, and an
error will result if these options are used with creating these library sets. A custom
printf function is automatically generated by the compiler when required, as described
in section 2.3.4.
Take care with command-line options. The linker cannot interpret driver options; sim-
ilarly the command-line driver cannot interpret linker options. In most situations, it is
always the command-line driver, PICC18, that is being executed. If you need to add
alternate settings in the linker tab in an MPLAB Build options... dialogue, these
are the driver options (not linker options), but which are used by the driver to generate
the appropriate linker options during the linking process.
45
PICC18 Driver Option Descriptions PICC18 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 assembly code which contains user-defined
psects. 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 PICC18 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
that the psects should be linked so that one follows two, which follows three, and
46
PICC18 Command-line Driver PICC18 Driver Option Descriptions
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.
47
PICC18 Driver Option Descriptions PICC18 Command-line Driver
To change the directory in which all output and intermediate files are written, use the --OUTDIR
option, see Section 2.6.48. 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
48
PICC18 Command-line Driver PICC18 Driver Option Descriptions
49
PICC18 Driver Option Descriptions PICC18 Command-line Driver
In the case of code being assembled that was originally C source, the list file shows both the
original C code and the corresponding assembly code generated by the code generator. For both
C and assembly source code, a line number, the binary op-codes and addresses are shown. If the
assembler optimizer is enabled (default operation) the list file may differ from the original assem-
bly source code. The assembler optimizer may also simpify some expression and remove some
assembler directives from the listing file for clarity, although they are processed in the usual way.
Provided the link stage has successfully concluded, the listing file will be updated by the linker
so that it contains absolute addresses and symbol values. Thus you may use the assembler listing file
to determine the position of, and exact op codes corresponding to, instructions.
,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.
50
PICC18 Command-line Driver PICC18 Driver Option Descriptions
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 MPLAB IDE,
and makefiles.
51
PICC18 Driver Option Descriptions PICC18 Command-line Driver
Basic debugging with Microchip REALICE, ICD3, PICKIT2 and PICKIT3 are also supported
when --debugger=realice, --debugger=icd3, --debugger=pickit2 or --debugger=pickit3
is used.
See Section 2.7 for use of this option in MPLAB IDE.
52
PICC18 Command-line Driver PICC18 Driver Option Descriptions
byteselect or bytewrite. Which mode is selected will affect the code generated when writing
to the external data. In word write mode, dummy reads and writes may be added to ensure that an
even number of bytes are always written. In byte select or byte write modes dummy reads and writes
are not generated and can result in more efficient code. Note that this option does not in any way
pre-configure the device for operation in the selected mode.
See Section 2.7 for use of this option in MPLAB IDE.
53
PICC18 Driver Option Descriptions PICC18 Command-line Driver
PICC18 --help=warn
This will display more detailed information about the --WARN option, the available suboptions, and
which suboptions are enabled by default.
54
PICC18 Command-line Driver PICC18 Driver Option Descriptions
The list of all preprocessor macros (preprocessor icon) and the graphical memory usage map
(Linker icon) provide information that is not otherwise readily accessible.
See Section 2.7 for use of this option in MPLAB IDE.
55
PICC18 Driver Option Descriptions PICC18 Command-line Driver
56
PICC18 Command-line Driver PICC18 Driver Option Descriptions
57
PICC18 Driver Option Descriptions PICC18 Command-line Driver
58
PICC18 Command-line Driver PICC18 Driver Option Descriptions
If you wish to see the preprocessed source for the printf family of functions, do not use this
option. The source for this function is customised by the compiler, but only after the code generator
has scanned the project for printf usage. Thus, as the –PRE option stops compilation after the
preprocessor stage, the code generator will not execute and no printf code will be processed. If this
option is omitted, the preprocessed source for printf will be retained in the file doprnt.pre.
If you wish to see the preprocessed source for the printf family of functions, do not use this
option. The source for this function is customised by the compiler, but only after the code generator
has scanned the project for printf usage. Thus, as the –PRE option stops compilation after the
preprocessor stage, the code generator will not execute and no printf code will be processed. If this
option is omitted, the preprocessed source for printf will be retained in the file doprnt.pre.
#include <stdio.h>
add(arg1, arg2)
int * arg1;
int * arg2;
{
return *arg1 + *arg2;
}
59
PICC18 Driver Option Descriptions PICC18 Command-line Driver
PICC18 will produce test.pro containing the following declarations which may then be edited as
necessary:
--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.
60
PICC18 Command-line Driver PICC18 Driver Option Descriptions
This option is also used to specify RAM for far objects on PIC18 devices. These objects are
stored in the PIC18 extended memory. Any additional memory specified with this option whose
address is above the on-chip program memory is assumed to be extended memory implemented as
RAM.
For example, to indicate that RAM has been implemented in the extended memory space at
addresses 0x20000 to 0x20fff, use the following option.
--RAM=default,+20000-20fff
--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.
See Section 2.7 for use of this option in MPLAB IDE.
61
PICC18 Driver Option Descriptions PICC18 Command-line Driver
62
PICC18 Command-line Driver PICC18 Driver Option Descriptions
63
PICC18 Driver Option Descriptions PICC18 Command-line Driver
This option can also be used to remove an application from the build sequence. If the file param-
eter is specified as off, execution of the named application will be skipped. In most cases this is
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.62 --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.
64
PICC18 Command-line Driver PICC18 Driver Option Descriptions
65
MPLAB IDE v8 Universal Toolsuite Equivalents PICC18 Command-line Driver
1. Output directory
This selection uses the buttons and fields grouped in the bracket to specify an output directory
for files output by the compiler.
2. Include Search path
This selection uses the buttons and fields grouped in the bracket to specify include (header)
file search directories. See 2.6.6.
1. Define macros
The buttons and fields grouped in the bracket can be used to define preprocessor macros. See
Section 2.6.3.
2. Undefine macros
The buttons and fields grouped in the bracket can be used to undefine preprocessor macros.
See Section 2.6.15.
66
PICC18 Command-line Driver MPLAB IDE v8 Universal Toolsuite Equivalents
67
MPLAB IDE v8 Universal Toolsuite Equivalents PICC18 Command-line Driver
3 5
6
4
7
68
PICC18 Command-line Driver MPLAB IDE v8 Universal Toolsuite Equivalents
3. Preprocess assembly
This checkbox controls whether assembly source files are scanned by the preprocessor. See
Section 2.6.12.
4. Optimization settings
These controls are used to adjust the different optimizations the compiler employs. See Sec-
tion 2.6.47.
5. Identifier length
This selector is currently not implemented. See Section 2.6.10.
6. Verbose
This checkbox controls whether the full command-lines for the compiler applications are dis-
played when building. See Section 2.6.16.
7. Warning level
This selector allows the warning level print threshold to be set. See Section 2.6.64.
8. Operation Mode
This selector allows the user to force another available operating mode (e.g. Lite, Standard or
PRO) other than the default. See Section 2.6.41.
9. Address Qualifier
This selector allows the user to select the behavior of the address qualifier. See Section 2.6.18.
1. Runtime options
These checkboxes control the many runtime features the compiler can employ. See Section
2.6.55.
2. Fill
This field allows a fill value to be specified for unused memory locations. See Section 2.6.33.
3. Codeoffset
This field allows an offset for the program to be specified. See Section 2.6.24.
69
MPLAB IDE v8 Universal Toolsuite Equivalents PICC18 Command-line Driver
1 8
10
11
12
13
14 15
70
PICC18 Command-line Driver MPLAB IDE v8 Universal Toolsuite Equivalents
4. Checksum
This field allows the checksum specification to be specified. See Section 2.6.20.
5. Errata
This field allows the errata workarounds employed by the compiler to be controlled. See
Section 2.6.30.
6. Vectors
Not applicable.
7. Callgraph
Not applicable.
8. Debugger
This selector allows the type of hardware debugger to be chosen. See Section 2.6.26.
9. Trace type
Not yet implemented.
12. Frequency
Not applicable.
71
MPLAB IDE v8 Universal Toolsuite Equivalents PICC18 Command-line Driver
1
6
2
7
3
8
4
9
5
10
11
1. Memory model
Not applicable.
2. Size of Double
This selector allows the size of double types to be selected. See Section 2.6.27.
72
PICC18 Command-line Driver MPLAB X Universal Toolsuite Equivalents
3. Size of Float
This selector allows the size of float types to be selected. See Section 2.6.34.
5. RAM ranges
This field allows the default RAM (data space) memory used to be adjusted. See Section
2.6.53.
7. External memory
This selector allows the type of external memory access to be specified. See Section 2.6.29.
8. Instruction set
Not applicable.
9. Printf
Not applicable.
73
MPLAB X Universal Toolsuite Equivalents PICC18 Command-line Driver
1
2
The following dialogs and descriptions identify the mapping between the MPLAB X IDE dialog
controls and command-line options. As the plugin is universal across all HI-TECH compilers, not
all options are applicable for HI-TECH C Compiler for PIC18 MCUs.
If you are using MPLAB IDE v8, see Section 2.7.
2.8.1.1 Messages
These options relate to messages produced by the compiler (see Section 2.5 for more information).
See Figure 2.7 in conjunction with the following command line option equivalents.
1. Verbose:
This checkbox controls whether the full command-lines for the compiler applications are dis-
played when building. See Section 2.6.16.
2. Warning level:
This selector allows the warning level print threshold to be set. See Section 2.6.64.
74
PICC18 Command-line Driver MPLAB X Universal Toolsuite Equivalents
1. Address Qualifier:
This selector allows the user to select the behavior of the address qualifiers. See Section 2.6.18.
2.8.1.3 Operation
This option illustrated in Figure 2.9 relates to the operating mode of the compiler.
1. Operation Mode:
This selector allows the user to force another available operating mode (e.g. Lite or PRO)
other than the default. See Section 2.6.41.
2.8.1.4 Preprocessor
These options, shown in Figure 2.10, relate to preprocessor operation.
75
MPLAB X Universal Toolsuite Equivalents PICC18 Command-line Driver
1
2
3
4
5
1. Define macros:
The buttons and fields grouped in the bracket can be used to define preprocessor macros. See
Section 2.6.3.
2. Undefine macros:
The buttons and fields grouped in the bracket can be used to undefine preprocessor macros.
See Section 2.6.15.
3. Preprocess assembly:
This checkbox controls whether assembly source files are scanned by the preprocessor. See
Section 2.6.12.
4. Identifier length:
This selector is currently not implemented. See Section 2.6.10.
5. Include Directories:
This selection uses the buttons and fields grouped in the bracket to specify include (header)
file search directories. See Section 2.6.6.
2.8.1.5 Optimization
These options, shown in Figure 2.11, relate to optimizations performed by the compiler.
1. Optimization set:
This controls enables different optimizations the compiler employs. See Section 2.6.47.
76
PICC18 Command-line Driver MPLAB X Universal Toolsuite Equivalents
1
2
3
4
5
6
3. Assembly Files:
This control enables optimization of assembly source files. See Section 2.6.47.
4. Speed:
This control allows you to toggle between speed- or space-biased optimizations. See Sec-
tion 2.6.47.
5. Debug:
This control allows you to disable some optimizations so that generated code is better behaved
in debuggers. See Section 2.6.47.
6. Global Level:
This control allows you to enable the global C optimizer and adjust the optimization level. See
Section 2.6.47.
2.8.2.1 Data
These options, shown in Figure 2.12 relate to C data types and data memory.
77
MPLAB X Universal Toolsuite Equivalents PICC18 Command-line Driver
1
2
1
2
3
4
1. Size of Double:
This selector allows the size of the double type to be selected. See Section 2.6.27.
2. Size of Float:
This selector allows the size of the float type to be selected. See Section 2.6.34.
3. RAM ranges:
This field allows the default RAM (data space) memory used to be adjusted. See Section 2.6.53.
2.8.2.2 Report
These options, shown in Figure 2.13 relate to information printed after compilation.
78
PICC18 Command-line Driver MPLAB X Universal Toolsuite Equivalents
2.8.2.3 Runtime
All the widgets in Figure 2.14 correspond to suboptions of the –RUNTIME option, see Sec-
tion 2.6.55.
2.8.2.4 Code
These options, shown in Figure 2.15 relate to program memory.
1. External memory:
The control allows configuration of the external memory interface. See Section 2.6.29.
2. ROM ranges:
This field allows the default ROM (program space) memory used to be adjusted. See Sec-
tion 2.6.54.
2.8.2.5 Additional
These options, shown in Figure 2.16 relate to miscellaneous options.
79
MPLAB X Universal Toolsuite Equivalents PICC18 Command-line Driver
80
PICC18 Command-line Driver MPLAB X Universal Toolsuite Equivalents
1
2
3
4
5
6
7
2. Fill:
This field allows a fill value to be specified for unused memory locations. See Section 2.6.33.
3. Codeoffset:
This field allows an offset for the program to be specified. See Section 2.6.24.
4. Checksum:
This field allows the checksum specification to be specified. See Section 2.6.20.
5. Errata:
This allows customization of the errata workarounds applied by the compiler. See Sec-
tion 2.6.30.
6. Trace type:
Not yet implemented.
7. Extend address 0 in HEX file:
This option specifies that the intel HEX file should have initialization to zero of the upper
address. See Section 2.6.49.
81
MPLAB X Universal Toolsuite Equivalents PICC18 Command-line Driver
82
Chapter 3
C Language Features
HI-TECH C Compiler for PIC18 MCUs supports a number of special features and extensions to the
C language which are designed to ease the task of producing ROM-based applications. This chapter
documents the compiler options and special language features which are specific to the Microchip
PIC 18 family of processors.
83
ANSI Standard Issues C Language Features
where var must be an unsigned int. Rotates can be either left or right and of any number of bits.
Note that a rotate left of 1 bit is equivalent to a rotate right of 7 bits when dealing with byte-wide
variables, or a rotate right of 15 bits when dealing with 2-byte quantities.
•
Support for compatibility in version 9.80 of HI-TECH C Compiler for PIC18 MCUs is
beta only. Not all syntax may be supported and compliance with the C18 operation is
not guaranteed.
In C18 compatibility mode, the compiler will accept most C language extensions offered by MPLAB
C18 and many of the directives and instruction formats accepts by the internal C18 assembler. Sep-
arate assembly modules, that would normally be passed to MPASM, and the directives and syntax
that these files can contain, are not supported.
To provide further compatibility of legacy projects, a replacement MPLAB C18 driver (mcc18)
is provided HI-TECH C Compiler for PIC18 MCUs that mimics the operation of the MPLAB C18
84
C Language Features Processor-related Features
compiler executable. When executed, this replacement driver will automatically invoke the HI-
TECH compiler in the compatibility mode and transcode options to the HI-TECH equivalent. This
allows command line options, batch files, linker scripts or MPLAB IDE projects setup for MPLAB
C18 to use the HI-TECH compiler with virtually no modification. Legacy projects need only be
associated with, and call, the replacement MPLAB C18 driver to build using the HI-TECH compiler
in compatibility mode.
This manual only describes the operation of the compiler in HI-TECH compatibility mode. For
the meaning of language extensions and compiler operation in C18 compatibility mode, refer to the
MPLAB C Compiler for PIC18 MCUs compiler manual.
•
When you run the installer for this compiler, you have the option of converting your
existing MPLAB IDE projects configured to use the MPLAB C Compiler for PIC18
MCUs to the HI-TECH compiler. Once converted, these projects will use the HI-TECH
compiler in compatibility mode and the HI-TECH replacement compiler driver (mcc18)
will be called. At any time, you may re-run the compiler’s activation program from
the Windows Start menu to convert projects if you did not perform this action when
installing.
If you convert your C18 projects, this will mean that they will not use the installed
MPLAB C Compiler for PIC18 MCUs unless you revert the Location paths of the exe-
cutables in the Select Language Toolsuite dialog in the MPLAB IDE (v8), or the Built
Tool settings in the Embedded tab of the MPLAB X IDE Preferences dialog.
85
Processor-related Features C Language Features
From the command line, the same information can be obtained. Run the compiler you wish to
use and pass it the option --CHIPINFO (See Section 2.6.22). A list of all devices will be printed.
Additional code-compatible processors may be added by editing the picc-18.ini file in the
DAT directory. User-defined processors should be placed at the end of the file. The header of the
file explains how to specify a processor. Newly added processors will be available the next time you
compile by selecting the name of the new processor on the command line in the usual way.
3.2.3 Stack
The hardware stack on PIC18 devices is limited in depth and cannot be manipulated directly. It is
only used for function return address and cannot be used for program data. The compiler implements
a compiled stack for local data objects, see Section 3.4.1.1 for information on how this is achieved.
You must ensure that the maximum stack depth is not exceeded; otherwise, code may fail. Call-
ing too many nested functions may overflow the stack, and it is important to take into account
interrupts, which also use levels of the stack.
A call graph is provided by the code generator in the assembler list file. This will indicate the
stack levels at each function call and can be used as a guide to stack depth. The code generator may
also produce warnings if the maximum stack depth is exceeded, see Section 2.6.55.
Both of these are guides to stack usage. Optimizations and the use of interrupts can change the
stack depth used by a program over that determined by the compiler.
86
C Language Features Processor-related Features
where setting is a configuration setting descriptor, e.g. WDT, and state is a textual description
of the desired state, e.g. OFF. The value field is a numerical value that can be used in preference to
a descriptor. The value is assigned to the setting. For example,
One pragma can be used to program several settings by separating each setting-value pair with a
comma. For example, the above could be specified with one pragma, as in the following.
Rather than specify individual settings, the entire register may be programmed with one numer-
ical value, if you prefer, e.g.
The settings and values associated with each device can be determined from an HTML guide. Open
the file chipinfo.html, which is located in the DOCS directory of your compiler installation. Click
on your target device and it will show you the settings and values that are appropriate with this
pragma. Check your device datasheet for more information.
The compiler also has legacy support for the __CONFIG and __PROG_CONFIG macros which allow
configuration bit symbols or a configuration word value, respectively, to be specified. For example:
__CONFIG(2, BW8 & PWRTDIS & WDTPS1 & WDTEN); // specify symbols
or
You cannot use the symbols in the __PROG_CONFIG macro, nor can you use a literal value in the
__CONFIG macro.
Use the pragma in preference to the macros for new projects. To use these macros, ensure you
include <htc.h> in your source file. Symbols for the macros can be found in the .cfgdata fies
contained in the dat/cfgdata directory of your compiler installation directory.
Neither the config pragma, nor the macros, produce executable code and so should ideally be
placed outside function definitions.
87
Processor-related Features C Language Features
3.2.5 ID Locations
Some PIC18 devices have locations outside the addressable memory area that can be used for storing
program information, such as an ID number. The config pragma may also be used to place data
into these locations by using a special register name. The pragma is used in a manner similar to:
where X is the number (position) of the ID location, and value is the nibble or byte which is to be
positioned into that ID location. If the value is larger than the maximum value allowable for each
location on the target device, the value will be truncated and a warning message issued. The size of
each ID location value varies from device to device. See your device datasheet for more information.
For example:
will attempt fill the first two ID locations with 1 and 4. One pragma can be used to program several
locations by separating each register-value pair with a comma. For example, the above could also be
specified as:
The compiler also has legacy support for the __IDLOC macro, for example:
__IDLOC(15F01);
To use this macro, ensure you include <htc.h> in your source file.
Neither the config pragma, nor the __IDLOC macro, produce executable code and so should
ideally be placed outside function definitions.
88
C Language Features Processor-related Features
bsf _foo,6
To set or clear individual bits within integral type, the following macros could be used:
To perform the same operation as above, the bitset macro could be employed as follows:
bitset(foo,6);
#include <htc.h>
__EEPROM_DATA(0, 1, 2, 3, 4, 5, 6, 7);
The macro accepts eight parameters, being eight data values. Each value should be a byte in size.
Unused values should be specified as a parameter of zero. The macro may be called multiple times
to define the required amount of EEPROM data. It is recommended that the macro be placed outside
any function definitions.
The macro defines, and places the data within, a psect called eeprom_data. This psect is posi-
tioned by a linker option in the usual way. This macro is not used to write to EEPROM locations
during run-time.
There are functions to access the EEPROM at runtime. These are provided by the peripheral
library.
The function forms of these routines use the prototypes:
Read and return the byte location at addr in the EEPROM memory.
89
Processor-related Features C Language Features
EEPROM_WRITE(address, value);
To read a byte of data from an address in EEPROM memory, and store it in a variable:
variable=EEPROM_READ(address);
For convenience, __EEPROMSIZE predefines the number of bytes of EEPROM available on chip.
Read num_bytes bytes of flash memory starting from startaddr, storing them in the array specified
by flash_array.
Write num_bytes bytes of data from flash_array into flash memory starting at address start_addr.
90
C Language Features Processor-related Features
Write num_blocks blocks of data from flash_array into flash memory starting at address start_addr.
The block size is device dependent and is indicated in the device datasheet.
Note that when flash memory is written, the entire block that contains the new values must be
erased and then written as a whole. You need to ensure that the start and end address you specify in
these routines take these boundaries into account. If you only wish to write some of the locations in
the block, then you must read in the block and store it in a RAM array, modify the copy to include
the changes required, then write then modifed array back to flash. Similarly, when erasing flash
memory, you should erase entire blocks. Check your device datasheet for flash block sizes and exact
operation.
#include <htc.h>
void main(void)
{
PORTA = 0x00;
RA0 = 1;
91
Processor-related Features C Language Features
PORTAbits.RA2 = 1;
}
To confirm the names that are relevant for the device you are using, check the device specific header
file that <htc.h> will include for the definitions of each variable. These files will be located in
the include directory of the compiler and will have a name that represents the device. There is a
one-to-one correlation between device and header file name that will be included by <htc.h>, e.g.
when compiling for a PIC18F452 device the <htc.h> header file will include (among other files)
<pic18f452.h>.
For compatibility, an additional header file using a C18-style name is also shipped with the
compiler. This will #include the “pic” version of the same file. So, for the PIC18F452 device, the
file <p18f452.h> can be used for legacy projects.
Care should be taken when accessing some SFRs from C code or from assembly in-line with
C code. Some registers are used by the compiler to hold intermediate values of calculations, and
writing to these registers directly can result in code failure. The compiler does not detect when SFRs
have changed as a result of C or assembly code that writes to them directly. The list of registers used
by the compiler and further information can be found in Section 3.7.
SFRs associated with peripherals are not used by the compiler to hold intermediate results and
can be changed as you require. Always ensure that you confirm the operation of peripheral modules
from the device data sheet.
i = TMR0L;
i += TMR0H < < 8;
92
C Language Features Supported Data Types and Variables
Macros are also provided to perform common operations, like reading and writing the timer registers,
and which read the registers in the correct order. See the macros READTIMERx and WRITETIMERx in
Chapter A.
93
Supported Data Types and Variables C Language Features
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 Compiler for PIC18 MCUs.
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:
Defining and initializing a non-const array (i.e. not a pointer definition) with a string, for example:
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:
94
C Language Features Supported Data Types and Variables
95
Supported Data Types and Variables C Language Features
96
C Language Features Supported Data Types and Variables
sive. Unsigned short and unsigned int are 16-bit unsigned integer types, representing integral
values from 0 to 65,535 inclusive. All 16-bit integer values are represented in little endian format
with the least significant byte at the lower address.
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.
HI-TECH C Compiler for PIC18 MCUs supports two 24-bit integer types. short long are 24-bit
two’s complement signed integer types, representing integral values from -8,388,608 to +8,388,607
inclusive. Unsigned short long are 24-bit unsigned integer types, representing integral values
from 0 to 16,777,215 inclusive. All 24-bit integer values are represented in little endian format with
the least significant byte at the lower address.
Variables may be declared using the signed short long int and unsigned short long
int keyword sequences, respectively, to hold values of these types. When specifying a short
long int type, the keyword int may be omitted. Thus a variable declared as short long will
contain a signed short long int and a variable declared as unsigned short long will contain
an unsigned short long int.
HI-TECH C Compiler for PIC18 MCUssupports two 32-bit integer types. Long is a 32-bit two’s
complement signed integer type, representing integral values from -2,147,483,648 to +2,147,483,647
inclusive. The unsigned long type is a 32-bit unsigned integer type, representing the integral
values from 0 to 4,294,967,295 inclusive. All 32-bit integer values are represented in little endian
format with the least significant word and least significant byte at the lowest address. Long and
unsigned long occupy 32 bits as this is the smallest long integer size allowed by the ANSI standard
for C.
Variables may be declared using the signed long int and unsigned long int keyword se-
quences, respectively, to hold values of these types. Where only long int is used in the declaration,
the type will be signed long. When specifying this type, the keyword int may be omitted. Thus
a variable declared as long will contain a signed long int and a variable declared as unsigned
long will contain an unsigned long int.
97
Supported Data Types and Variables C Language Features
98
C Language Features Supported Data Types and Variables
where 23 is the number of bits taken up by the mantissa, to give 0.302447676659. Add one to this
fraction. The floating-point number is then given by:
−10 × 2124 × 1.302447676659 = 1×2.126764793256e + 37 × 1.302447676659≈ 2.77000e + 37
Variables may be declared using the float and double keywords, respectively, to hold values
of these types. Floating point types are always signed and the unsigned keyword is illegal when
specifying a floating point type. Types declared as long double will use the same format as types
declared as double.
struct {
unsigned lo : 1;
unsigned dummy : 6;
unsigned hi : 1;
} foo;
struct {
unsigned lo : 1;
unsigned dummy : 6;
unsigned hi : 1;
unsigned extra : 2;
} foo;
99
Supported Data Types and Variables C Language Features
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 lo : 1;
unsigned : 6;
unsigned hi : 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 lo : 1;
unsigned mid : 6;
unsigned hi : 1;
} foo = {1, 8, 0};
As PIC18 devices are little endian, the first bit defined will be the least 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:
struct {
unsigned lo : 1;
unsigned dummy : 6;
unsigned hi : 1;
} foo;
will produce a structure occupying 1 byte. If foo was ultimately linked at address 10H, the field lo
will be bit 0 of address 10H, hi will be at bit 7. The least significant bit of dummy will be bit 1 of
address 10H and the most significant bit of dummy will be at bit 6.
100
C Language Features Supported Data Types and Variables
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 initialized 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};
HI-TECH C Compiler for PIC18 MCUs supports the use of the ANSI type qualifiers const and
volatile.
The const type qualifier is used to tell the compiler that an object is read only and will not be
modified. If any attempt is made to modify an object declared const, the compiler will issue a
warning. User-defined objects declared const are placed in a special psects in the program space.
Obviously, a const object must be initialised when it is declared as it cannot be assigned a value at
any point at runtime. For example:
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:
101
Supported Data Types and Variables C Language Features
Volatile objects may be accessed using different generated code to non-volatile objects. For ex-
ample, when assigning a non-volatile object the value 1, the object may be cleared and then incre-
mented, but the same operation performed on a volatile object will load the W register with 1 and
then store this to the appropriate address.
void test(void) {
persistent int intvar; /* WRONG! */
... other code ...
}
because intvar is of class auto. To declare intvar as a persistent variable local to function
test(), write:
HI-TECH C Compiler for PIC18 MCUs also supports the keywords bank1, bank2 and bank3. These
keywords have been included to allow code to be easily ported from HI-TECH C Compiler for
PIC10/12/16 MCUs. These keywords are accepted by HI-TECH C Compiler for PIC18 MCUs, but
have no effect in terms of the object’s storage or how they are accessed. The --ADDRQUAL option has
no effect on these qualifiers in this version of the compiler.
102
C Language Features Supported Data Types and Variables
Objects qualified near cannot be auto or parameters to a function, but can be qualified static,
allowing them to be defined locally within a function, as in:
void myFunc(void) {
static near unsigned char local_near;
Note that the compiler may store some temporary objects in the common memory, so not all of this
space may be available for user-defined variables.
If the PICC18 option, --STRICT is used, this type qualifier is changed to __near.
For the operation of this qualifier in C18 compatibility mode (see Section 3.1.4), refer to the
MPLAB C Compiler for PIC18 MCUs manual.
103
Supported Data Types and Variables C Language Features
Objects qualified far cannot be auto or parameters to a function, but can be qualified static,
allowing them to be defined locally within a function, as in:
void myFunc(void) {
static far unsigned char local_far;
If the PICC18 option, --STRICT is used, this type qualifier is changed to __far.
Note that not all devices support extending their memory space in this way and the far qualifier
is not applicable to all PIC18 devices. For those devices that can extend their memory, the ad-
dress range where the additional memory will be mapped must first be specified with the --RAM
option, see 2.6.53. For example, to map additional data memory from 20000h to 2FFFFh use
--RAM=default,+20000-2FFFF.
For the operation of this qualifier in C18 compatibility mode (see Section 3.1.4), refer to the
MPLAB C Compiler for PIC18 MCUs manual.
104
C Language Features Supported Data Types and Variables
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
Bear 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.
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.
105
Supported Data Types and Variables C Language Features
– Address is an offset into psect mediumconst which is linked into any 64k block, but with
an offset into this block equal to the size of the data space memory;
– Addresses above the top of the data space access program space; other addresses access
data space;
• A 24-bit pointer capable of accessing the entire data space memory and the entire program
space;
– Bit #21 determines destination: this bit set indicates a data space address; clear indicates
a program space address
– This is the default pointer configuration as it can point to any object.
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).
106
C Language Features Supported Data Types and Variables
T UT•RIAL
DYNAMIC POINTER SIZES A program in the early stages of development contains the
following code;
void main(void) {
int i, *ip;
ip = &i;
}
The code generator is able to automatically allocate the variable i to the access bank,
which it does. The code generator notes that the pointer ip only points to the access
bank variable i, so this pointer is made an 8-bit wide access bank pointer.
As the program is developed, other near variables are defined and allocated space in the
access bank. A point is reach at which the variable i will no longer fit in the access bank
and it is automatically moved to banked RAM. When the program is next compiled, the
pointer ip will automatically become a 16-bit pointer to all of the data 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. HI-TECH specific qualifiers, like near and far, do not need to be used to indicate
pointer targets, and should be avoided. The non-use of these qualifiers will result in more portable
and readable code, and lessen the chance of extraneous warnings being issued by the compiler.
T UT•RIAL
107
Supported Data Types and Variables C Language Features
void main(void) {
const char in_table[20] = { /* values */ };
char * cp;
cp = &in_table;
}
If the array above is the only const data in the program, then there are 20 bytes of const
data used in the program. In this instance, the code generator will make the pointer, cp,
a one byte wide pointer to objects in the program space.
Later, the program is changed and another const array is added to the code:
const char out_table[200] = { /* values */ };
As the total size of const data for this program now exceeds 255 bytes, the size of any
pointer that can access const objects will be made 2 bytes long. Even if the pointer, cp,
is not assigned the address of this new array, out_table, its size will increase.
For pointer that are accessing const objects, the address contained within the pointer is an offset into
the psect used to store the const data. For programs defining less than 256 bytes of const data, this
data is placed into a psect called smallconst; for larger const data amounts up to 64 kbytes, the
psect is called mediumconst.
The size of pointers that can access const data indicates the storage size of the address. However,
PIC18 devices use a 3-byte table pointer SFR to access data in the program space and all 3 bytes
of this register must be loaded and valid to access program space data. To avoid having to load all
3 bytes of this register with each program space access, the code generator also keeps track of the
number of table pointer registers that are modified during the program. These active table pointer
registers will be re-loaded with each program space access. The non-active registers are assumed to
retain the value assigned to them in the runtime startup code.
•
Any hand-written assembler code, or C code that writes to the table pointer SFRs di-
rectly, must ensure that the contents of any non-active table registers are preserved.
Saving both TBLPTRH and TBLPTRU will ensure that this requirement is met.
108
C Language Features Supported Data Types and Variables
it can dereference both memory spaces, and the address will be encoded so that the target memory
space can be determined at runtime.
A 16-bit mixed space pointer is encoded such that if it holds an address that is higher than the
highest general purpose RAM address, it holds the address of a program space object; all other
address reference objects in the data space.
A 24-bit mixed space pointer is encoded such that if bit number #21 is set, it contains the address
of an object in the data space; all other addresses hold the address of a program space object.
T UT•RIAL
109
Storage Class and Object Placement C Language Features
defined. Function pointers are 16-bits wide for memory spaces less the 64 kbytes in size. For larger
program space memory sizes, these then swap to 3 bytes in size.
It should be stressed that direct calls to functions are not affected by the size of function pointers.
The size of function pointers only affect code calling functions indirectly. The addresses for all code
labels are always shown in the map file as an untruncated 3-byte address regardless of the pointer
size determined by the code generator.
The size of function pointers will affect the number of table pointer registers considered active.
110
C Language Features Storage Class and Object Placement
variables are assigned memory: a psect is used to hold the stack and this psect is placed into the
available data memory by the linker. The psect used to hold the compiled stack is called cstack,
and like with non-auto variable psects, the psect basename is always used in conjunction with a
linker class name to indicate the RAM bank in which the psect will be positioned. See Section 3.8.1
for the limitations associated with where this psect can be linked.
The auto variables defined in a function will not necessarily be allocated memory in the order
declared, in contrast to parameters which are always allocated memory based on their lexical order.
In fact, auto variables for one function may be allocated in many RAM banks.
The the standard qualifiers: const and volatile may both be used with auto variables and
these do not affect how they are positioned in memory. This implies that a local const-qualified
object is still an auto object and, as such, will be allocated memory in the compiled stack in the data
space memory, not in the program memory like with non-auto const objects.
The compiler will try to locate the stack in one data bank, but if this fills (i.e. if the compiler
detects that the stack has become too large for the free space in a bank), it can build up the stack into
several components (each with their own psect) and link each in a different bank.
Each auto object is referenced in assembly code using a special symbol defined by the code
generator. If you write assembly code that accesses auto variables defined in C source code, you
must use these symbols, which are discussed in Section 3.10.3.
Compiled Stack Operation A compiled stack consists of fixed memory areas that are usable by
each function’s stack-based variables. When a compiled stack is used, functions are not re-entrant
since stack-based variables in each function will use the same fixed area of memory every time the
function is invoked.
Fundamental to the generation of the compiled stack is the call graph, which defines a tree-like
hierarchy of function calls, i.e it shows what functions may be called by each function.
There will be one graph produced for each root function. A root function is typically not called,
but which is executed via other means and contains a program entry point. The function main() is
an example of a root function that will be in every project. Interrupt functions, which are executed
when a hardware interrupt occurs, are another example.
Figure 3.1 shows sections of a program being analyzed by the code generator to form a call
graph. In the original source code, the function main() calls F1(), F2() and F3(). F1() calls F4(),
but the other two functions make no calls. The call graph for main() indicates these calls. The
symbols F1, F2 and F3 are all indented one level under main. F4 is indented one level under F1.
This is a static call graph which shows all possible calls. If the exact code for function F1()
looked like:
int F1(void) {
if(PORTA == 44)
return F4();
111
Storage Class and Object Placement C Language Features
main {
F1(…);
F2(…); Call graph
F3(…);
} main
F1
F4
code F2
F1 { generator F3
F4(…); isr
} F5
F6
isr {
F5(…); Analysis of program
F6(…);
}
return 55;
}
the function F4() will always appear in the call graph, even though it is conditionally executed in
the actual source code. Thus, the call graph indicates all functions, even those that might be called.
In the diagram, there is also an interrupt function, isr(), and it too has a separate graph gener-
ated.
The term main-line code is often used, and refers to any code that is executed as a result of the
main() function being executed. In the above figure, F1(), F2(), F3() and F4() are only ever
called by main-line code.
The term interrupt code refers to any code that is executed as a result of an interrupt being
generated, in the above figure, F5() and F6() are called by interrupt code.
Figure 3.2 graphically shows an example of how the compiled stack is formed.
Each function in the program is allocated a block of memory for its parameter, auto and tem-
porary variables. Each block is referred to as an auto-parameter block (APB). The figure shows the
APB being formed for function F2(), which has two parameters, a and b, and one auto variable, c.
112
C Language Features Storage Class and Object Placement
a
int aa , int
F2(int int bb ) { F2
b
char c ; c
} 2 Analysis of call graph
main
F1
main F4
F3 F2
compiled F1
stack F2 F3
F4 isr
F5
isr
F6
F5 F6
The parameters to the function are first grouped in an order strictly determined by the lexical
order in which they appear in the source code. These are then followed by any auto objects, however
the auto objects may be placed in any order. So we see memory for a is followed by that for b and
lastly, c.
Once these variables have been grouped, the exact location of each object is not important at this
point and we can represent this memory by one block — the APB for this function.
The APBs are formed for all functions in the program. Then, by analyzing the call graph, these
blocks are assigned positions, or bases values, in the compiled stack.
Memory can be saved if the following point is observed: If two functions are never active at the
same time, then their APBs can be overlapped.
In the example shown in the figure, F4() and F1() are active at the same time, in fact F1() calls
F4(). However F2(), F3() and F1() are never active at the same time; F1() must return before
F2() or F3() can be called by main(). The function main() will always be active and so its APB
can never overlap with that of an other function.
In the compiled stack, you can see that the APB for main() is allocated unique memory. The
blocks for F1(), F2() and F3() are all placed on top of each other and the same base value in the
compiled stack, however the memory taken up by the APBs for F1() and F4() are unique and do
not overlap.
Our example also has an interrupt function, isr(), and its call graph is used to assemble the
113
Storage Class and Object Placement C Language Features
APBs for any interrupt code in the same way. Being the root of a graph, isr() will always be
allocated unique memory, and the APBs for interrupt functions will be allocated memory following.
The end result is a block of memory which forms the compiled stack. This block can then be
placed into the device’s memory by the linker.
For devices with more than one bank of data memory, the compiled stack may be built up into
components, each located in a different memory bank. The compiler will try to allocate the com-
piled stack in one bank, but if this fills, it will consider other banks. The process of building these
components of the stack is the same, but each function may have more than one APB and these will
be allocated to one of the stack components based on the remaining memory in the component’s
destination bank.
Human readable symbols are defined by the code generator which can be used to access auto
and parameter variables in the compiled stack from assembly code, if required. See Section 3.10.4
for full information between C domain and assembly domain symbols.
All static variables have permanent storage duration, even those defined inside a function which
are “local static” variables. Local static variables only have scope in the function or block in which
they are defined, but unlike auto variables, their memory is reserved for the entire duration of the
program. Thus they are allocated memory like other non-auto variables. Any static variable may
be accessed by other functions via pointers since they have permanent duration.
Variables which are static are guaranteed to retain their value between calls to a function,
unless explicitly modified via a pointer.
Variables which are static and which are initialized only have their initial value assigned once
during the program’s execution. Thus, they may be preferable over initialized auto objects which are
assigned a value every time the block in they are defined begins execution. Any initialized static
variables are initialized in the same way as other non-auto initialized objects by the runtime startup
code, see Section 2.3.2.
Local objects which are static are assigned an assembly symbol which consists of the function
name followed by an @ symbol and the variable’s lexical name, e.g. main@foobar will be the
assembly identifier used for the static variable foobar defined in main().
Non-local static objects use their lexical name with a leading underscore character, e.g. _foobar
will be the assembly identifier used for this object. However, if there is more than one such static
object defined, then subsequent objects will use the name of the file that contains them and their
lexical name separated by an @ symbol, e.g. lcd@foobar would be the assembly symbol for the
static variable foobar defined in lcd.c.
114
C Language Features Storage Class and Object Placement
will declare a variable called Portvar located at 06h in the data memory. The compiler will re-
serve storage for this object and will equate the variable’s identifier to that address. The compiler-
generated assembler will include a line similar to:
No auto variables can be made absolute as they are located in a compiled stack. See Section 3.4.1.1.
Absolute variables cannot be initialized.
The compiler does not make any checks for overlap of absolute variables with other absolute
variables, so this must be considered when choosing the variable locations. There is no harm in
defining more than one absolute variable to live at the same address if this is what you require. The
compiler will not locate ordinary variables over the top of absolutes, so there is no overlap between
these objects.
Both initialized and uninitialized const objects can be made absolute. That latter is useful when
you only need to define a label in program memory without making a contribution to the output file.
115
Functions C Language Features
3.5 Functions
In some situations, the code associated with a function is output more than once. See Section 3.9.4
from more information.
116
C Language Features Functions
Using this construct with interrupt functions will not alter the position of the interrupt context
saving code that precedes the code associated with the interrupt function body. See also Section
2.6.24.
#asm
GLOBAL ?_extReadFn
?_extReadFn EQU 0x20
#endasm
117
Functions C Language Features
The names “argument” and “parameter” are often used interchangeably, but typically an argu-
ment is the actual value that is passed to the function and a parameter is the variable defined by the
function to store the argument.
The compiler will either pass arguments in the W register, or in the auto-parameter block (APB)
of the called function. If the first parameter is one byte in size, it is passed in the W register. All other
parameters are passed in the APB. This applies to basic types and to aggregate types, like structures.
The parameters are grouped along with the function’s auto variables in the APB and are placed
in the compiled stack. See Section 3.4.1.1 for detailed information on the compiled stack. The
parameter variables will be referenced as an offset from the symbol ?_function, where function is
the name of the function in which the parameter is defined (i.e. the function that is to be called).
Unlike auto variables, parameter variables are allocated memory strictly in the order in which
they appear in the function’s prototype. This means that the parameters will always be placed in
the same memory bank even if the other auto variables for that function have been allocated across
multiple banks.
The parameters for functions that take a variable argument list (defined using an ellipsis in the
prototype) are placed in the parameter memory, along with named parameters.
Take, for example, the following ANSI-style function.
The function test() will receive the argument for b in its function auto-parameter block and that
for a in the W register. A call to this function:
test(xyz, 8);
In this example, the parameter b is held in the memory locations ?_test (Least Significant Byte)
and ?_test+1 (Most Significant Byte) which are on the compiled stack. You may also see this same
location referenced as test@b, which is an alternate symbol.
The exact code used to call a function, or the code used to access a parameters from within a
function, can always be examined in the assembly list file. See Section 2.6.19 for the option that
generates this file. This is useful if you are writing an assembly routine that must call a function
with parameters, or accept arguments when it is called. The above example does not consider data
memory banking or program memory paging, which may require additional instructions.
118
C Language Features Operators
int return_16(void){
return 0x1234;
}
MOVLW 34h
MOVWF (?_return_16)
MOVLW 12h
MOVWF (?_return_16)+1
RETURN
3.6 Operators
HI-TECH C Compiler for PIC18 MCUs supports all the ANSI operators. The exact results of some
of these are implementation defined. The following sections illustrate code produced by the com-
piler.
119
Operators C Language Features
type. The conversion is to a “larger” type so there is no loss of information. Even if the operands
have the same type, in some situations they are converted to a different type before the operation.
This conversion is called integral promotion. HI-TECH C Compiler for PIC18 MCUs performs
these integral promotions where required. If you 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.
unsigned char count, a=0, b=50;
if(a - b < 10)
count++;
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:
if((unsigned int)(a - b) < 10)
count++;
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.
unsigned char count, c;
c = 0x55;
if( ~c == 0xAA)
count++;
If c contains the value 55h, it often assumed that ~c will produce AAh, however the result is FFAAh
and so the comparison above would fail. The compiler may be able to issue a mismatched compari-
son 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 Compiler for PIC18 MCUs will not perform the integral promotion so as
to increase the code efficiency. Consider the following example.
120
C Language Features Operators
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.
An 8-bit addition is more efficient than a 16-bit addition and so 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.
121
Register Usage C Language Features
#include <htc.h>
void getInput(void) {
ZERO = 0x1; // do not write using C code
c = read();
#asm
bcf ZERO_bit ; do not write using in-line assembly code
#endasm
process(c);
}
HI-TECH C is unable to interpret the meaning of in-line assembly code that is encountered in C
code. Nor does it associate a variable mapped over an SFR to the actual register itself. Writing to an
SFR register using either of these two methods will not flag the register as having changed and may
lead to code failure.
122
C Language Features Psects
3.8 Psects
When the code generator outputs code and data objects, it does so into a number of standard “pro-
gram sections”, referred to as psects. A psect is just a block of something: a block of code; a block
of data etc. By having everything inside a psect, all these blocks can be easily recognized and sorted
by the linker, even though they have come from different modules.
One of the main jobs of the linker is to group all the psects from the entire project and place
these into the available memory for the device.
A psect can be created in assembly code by using the PSECT assembler directive (see Section
4.3.10.3). The code generator uses this directive to direct assembly code it produces into the appro-
priate psect.
[bit]psectBaseNameCLASS[div]
where psectBaseName is the base name of the psect, such as bss.The CLASS is a name derived
from the linker class (see Section 5.7.2) in which the psect will be linked, e.g. BANK0. The prefix
bit is used if the psect holds bit variables. So there may be psects like: bssBANK0, bssBANK1 and
bitbssBANK0 defined by the compiler to hold the uninitialized variables.
If a psect has to be split into two ranges, then the letters l (elle) and h are used as div to indicate
if it is the lower or higher division. A psect would be split if memory in the middle of a bank has been
reserved, or is in some way not available to position objects. If an absolute variable is defined and
is located anywhere inside a memory range, that range will need to be split to ensure that anything
in the psects located there do not overwrite the absolute object. Thus you might see bssBANK0l and
bssBANK0h psects if a split took place.
The contents of these psects are described below, listed by psect base name.
123
Psects C Language Features
cinit Used by the C initialization runtime startup code. Code in this psect is output by the code
generator along with the generated code for the C program (look for it in the project’s assembly
list file) and does not appear in the runtime startup assembly module.
This psect can be linked anywhere in the program memory, provided they does not interfere
with the requirements of other psects. (It should not cross a 4000h address boundary for
devices where this is a published errata.)
const These psects hold objects that are declared const and string literals which are not modifiable.
Used when the total amount of const data in a program exceeds 64k.
This psect can be linked anywhere in the program memory provided it does not interfere with
the requirements of other psects.
eeprom_data Used to store data to be programmed into the EEPROM data area.
Do not change the default linker options relating to this psect.
end_init Used by initialization code in the startup.as module that transfers control to the main
function. (It should not cross a 4000h address boundary for devices where this is a published
errata.)
idata These psects contain the ROM image of any initialised variables. These psects are copied
into the data psects at startup. In this case, the class name is used to describe the class of the
corresponding RAM-based data psect. These psects will be stored in program memory, not
the data memory space.
This psect can be linked anywhere in the program memory, provided it does not interfere with
the requirements of other psects.
124
C Language Features Psects
init Used by initialisation code in the startup.as module. This code deals with setting up the
target device.
This psect can be linked anywhere in the program memory provided it does not interfere with
the requirements of other psects. (It should not cross a 4000h address boundary for devices
where this is a published errata.)
intcode Is the psect which contains the executable code for the default or high-priority interrupt
service routine. This psect is linked to interrupt vector at address 08H.
Do not change the default linker options relating to this psect. See Section 2.6.24 if you want
to move code when using a bootloader.
intcodelo Is the psect which contains the executable code for the low-priority interrupt service rou-
tine. This psect is linked to interrupt vector at address 018H.
Do not change the default linker options relating to this psect. See Section 2.6.24 if you want
to move code when using a bootloader.
mediumconst These psects hold objects that are declared const and string literals which are not
modifiable. Used when the total amount of const data in a program exceeds 255 bytes, but
does not exceed 64k.
This psect can be linked anywhere in the lower 64k of program memory provided it does not
interfere with the requirements of other psects.
powerup This contains executable code for the standard or user-supplied power-up routine.
Do not change the default linker options relating to this psect.
smallconst These psects hold objects that are declared const and string literals which are not mod-
ifiable. Used when the total amount of const data in a program is less than 255 bytes.
This psect can be linked anywhere in the program memory, provided it does not cross a 100h
boundary or interfere with the requirements of other psects.
textn Is a global psect used for executable code and library functions. n is a number. The code
associated with each function will be placed a unique text psect.
These psects can be linked anywhere in the program memory, provided they do not interfere
with the requirements of other psects. (It should not cross a 4000h address boundary for
devices where this is a published errata.)
125
Interrupt Handling in C C Language Features
cstack These psects contain the compiled stack. On the stack are auto, temporary and parameter
variables for the entire program. See Section 3.4.1.1 for information on the compiled stack.
These psects may be linked anywhere in their targeted memory bank and should not overlap
access bank memory.
data These psects contain the RAM image of any initialized variables. These psects may be linked
anywhere in their targeted memory bank and should not overlap access bank memory.
nv These psects are used to store variables qualified persistent. They are not cleared or otherwise
modified at startup. These psects may be linked anywhere in their targeted memory bank, but
should not overlap access bank memory.
long tick_count;
void interrupt tc_int(void){
126
C Language Features Interrupt Handling in C
++tick_count;
}
It is up to the user to determine and set the priority levels associated with each interrupt source on
the PIC18 devices. Defining a low-priority interrupt function does not put the PIC into interrupt-
priority mode.
Low- and high-priority interrupt functions have their own separate areas of memory in which
to save context, thus a high-priority interrupt function may interrupt a low-priority interrupt
function with no loss of data. The high-priority interrupt can also employ the devices’ shadow
registers to enable rapid context switching during the entry and exit of the service routine.
The interrupt_level pragma may be used with either or both interrupt functions in the
usual way.
127
Interrupt Handling in C C Language Features
Any objects saved by software are automatically restored by software before the interrupt function
returns. The order of restoration is the reverse to that used when context is saved.
The RETFIE instruction placed at the end of the interrupt code will reload the program counter
and the program will return to the location at which it was when the interrupt occurred. If the shadow
registers were used to save context, a RETFIE f instruction is used to indicate that the contents of
the shadow registers should be reloaded to their corresponding register.
Never use this macro to re-enable interrupts inside the interrupt function itself. Interrupts are au-
tomatically re-enabled by hardware on execution of the RETFIE instruction. Re-enabling interrupts
inside an interrupt function may result in code failure.
128
C Language Features Interrupt Handling in C
Main-line code will call the original function’s output, and the interrupt will call the duplicated
function’s output. The duplication takes place only in the called function’s output; there is no du-
plication of the C source code itself. The duplicated code and data uses different symbols and are
allocated different memory, so are fully independent.
This is similar to the process you would need to undertake if this feature was not implemented in
the compiler: the C function could be duplicated by hand, given different names and one called from
main-line code; the other from the interrupt function. However, you would have to maintain both
functions, and the code would need to be reverted if it was ported to a compiler which did support
reentrancy.
The compiler-generated duplicate will have unique identifiers for the assembly symbols used
within it. The identifiers consists of the same name used in the original output prefixed with the
symbol i1.
The output of the function called from main-line code will not use any prefixes and the assembly
names will be those normally used.
To illustrate, in a program the function main calls a function called input. This function is also
called by an interrupt function.
Examination of the assembly list file will show assembly code for both the original and dupli-
cate function outputs. The output corresponding to the C function input() will use the assembly
label _input. The corresponding label used by the duplicate function will be i1_input. If the
original function makes reference to a temporary variable, the generated output will use the symbol
??_input, compared to ??i1_input for the duplicate output. Even local labels within the function
output will be duplicated in the same way. The call graph, in the assembly list file, will show the
calls made to both of these functions as if they were independently written. These symbols will also
be seen in the map file symbol table.
This feature allows the programmer to use the same source code with compilers that use either
reentrant or non-reentrant models. It does not handle cases where functions are called recursively.
Code associated with library functions are duplicated in the same way. This also applies to
implicitly called library routines, such as those that perform division or floating-point operations
associated with C operators.
129
Interrupt Handling in C C Language Features
#pragma interrupt_level 1
The pragma should be placed before the definition of the function that is not to be duplicated. The
pragma will only affect the first function whose definition follows.
For example, if the function read() is only ever called from main-line code when the interrupts
are disabled, then duplication of the function can be prevented if it is also called from an interrupt
function as follows.
#pragma interrupt_level 1
int read(char device)
{
// ...
}
void main(void) {
TRISB = 0x80; // Only RB7 will interrupt on change
IPEN = 1; // Interrupt priorities enabled
PEIE = 1; // enable peripheral interrupts
RBIP = 0; // make this a low priority interrupt
RBIE = 1; // enable PORTB change interrupt
RBIF = 0; // clear any pending events
GIEL = 1; // enable low-priority interrupts
while(1)continue; // sit here and wait for interrupt
}
void interrupt low_priority b_change(void){
if(RBIE && RBIF){
130
C Language Features Mixing C and Assembly Code
• select a name (label) for the routine so that its corresponding C identifier is valid
• ensure that the routine’s label is globally accessible, i.e. from other modules
• select an appropriate equivalent C prototype for the routine on which argument passing can be
modelled
• optionally, use a signature value to enable type checking of parameters when the function is
called
• Limit arguments and return values to single byte-sized objects (Assembly routines may not
define variables that reside in the compiled stack. Use global variables for additional argu-
ments.
A mapping is performed on the names of all C functions and non-static global variables. See
3.10.3 for a description of mappings between C and assembly identifiers.
131
Mixing C and Assembly Code C Language Features
T UT•RIAL
C- CALLABLE ASSEMBLY ROUTINES The following example goes through the steps
of creating an assembly routine. A mapping is performed on the names of all C functions
and non-static global variables. See Section 3.10.4 for a complete description of
mappings between C and assembly identifiers.
An assembly routine is required which can add an 8-bit quantity passed to the routine
with the contents of PORTB and return this as an 8-bit quantity.
Most compiler-generated executable code is placed in psects called textn, where n is
a number. (see Section 3.8.1). We will create our own text psect based on the psect the
compiler uses. Check the assembly list file to see how the text psects normally appear.
You may see a psect such as the following generated by the code generator.
PSECT text0,local,class=CODE,reloc=2
T UT•RIAL
See Section 4.3.10.3 for detailed information on the flags used with the PSECT assembler
directive. This psect is called text0. It is flagged local, which means that it is distinct
from other psects with the same name. It lives in the CODE class. This flag is important
as it means it will be automatically placed in the area of memory set aside for code.
With this flag in place, you do not need to adjust the default linker options to have
the psect correctly placed in memory. The last option, the reloc value, is also very
important. This indicates that the psect must start on an even address boundary. The
PIC18 program memory space is byte addressable and instructions must be aligned on
an even address.
We simply need to choose a different name, so we might choose the name mytext, as
the psect name in which we will place out routine, so we have:
PSECT mytext,local,class=CODE,reloc=2
T UT•RIAL
Let’s assume we would like to call this routine add in the C domain. In assembly
domain we must choose the name _add as this then maps to the C identifier add. If
we had chosen add as the assembly routine, then it could never be called from C code.
The name of the assembly routine is the label that we will place at the beginning of the
assembly code. The label we would use would look like this.
132
C Language Features Mixing C and Assembly Code
_add:
T UT•RIAL
We need to be able to call this from other modules, some make this label globally
accessible, by using the GLOBAL assembler directive (Section 4.3.10.1).
GLOBAL _add
T UT•RIAL
char add(char);
T UT•RIAL
Check the assembly list file for the signature value of such a function. Signature values
are not mandatory, but allow for additional type checking to be made by the linker. We
determine that the following SIGNAT directive (Section 4.3.10.21) can be used.
SIGNAT _add,4217
T UT•RIAL
133
Mixing C and Assembly Code C Language Features
#include <pic18.inc>
GLOBAL _add ; make _add globally accessible
SIGNAT _add,4217 ; tell the linker how it should be called
; everything following will be placed into the mytext psect
PSECT mytext,local,class=CODE,delta=2
; our routine to add WREG to PORTB and return the result
; W is loaded by the calling function
_add:
BANKSEL (PORTB) ; select the bank of this object
ADDWF BANKMASK(PORTB),w ; add parameter to port
; the result is already in the required location (W)
; so we can just return immediately
RETURN
T UT•RIAL
To compile this, the assembly file must be preprocessed as we have used the C prepro-
cessor #include directive. See Section 2.6.12.
To call an assembly routine from C code, a declaration for the routine must be pro-
vided. This ensures that the compiler knows how to encode the function call in terms of
parameters and return values.
Here is a C code snippet that declares the operation of the assembler routine, then calls
the routine.
134
C Language Features Mixing C and Assembly Code
is not syntactically part of the C program, and thus it does not obey normal C flow-of-control rules,
however you can easily include multiple instructions with this form of in-line assembly.
The asm() statement is used to embed a single assembler instruction. This form looks and be-
haves like a C statement, however each instruction must be encapsulated within an asm() statement.
•
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.
The following example shows both methods used to rotate a byte left through carry:
When using in-line assembly code, great care must be taken to avoid interacting with compiler-
generated code. If in doubt, compile your program with the PICC18 -S option and examine the
assembly code generated by the compiler.
IMPORTANT NOTE: the #asm and #endasm construct is not syntactically part of the C program,
and thus it does not obey normal C flow-of-control rules. For example, you cannot use a #asm block
with an if statement and expect it to work correctly. If you use in-line assembler around any C
constructs such as if, while, do etc. then you should use only the asm("") form, which is a C
statement and will correctly interact with all C flow-of-control structures.
int foo;
135
Mixing C and Assembly Code C Language Features
GLOBAL _foo
movwf _foo
If the assembler is contained in a different module, then the GLOBAL assembler directive should be
used in the assembly code to make the symbol name available, as above. If the object is being
accessed from in-line assembly in another module, then an extern declaration for the object can be
made in the C code, for example:
This declaration will only take effect in the module if the object is also accessed from within C code.
If this is not the case then, an in-line GLOBAL assembler directive should be used. Care should be
taken if the object is defined in a bank other than 0. The address of a C object includes the bank
information which must be stripped before the address can be used in most PIC18 instructions. The
exceptions are the movff and lsfr instructions. Failure to do this may result in fixup errors issued
by the linker. If in doubt as to writing assembler which access C objects, write code in C which
performs a similar task to what you intend to do and study the assembler listing file produced by the
compiler.
•
C identifiers are assigned different symbols in the output assembly code so that an as-
sembly identifier cannot conflict with an identifier defined in C code. If assembly pro-
grammers choose identifier names that do not begin with an underscore, these identifiers
will never conflict with C identifiers. Importantly, this implies that the assembly identi-
fier, i, and the C identifier i relate to different objects at different memory locations.
136
C Language Features Mixing C and Assembly Code
The symbols in this header file look similar to the identifiers used in the C domain when including
<htc.h>, e.g. PORTA, EECON1 etc. They are different symbols in different domains, but will map to
the same memory location.
Bits within registers are defined as the registerName,bitNumber. So for example, RA0 is
defined as PORTA,0.
Here is an example of an assembly module that uses SFRs.
#include <pic18.inc>
GLOBAL _setports
PSECT text,class=CODE,local,reloc=2
_setports:
MOVLW 0xAA
BANKSEL (PORTA)
MOVWF BANKMASK(PORTA)
BANKSEL (PORTB)
BSF RB1
If you wish to access register definitions from assembly that is in-line with C code, different defini-
tions need to be used, but these are already available once you include the <htc.h> header file for
the C part of the module.
The symbols used for register names will be the same as those defined by <pic18.inc>; how-
ever, the names assigned to bit variables within the registers will include the suffix _bit. So for
example, the example given previously could be rewritten as in-line assembly as follows.
#include <htc.h>
#asm MOVLW 0xAA
BANKSEL (PORTA)
MOVWF BANKMASK(PORTA)
BANKSEL (PORTB)
BSF RB1_bits
#endasm
Care must be taken to ensure that you do not destroy the contents of registers that are holding
intermediate values of calculations. Some registers are used by the compiler and writing to these
registers directly can result in code failure. The compiler does not detect when SFRs have changed
as a result of assembly code that writes to them directly. The list of registers used by the compiler
and further information can be found in Section 3.7.
137
Mixing C and Assembly Code C Language Features
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-03FFhx3
for an 18F452 device, showing that addresses 210h through 22F were reserved from this
class range.
138
C Language Features Preprocessing
Variables can be defined in assembly code if required, but in some instances it is easier to do so in
C source code, in other cases, the symbols may need to be accessable from both assembly and C
source code.
A problem can occur if there is a variable defined in C code, but is never referenced throughout
the entire the C program. In this case, the code generator may remove the variable believing it is
unused. If assembly code is relying on this definition an error will result.
To work around this issue, HI-TECH C Compiler for PIC18 MCUs also searches assembly-
derived object files for symbols which are undefined. These will typically be symbols that are used,
but not defined, in assembly code. The code generator is informed of these symbols, and if they
are encountered in the C code the variable is automatically marked as being volatile. This is the
equivalent of the programmer having qualified the variable as being volatile in the source code,
see Section 3.3.10. Variables qualified as volatile will never be removed by the code generator,
even if they appear to be unused throughout the program.
T UT•RIAL
3.11 Preprocessing
All C source files are preprocessed before compilation. Assembler files can also be preprocessed if
the -P command-line option is issued, see Section 2.6.12.
139
Preprocessing C Language Features
/* 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.5), in assembly source code if the -P command-line option is issued, see Section 2.6.12.
All comments are removed by the C preprocessor before being passed to the parser application.
140
C Language Features Preprocessing
141
Preprocessing C Language Features
142
C Language Features Preprocessing
where keyword is one of a set of keywords, some of which are followed by certain options.
A list of the keywords is given in Table 3.9. Those keywords not discussed elsewhere are detailed
below.
•
Note that the warning level must be set to -1 or below for this option to have any visible
effect. See Section 2.6.64.
143
Preprocessing C Language Features
144
C Language Features Preprocessing
where routineName is the C equivalent name of the function or routine whose register usage is
being defined, and registerList is a space-separated list of registers names, as shown in Table
3.10. The pragma must be placed after the declaration for the assembly routine whose register usage
is being specified.
Those registers not listed are assumed to be unused by the function or routine. The code generator
may use any of these 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 recognized. A blank list indicates that the specified function or routine uses no registers.
145
Preprocessing C Language Features
For example, a routine called _search is written in assembly code. In the C source, we may
write:
extern void search(void);
#pragma regsused search wreg status fsr0
to indicate that this routine used the W register, STATUS and FSR0.
146
C Language Features Preprocessing
•
This pragma should not be used with user-defined functions; the code generator must
be aware of how to generator code for those functions specified as inline.
T UT•RIAL
D ISABLING A WARNING The following example shows the warning associated with
qualifying an auto object being disabled, number 348.
void main(void)
{
#pragma warning disable 348
near int c;
#pragma warning enable 348
147
Preprocessing C Language Features
/* etc */
}
int rv(int a)
{
near int c;
/* etc */
}
which will issue only one warning associated with the second definition of the auto
variable c. Warning number 348 is disabled during parsing of the definition of the auto
variable, c, inside the function main.
altst.c: 35: (348) auto variable "c" should not be qualified (warning)
This same affect would be observed using the following code.
void main(void)
{
#pragma warning push
#pragma warning disable 348
near int c;
#pragma warning pop
/* etc */
}
int rv(int a)
{
near int c;
/* etc */
}
Here the state of the messaging system is saved by the warning push pragma. Warning
348 is disabled, then after the source code which triggers the warning, the state of the
messaging system is retrieved by the use of the warning pop pragma.
The warning error/warning pragma It is also possible to change the type of some messages.
This is only possible by the use of the warning pragma and only affects messages generated by the
parser or code generator. The position of the pragma is only significant for the parser, i.e. a parser
message number may have its type changed, then reverted back around a section of the code to target
specific instances of the message. Specific instances of a message produced by the code generator
cannot be individually controlled. The pragma will remain in force during compilation of the entire
module.
148
C Language Features Linking Programs
T UT•RIAL
The following shows the warning produced in the previous example being converted to
an error for the instance in the function main().
void main(void)
{
#pragma warning error 348
near int c;
#pragma warning warning 348
/* etc */
}
int rv(int a)
{
near int c;
/* etc */
}
Compilation of this code would result in an error, and as with any error, this will force
compilation to cease after the current module has concluded, or the maximum error
count has been reached.
149
Linking Programs C Language Features
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
and a library file, the linker will not search the libraries 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 to preprocess assembler files as the library assembler files often contain C preprocessor
directives.
150
C Language Features Linking Programs
T UT•RIAL
It is sometimes necessary to write assembly language routines which are called from C
using an extern declaration. Such assembly language functions should include a signa-
ture which is compatible with the C prototype used to call them. The simplest method of
determining the correct signature for a function is to write a dummy C function with the
same prototype and compile it to assembly language using the PICC18 -S option. For
example, suppose you have an assembly language routine called _widget which takes
two int arguments and returns a char value. The prototype used to call this function
from C would be:
extern char widget(int, int);
Where a call to _widget is made in the C code, the signature for a function with two int
arguments and a char return value would be generated. In order to match the correct
signature the source code for widget needs to contain an assembler SIGNAT pseudo-op
which defines the same signature value. To determine the correct value, you would write
the following code:
char widget(int arg1, int arg2)
{
}
and compile it to assembly code using
PICC18 -S x.c
The resultant assembly code includes the following line:
SIGNAT _widget,8249
The SIGNAT pseudo-op tells the assembler to include a record in the .obj file which
associates the value 8249 with symbol _widget. The value 8249 is the correct signature
for a function with two int arguments and a char return value. If this line is copied into
the .as file where _widget is defined, it will associate the correct signature with the
function and the linker will be able to check for correct argument passing. For example,
if another .c file contains the declaration:
extern char widget(long);
then a different signature will be generated and the linker will report a signature mis-
match which will alert you to the possible existence of incompatible calling conventions.
151
Standard I/O Functions and Serial I/O C Language Features
152
Chapter 4
Macro Assembler
The Macro Assembler included with HI-TECH C Compiler for PIC18 MCUs assembles source files
for PIC18 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.
153
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.58.
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.
154
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 assembly produced using the -O assembler option. Thus if both
-A and -O are used with an assembly source file, the file will be optimized and rewritten, with-
out the usual conversion to an object file.
The output file, when this option is used, is a valid assembly file that can be passed to the as-
sembler. This differs to the assembly list file produced by the assembler when the -L assembler
option is used.
-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 picc-18.ini and can be
found in the DAT directory of the compiler distribution.
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. Use of the option in this form has a similar effect as the
same option used with command-line driver. See Section 2.5 for more information.
Specifying a digit as argument has a similar effect, only it allows selection of pre-set
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 when an assembly list file is requested (see assembler option -L), the listing
format is pageless, i.e. the assembly 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 ASPIC18 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.
155
Assembler Options Macro Assembler
-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.
An assembly listing file contains additional fields, such as the address and opcode fields, which
are not part of the assembly source syntax, hence these files cannot be passed to the assembler
for compilation. See the assembler -A option for generating processed assembly source files
that can be used as source files in subsequent compilation.
-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.
-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.10.20.
You can also add your own processors to the compiler via the compiler’s chipinfo file.
-Twidth This option allows specification of the assembly list file width, in characters. width
should be a decimal number greater than 41. The default width is 80 characters.
-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, i.e. it
should only be used with hand-written assembler source files.
-W[!]warnlevel This option allow the warning threshold level to be set. This will limit the number
of warning messages produce when the assembler is executing. The effect of this option is
similar to the command-line driver’s --WARN option, see Section 2.6.64. See Section 2.5 for
more information.
-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 assembler option will prevent the local
symbols from being included in the object file, thereby reducing the file size.
156
Macro Assembler HI-TECH C Assembly Language
Notice that first two instruction have the RAM access bit (bit 8 of the op-code) cleared, but that it is
set in the last two instructions.
The retfie instruction may be followed by “f” (no comma) to indicate that the shadow registers
should be retrieved and copied to their corresponding registers on execution.
157
HI-TECH C Assembly Language Macro Assembler
The compiler also supports the use of the PIC10/12/16 compiler pseudo instructions LJMP and
FCALL. These map to a regular GOTO and CALL PIC18 instruction, respectively. This support allows
for easier porting of assembly code from PIC10/12/16 devices to the PIC18 architecture. Avoid
using these pseudo instructions in projects developed for PIC18 devices.
loadfsr 2,1FFh
which will load FSR2 with the value 1FFh. This macro should be used in preference to the lfsr
instruction.
The BANKMASK macro can also be used to mask an address for using in a file register instruc-
tion. On all PIC18 devices, it performs a bitwise AND operation with the value 0xFF. Do not use
this macro with operands that should represent a full banked address, for example with the MOVFF
instruction.
4.3.4 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.
158
Macro Assembler HI-TECH C Assembly Language
4.3.4.1 Delimiters
All numbers and identifiers must be delimited by white space, non-alphanumeric characters or the
end of a line.
4.3.5 Comments
An assembly comment is initiated with a semicolon that is not part of a string or character constant.
If the assembly file is first processed by the C preprocessor, see Section 2.6.12, then it may also
contain C or C++ style comments using the standard /* ... */ and // syntax.
159
HI-TECH C Assembly Language Macro Assembler
4.3.6 Constants
4.3.6.1 Numeric Constants
The assembler performs all arithmetic with signed 32-bit precision.
The default radix for all numbers is 10. Other radices may be specified by a trailing base specifier
as given in Table 4.3.
Hexadecimal numbers must have a leading digit (e.g. 0ffffh) to differentiate them from identi-
fiers. Hexadecimal digits are accepted in either upper or lower case.
Note that a binary constant must have an upper case B following it, as a lower case b is used for
temporary (numeric) label backward references.
In expressions, real numbers are accepted in the usual format, and are interpreted as IEEE 32-bit
format.
4.3.7 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
160
Macro Assembler HI-TECH C Assembly Language
$
?$_12345
goto $
will represent code that will jump to itself and form an endless loop. By using this symbol and an
offset, a relative jump destination to be specified.
The address represented by $ is a word address and thus any offset to this symbol represents a
number of instructions. For example:
goto $+1
movlw 8
movwf _foo
161
HI-TECH C Assembly Language Macro Assembler
#include <pic18.inc>
to the assembler source file. (Assembly header files use the .inc extension.) Note that the file must
be included using a C pre-processor directive and hence the option to pre-process assembly files must
be enabled when compiling, see Section 2.6.12. This header file contains appropriate commands to
ensure that the header file specific for the target device is included into the source file.
These header files contain EQU declarations for all byte or multi-byte sized registers and #define
macros for named bits within byte registers.
frank:
movlw 1
goto fin
simon44: clrf _input
Here, the label frank will ultimately be assigned the address of the mov instruction, and simon44 the
address of the clrf instruction. Regardless of 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.
Like variables, labels have scope. By default, they may be used anywhere in the module in which
they are defined. They may be used by code above their definition. To make a label accessible in
other modules, use the GLOBAL directive. See Section 4.3.10.1 for more information.
4.3.8 Expressions
The operands to instructions and directives are comprised of expressions. Expressions can be made
up of numbers, identifiers, strings and operators.
162
Macro Assembler HI-TECH C Assembly Language
163
HI-TECH C Assembly Language Macro Assembler
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.
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 is used
to define a psect. It takes as arguments a name and an optional comma-separated list of flags. See
Section 4.3.10.3 for full information on psect definitions. 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 rbss psect.
PSECT text,class=CODE
adjust:
goto clear_fred
increment:
incf _fred
PSECT bss,class=BANK0,space=1
fred:
DS 2
PSECT text,class=CODE
clear_fred:
164
Macro Assembler HI-TECH C Assembly Language
clrf _fred
return
Note that even though the two blocks of code in the text psect are separated by a block in the bss
psect, the two text psect blocks will be contiguous when loaded by the linker. In other words,
the incf _fred instruction will be followed by the clrf instruction in the final output. The actual
location in memory of the text and bss 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.10.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.10.2 END
END is optional, but if present should be at the very end of the code defined in the module. It will
terminate the assembly process, 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 entry point
(address) of the program. Whether this is of any use will depend on the type of output debug file
being generated and the target platform. It is typically most useful for hosted systems, where an
application program may not be located at the reset vector.
For example, if start_label is defined at the reset vector:
END start_label
165
HI-TECH C Assembly Language Macro Assembler
166
Macro Assembler HI-TECH C Assembly Language
4.3.10.3 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.
• 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.
167
HI-TECH C Assembly Language Macro Assembler
• 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.
• 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.
• 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
168
Macro Assembler HI-TECH C Assembly Language
4.3.10.4 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.
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.10.5 EQU
This pseudo-op defines a symbol and equates its value to an expression. For example
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.10.6.
4.3.10.6 SET
This pseudo-op is equivalent to EQU except that allows a symbol to be re-defined. For example
thomas SET 0h
169
HI-TECH C Assembly Language Macro Assembler
4.3.10.7 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.
4.3.10.8 DW
DW operates in a similar fashion to DB, except that it assembles expressions into words. Example:
DW -1, 3664h, ‘A’, 3777Q
4.3.10.9 DS
This directive reserves, but does not initialize, memory locations. The single argument is the number
of bytes to be reserved. Examples:
alabel: DS 23 ;Reserve 23 bytes of memory
xlabel: DS 2+3 ;Reserve 5 bytes of memory
4.3.10.10 DABS
This directive allows one or more bytes of memory to be reserved at the specified address. The
general form of the directive is:
DABS memory_space,address,bytes
where memory_space is a number representing the memory space in which the reservation will
take place, address is the address at which the reservation will take place, and bytes is the
number of bytes that is to be reserved. This directive differs to the DS directive in that it does not
allocate space at the current location in the current psect, but instead can be used to reserve memory
at any location.
The memory space number is the same as the number specified with the space flag option to
psects. Devices with a single flat memory space will typically always use 0 as the space value;
devices with separate code and data spaces typically use 0 for the code space and 1 for the data
space.
The code generator issues a DABS directive for every user-defined absolute C variable, or for
variables that have been allocated an address by the code generator.
170
Macro Assembler HI-TECH C Assembly Language
4.3.10.11 FNCALL
This directive takes the form:
FNCALL fun1,fun2
FNCALL is usually used in compiler generated code. It tells the linker that function fun1 calls function
fun2. This information is used by the linker when performing call graph analysis. If you write
assembler code which calls a C function, use the FNCALL directive to ensure that your assembler
function is taken into account. For example, if you have an assembler routine called _fred which
calls a C routine called foo(), in your assembler code you should write:
FNCALL _fred,_foo
4.3.10.12 FNROOT
This directive tells the assembler that a function is a root function and thus forms the root of a call
graph. It could either be the C main() function or an interrupt function. For example, the C main
module produce the directive:
FNROOT _main
171
HI-TECH C Assembly Language Macro Assembler
;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:
storem MACRO arg1,arg2
movlw &arg2
movwf &arg1
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:
movlw 2
movwf tempvar
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.
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. If it is desired to include a
comma (or other delimiter such as a space) in an argument then angle brackets < and > may be used
to quote the argument. In addition 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:
172
Macro Assembler HI-TECH C Assembly Language
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.11.3,
4.3.10.15 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.10.16 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.
ALIGN 2
173
HI-TECH C Assembly Language Macro Assembler
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.10.17 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
addwf fred,w
ENDM
will expand to
addwf fred,w
addwf fred,w
addwf fred,w
PSECT idata_0
IRP number,4865h,6C6Ch,6F00h
DW number
ENDM
PSECT text0
PSECT idata_0
DW 4865h
DW 6C6Ch
DW 6F00h
PSECT text0
174
Macro Assembler HI-TECH C Assembly Language
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,delta=2
IRPC char,ABC
DB ’char’
ENDM
PSECT text
PSECT romdata,class=CODE,delta=2
DB ’A’
DB ’B’
DB ’C’
PSECT text
4.3.10.19 BANKSEL
This directive can be used to generate code to select the bank of the operand. The operand should be
the symbol or literal address of an object that resides in the data memory.
The generated code will use a MOVLB instruction.
For example:
MOVLW 20
BANKSEL (_foobar) ; select bank for next file instruction
MOVWF BANKMASK(_foobar) ; write data and mask address
4.3.10.20 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 PICC18, see Section 2.6.21, or using the
assembler -P option, see Table 4.1, but can also be set with this directive, e.g.
PROCESSOR 16F877
175
HI-TECH C Assembly Language Macro Assembler
4.3.10.21 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:
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
A list of keywords is given in Table 4.7, and each is described further below. Some controls have
shorter forms, which are indicated in the table.
4.3.11.2 COND
Any conditional code will be included in the listing output. See also the NOCOND control in Section
4.3.11.6.
4.3.11.3 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.11.7.
176
Macro Assembler HI-TECH C Assembly Language
177
HI-TECH C Assembly Language Macro Assembler
4.3.11.4 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.12 which forces the C preprocessor to preprocess
assembly file, thus allowing use of preprocessor directives, such as #include (see Section 3.11.2).
4.3.11.5 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 Table 4.8.
See also the NOLIST control in Section 4.3.11.8.
4.3.11.6 NOCOND
Using this control will prevent conditional code from being included in the listing output. See also
the COND control in Section 4.3.11.2.
4.3.11.7 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.11.3. Assembly macro are discussed in Section 4.3.10.14.
178
Macro Assembler HI-TECH C Assembly Language
4.3.11.8 NOLIST
This control turns the listing output off from this point onward. See also the LIST control in Section
4.3.11.5.
4.3.11.9 NOXREF
NOXREF will disable generation of the raw cross reference file. See also the XREF control in Section
4.3.11.14.
4.3.11.10 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.11.11 STACK
The STACK control is added by the code generator to indicate to the assembler the available stack
level for an assembly routine. It is typically placed after an assembly label. The assembler uses this
information if code is being optimized. Procedural abstraction can increase stack usage and can only
be employed in a routine if this will not cause the hardware stack to overflow.
Misuse of this control can lead to code failure the stack depth specified is not correct.
4.3.11.12 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.11.13.
4.3.11.13 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.11.12.
4.3.11.14 XREF
XREF is equivalent to the driver command line option --CR (see Section 2.6.25). 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.
179
Assembly List Files Macro Assembler
The format of the main listing has the form as shown in Section Figure 4.1.
The line numbers purely relate to the assembly list file and are not associated with the lines
numbers in the C or assembly source files. Any assembly that begins with a semi- colon indicates it
is a comment added by the code generator. Such comments contain either the original source code
which corresponds to the generated assembly, or is a comment inserted by the code generator to
explain some action taken.
Before the output for each function there is detailed information regarding that function summa-
rized by the code generator. This information relates to register usage, local variable information,
functions called and the calling function.
180
Macro Assembler Assembly List Files
1 4
768 ;sp2_inpADC.c: 119: void ADC_start(unsigned char chan)
769 2 ;sp2_inpADC.c: 120: {
770 0243 _ADC_start:
771 3 ; Regs used in _ADC_start: [reg0,reg3] line number
772 0243 00A3 instruction operands
773 ;sp2_inpADC.c: 121: chan &= 0x07; address
774 0244 3007 instruction operands
775 0245 05A3 instruction operands op code
776 5
;sp2_inpADC.c: 128: }
777 0252 0008 instruction source comment
778 ; ========= function _ADC_start ends ========
assembly
181
Assembly List Files Macro Assembler
4064 ;;
1 *************** function _render *****************
4065 ;; Defined at:
4066 ;; line 29 in file "draw.c" 2
3 Parameters:
4067 ;; Size Location Type
4068 ;; None
4069 ;; Auto vars: Size Location Type
4070 ;; lll 4 42[BANK0 ] long
4071 ;; x 4 2 46[BANK0 ] volatile int
4072 ;; cp 1 41[BANK0 ] PTR unsigned char
4073 ;; -> inputData(2),
5 Return value: Size Location
4074 ;; Type
4075 ;; None void
6 Registers used:
4076 ;;
4077 ;; wreg, fsr0l, fsr0h, status,2, status,0, pclath, cstack
7 Tracked objects:
4078 ;;
4079 ;; On entry : 17F/0
4080 ;; On exit : 0/0
4081 ;; Unchanged: FFE00/0
4082 ;; Data sizes: COMMON BANK0 BANK1 BANK2
4083 ;; Params: 0 0 0 0
8
4084 ;; Locals: 0 7 0 0
4085 ;; Temps: 0 5 0 0
4086 ;; Totals: 0 12 0 0
4087 ;;Total ram usage: 12 bytes 1 function's name
4088 ;; Hardware stack levels used: 1
2 file name and line number of definition
9 Hardware stack levels required when called:
4089 ;; 4
4090 ;; This function calls: 3 size, location and type of parameters
4091 ;; _lrv
4092 ;; ___altofl 4 size, location and type of auto variables
10
4093 ;; ___awdiv 5 size, location and type of return value
4094 ;; ___awmod
4095 11
;; This function is called by: 6 registers that the function code used
4096 ;; _main
12 7 selected GPR bank on entry and exit
4097 ;; This function uses a non-reentrant model
8 RAM memory summary for entire function
9 hardware stack requirements
10 functions called by this function
11 which functions call this function
12 how the function was encoded
182
Macro Assembler Assembly List Files
For example, the following shows a pointer called task_tmr in the C code, and which is local
to the function timer_intr(). It is a pointer to an unsigned int and it is one byte wide. There is
only one target to this pointer and it is the member timer_count in the structure called task. This
target variable resides in the BANK0 class and is two bytes wide.
timer_intr@task_tmr PTR unsigned int size(1); Largest target is 2
-> task.timer_count(BANK0[2]),
The pointer reference graph shows both pointers to data objects and pointers to functions.
183
Assembly List Files Macro Assembler
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 the
function bar() will never be called even though it appears in the call graph.
In addition to these functions there is information relating to the memory allocated in the com-
piled stack for main(). This memory will be used for auto, temporary and parameter variables
defined in main(). The only difference between an auto and temporary variable is that auto vari-
ables are defined by the programmer, and temporaries are defined by the compiler, but both behave
in the same way.
In the orange box for main() you can see that it defines 10 auto and temporary variable. It de-
fines no parameters (main() never has parameters). There is a total of 24 references in the assembly
code to local objects in main().
Rather than the compiled stack being one memory allocation in one memory space, it can have
components placed in multiple memory spaces to utilize all available memory of the target device.
This break down is shown under the memory summary line for each function. In this example, it
shows that some of the local objects for main() are placed in the common memory, but others are
placed in bank 0 data RAM.
The Used column indicates how many bytes of memory are used by each section of the compiled
stack and the Space column indicates in which space that has been placed. The Base value indicates
184
Macro Assembler Assembly List Files
the offset that block has in the respective section of the compiled stack. For example, the figure tells
us main()has 6 bytes of memory allocated at an offset of 4 in the compiled stack section that lives
in common memory. It also has 4 bytes of memory allocated in bank 0 memory at an offset of 16 in
the bank 0 compiled stack component.
Below the information for main() (outside the orange box) you will see the same information
repeated for the functions that main() called, viz. rv(), rvx() and rvy(). Indentation is used
to indicate the maximum depth that function reaches in the call graph. The arrows in the figure
highlight this indentation.
After each tree in the call graph, there is an indication of the maximum call (stack) depth that
might be realized 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 main() tree cannot be determined as the
point in main’s call tree at which the interrupt (or other function invocation) will occur cannot
be known;
• The assembler optimizer may have replaced function calls with jumps to functions, reducing
that tree’s stack usage.
• The assembler’s procedural abstraction optimizations may have added in calls to abstracted
routines. (Checks are made to ensure this does not exceed the maximum stack depth.)
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 only a guide to potential stack
problems.
185
Assembly List Files Macro Assembler
In this example, it shows that of all the call graph paths starting from the function main(), the
path main() calls foobar(), which calls flsub(), which calls fladd(), is using the largest block
of memory in bank 0 RAM. The exact memory usage of each function is shown in the call graph
tables.
The memory used by functions that are not in the critical path will overlap entirely with that in
the critical path. Reducing the memory usage of these will have no impact on the memory usage of
the entire program.
186
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.
187
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.
188
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 (obsolete)
continued. . .
189
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 defined or undefined symbol in table
-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
190
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
This option is now obsolete.
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.
191
Operation Linker and Utilities
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
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
192
Linker and Utilities Operation
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.
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
193
Operation Linker and Utilities
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.9.
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.
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
194
Linker and Utilities Operation
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.
-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
195
Operation Linker and Utilities
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
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. The symbol may either be
defined or undefined.
Symbols may be defined to be equal to another symbol or a numerical value, e.g.
196
Linker and Utilities Invoking the Linker
-U_myUndefinedSymbol
-U_myDefinedSymbol=0x55
-U_equatedSymbol=_foobar
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.
197
Map Files 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
5.9.1 Generation
If compilation is being performed via MPLAB IDE, 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.9.
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.32 for more information on this option.
5.9.2 Contents
The sections in the map file, in order of appearance, are as follows:
• The version number of the object code in the first file linked;
198
Linker and Utilities Map Files
Portions of an example map file, along with explanatory text, are shown in the following sections.
199
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. The linker options are necessarily complex. Fortunately, they rarely need adjusting
from their default settings. They are formed by the command-line driver, PICC18, based on the
selected target device and the specified driver options. You can often confirm that driver options
were valid by looking at the linker options in the map file. For example, if you ask the driver to
reserve an area of memory, you should see a change in the linker options used.
If the default linker options must be changed, this can be done indirectly through the driver using
the driver -L- option, see Section 2.6.8. If you use this option, always confirm the change appears
correctly in the map file.
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.Note that since the
code generator combines all C source files (and p-code libraries), there will only be one object file
representing the entire C part of the program. The object file corresponding to the runtime startup
code is normally present in this list.
The information in this section of the map file can be used to confirm that a module is making a
contribution to the output file and to determine the exact psects that each module defines.
Shown are all the psects (under the Name column) that were linked into the program from each
object file, and information regarding that psect.
The linker deals with two kinds of addresses: link and load. Generally speaking the link address
of a psect is the address by which it will be accessed at run time.
The load address, which is often the same as the link address, is the address at which the psect
will start within the output file (HEX or binary file etc.). If a psect is used to hold bits, the load
200
Linker and Utilities Map Files
address is irrelevant and is instead used to hold the link address (in bit units) converted into a byte
address.
The Length of the psect is shown (in units suitable for that psect).
The Selector is less commonly used and is of no concern when compiling for PIC18 devices.
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 (such as PIC18 devices), this field
must be used in conjunction with the address to specify an exact storage location. A space of 0
indicates the program memory, and a space of 1 indicates the data memory. See 4.3.10.3.
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
201
Map Files Linker and Utilities
Under this are the class names followed by those psects which belong to this class, see 4.3.10.3.
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:
and is followed by a list of classes and the memory still available in each class. 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 are not displayed, but the column Largest block shows the largest contiguous free
space which takes into account any paging in the memory range. If you are looking to see why psects
cannot be placed into memory (e.g. cant-find-space type errors) then this important information to
study.
Note that the memory associated with a class can overlap that in others, thus the total free space
is not simply the addition of all the unused ranges.
202
Linker and Utilities Map Files
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:
• Linker-defined symbols.
Assembly symbols are made global via the GLOBAL assembler directive, see Section 4.3.10.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 3.12.3. 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
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.19 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.
203
Librarian Linker and Utilities
5.10 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.
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.
204
Linker and Utilities Librarian
5.10.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:
This command deletes the object modules a.obj, b.obj and c.obj from the library file.lib:
205
Librarian Linker and Utilities
libr
libr> r file.lib 1.obj 2.obj 3.obj \
libr> 4.obj 5.obj 6.obj
will perform much the same as if the object files had been typed on the command line. The libr>
prompts were printed by LIBR itself, the remainder of the text was typed as input.
libr <lib.cmd
LIBR will read input from lib.cmd, and execute the command found therein. This allows a virtually
unlimited length command to be given to LIBR.
will list all modules in file.lib with their global symbols, with the output formatted for an 80
column printer or display.
206
Linker and Utilities Objtohex
The ordering of the modules in a library is significant to the linker. If a library contains a module
which references a symbol defined in another module in the same library, the module defining the
symbol should come after the module referencing the symbol.
5.11 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
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:
207
Objtohex Linker and Utilities
208
Linker and Utilities Cref
5.12 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:
cref options files
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.12.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
209
Cref Linker and Utilities
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.12.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.
5.12.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.12.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.12.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.12.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.12.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
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.
210
Linker and Utilities Cromwell
5.13 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:
CROMWELL options input_files -okey output_file
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.13.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
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.13.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
211
Cromwell Linker and Utilities
212
Linker and Utilities Cromwell
list. For example, in the DSPIC C compiler these classes are typically “CODE” and “NEARCODE”,
i.e. -NCODE,NEARCODE.
5.13.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.13.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.
5.13.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.13.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.13.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.13.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.13.9 -E
Use this option to tell CROMWELL to ignore any filename extensions that were given. The default
extension will be used instead.
213
Hexmate Linker and Utilities
5.13.10 -B
In formats that support different endian types, use this option to specify big-endian byte ordering.
5.13.11 -M
When generating COD files this option will remove the preceding underscore character from sym-
bols.
5.13.12 -V
Turns on verbose mode which will display information about operations CROMWELL is performing.
5.14 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
214
Linker and Utilities Hexmate
• 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.14.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:
215
Hexmate Linker and Utilities
216
Linker and Utilities Hexmate
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.14.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.14.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.14.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.
217
Hexmate Linker and Utilities
5.14.1.5 -CK
The -CK option is for calculating a checksum. The usage of this option is:
-CK=start-end@destination[+offset][wWidth][tCode][gAlgorithm]
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.14.1.6 -FILL
The -FILL option is used for filling unused memory locations with a known value. The usage of this
option is:
-fill=[const_width:]fill_expr[@address[:end_address]]
where:
218
Linker and Utilities Hexmate
• const_width has the form wn and signifies the width (n bytes) of each constant in fill_expr.
If const_width is not specified, the default value is the native width of the architecture. i.e.
--fill=w1:1 with fill every byte with the value 0x01.
• fill_expr can use the syntax (where const and increment are n-byte constants):
– const fill memory with a repeating constant i.e. --fill=0xBEEF becomes 0xBEEF,
0xBEEF, 0xBEEF, 0xBEEF
– const+=increment fill memory with an incrementing constant i.e. --fill=0xBEEF+=1
becomes 0xBEEF, 0xBEF0, 0xBEF1, 0xBEF2
– const-=increment fill memory with a decrementing constant
i.e. --fill=0xBEEF-=0x10 becomes 0xBEEF, 0xBEDF, 0xBECF, 0xBEBF
– const,const,...,const fill memory with a list of repeating constants
i.e. --fill=0xDEAD,0xBEEF becomes 0xDEAD,0xBEEF,0xDEAD,0xBEEF
– @unused (or nothing) fill all unused memory with fill_expr i.e. --fill=0xBEEF@unused
fills all unused memory with 0xBEEF. (This option can only be used with the PICC18
command-line option --FILL, see 2.6.33. The driver will expand this to the appropriate
ranges and pass these to HEXMATE.)
– @address fill a specific address with fill_expr i.e. --fill=0xBEEF@0x1000 puts 0xBEEF
at address 1000h
219
Hexmate Linker and Utilities
All constants can be expressed in (unsigned) binary, octal, decimal or hexadecimal, as per normal C
syntax, so for example 1234 is a decimal value, 0xFF00 is hexadecimal and FF00 is illegal.
5.14.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.
• Mask is optional. It allows a bit mask over the Findcode value and is entered in little endian
byte order.
• 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.
220
Linker and Utilities Hexmate
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.14.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.14.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]
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.14.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:
• Length is optional and sets the maximum number of bytes per data record. A valid length is
between 1 and 128, with 16 being the default.
221
Hexmate Linker and Utilities
T UT•RIAL
Consider this case. A bootloader trying to download an INHX32 file fails 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.
5.14.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
5.14.1.12 -LOGFILE
The -LOGFILE option saves hex file statistics to the named file. For example:
-LOGFILE=output.log
222
Linker and Utilities Hexmate
will analyse the hex file that hexmate is generating and save a report to a file named output.log.
5.14.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.14.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.
5.14.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:
223
Hexmate Linker and Utilities
-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.14.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.14.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:
• Code is optional and allows a byte sequence to trail each byte in the string. This can allow the
bytes of the string to be encoded within an instruction.
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.
224
Linker and Utilities Hexmate
5.14.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.
225
Hexmate Linker and Utilities
226
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.
227
Library Functions
__CONFIG
Synopsis
#include <htc.h>
__CONFIG(n, data)
Description
This macro is used to program the configuration fuses that set the device into various modes of
operation.
The macro accepts the number corresponding to the configuration register it is to program, then
the 16-Bit value it is to update it with.
16-Bit masks have been defined to describe each programmable attribute available on each de-
vice. These attribute masks can be found tabulated in this manual in the Features and Runtime
Environment section.
Multiple attributes can be selected by ANDing them together.
Example
#include <htc.h>
void
main (void)
{
}
See also
__EEPROM_DATA(), __IDLOC()
228
Library Functions
__EEPROM_DATA
Synopsis
#include <htc.h>
__EEPROM_DATA(a,b,c,d,e,f,g,h)
Description
This macro is used to store initial values into the device’s EEPROM registers at the time of program-
ming.
The macro must be given blocks of 8 bytes to write each time it is called, and can be called
repeatedly to store multiple blocks.
__EEPROM_DATA() will begin writing to EEPROM address zero, and will auto-increment the
address written to by 8, each time it is used.
Example
#include <htc.h>
__EEPROM_DATA(0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07)
__EEPROM_DATA(0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F)
void
main (void)
{
}
See also
__CONFIG()
229
Library Functions
__IDLOC
Synopsis
#include <htc.h>
__IDLOC(x)
Description
This macro places data into the device’s special locations outside of addressable memory reserved
for ID. This would be useful for storage of serial numbers etc.
The macro will attempt to write 5 nibbles of data to the 5 locations reserved for ID purposes.
Example
#include <htc.h>
__IDLOC(15F01);
/* will store 1, 5, F, 0 and 1 in the ID registers*/
void
main (void)
{
}
See also
__EEPROM_DATA(), __CONFIG()
230
Library Functions
_DELAY()
Synopsis
#include <htc.h>
Description
This is an inline function that is expanded by the code generator. When called, this routine expands
to an inline assembly delay sequence. The sequence will consist of code that delays for the number
of cycles that is specified as argument. The argument must be a literal constant.
Example
#include <htc.h>
void
main (void)
{
control |= 0x80;
_delay(10); // delay for 10 cycles
control &= 0x7F;
}
See Also
_delay3()
231
Library Functions
_DELAY3()
Synopsis
#include <htc.h>
Description
This is an inline function that is expanded by the code generator. When called, this routine expands
to an inline assembly delay sequence. The sequence will consist of code that delays for 3 times the
number of cycles that is specified as argument. The argument can be any expression.
Example
#include <htc.h>
void
main (void)
{
control |= 0x80;
_delay3(10); // delay for 30 cycles
control &= 0x7F;
}
See Also
_delay()
232
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.
233
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 π
234
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
235
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.
236
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 - π
237
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.
238
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.
239
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.
240
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.
241
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.
242
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.
243
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;
244
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.
245
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));
}
246
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
247
Library Functions
Return Value
The return value is the character pointer passed as the sole argument.
248
Library Functions
CLRWDT
Synopsis
#include <htc.h>
CLRWDT();
Description
This macro is used to clear the device’s internal watchdog timer.
Example
#include <htc.h>
void
main (void)
{
WDTCON=1;
/* enable the WDT */
CLRWDT();
}
249
Library Functions
CONFIG_READ(), CONFIG_WRITE()
Synopsis
#include <htc.h>
Description
These functions allow access to the device configuration registers which determine many of the
behavioural aspects of the device itself.
config_read() accepts a single parameter to determine which config word will be read. The 16-Bit
value contained in the register is returned.
config_write() doesn’t return any value. It accepts a second parameter which is a 16-Bit value to
be written to the selected register.
Example
#include <htc.h>
void
main (void)
{
unsigned int value;
See Also
device_id_read(),idloc_read(),idloc_write()
250
Library Functions
Return Value
config_read() returns the 16-Bit value contained in the nominated configuration register.
Note
The functions config_read() config_write() are only applicable to such devices that support this
feature.
251
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.
252
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.
253
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()
254
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.
255
Library Functions
device_id_read()
Synopsis
#include <htc.h>
Description
This function returns the device ID code that is factory-programmed into the chip. This code can be
used to identify the device and its revision number.
Example
#include <htc.h>
void
main (void)
{
unsigned int id_value;
unsigned int device_code;
unsigned char revision_no;
id_value = device_id_read();
/* lower 5 bits represent revision number
* upper 11 bits identify device */
device_code = (id_value > > 5);
revision_no = (unsigned char)(id_value & 0x1F);
See Also
flash_read(), config_read()
256
Library Functions
Return Value
device_id_read() returns the 16-Bit factory-programmed device id code used to identify the device
type and its revision number.
Note
The device_id_read() is applicable only to those devices which are capable of reading their own
program memory.
257
Library Functions
DI, EI
Synopsis
#include <htc.h>
void ei (void)
void di (void)
Description
The di() macro disables all interrupts globally (regardless of priority settings), ei() re-enables inter-
rupts globally. These are implemented as macros defined in PIC18.h. The example shows the use
of ei() and di() around access to a long variable that is modified during an interrupt. If this was not
done, it would be possible to return an incorrect value, if the interrupt occurred between accesses to
successive words of the count value.
Example
#include <htc.h>
long count;
void
interrupt tick (void)
{
count++;
}
long
getticks (void)
{
long val; /* Disable interrupts around access
to count, to ensure consistency.*/
di();
val = count;
ei();
return val;
258
Library Functions
Note
As these macros act on the global interrupt enable bit of the PIC18 processor, ei() will only restore
those interrupt sources that were previously enabled.
259
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.
260
Library Functions
EEPROM_READ, EEPROM_WRITE
Synopsis
#include <htc.h>
Description
These functions allow access to the on-chip eeprom (when present). The eeprom is not in the
directly-accessible memory space and a special byte sequence is loaded to the eeprom control regis-
ters to access this memory. Writing a value to the eeprom is a slow process and the eeprom_write()
function polls the appropriate registers to ensure that any previous writes have completed before
writing the next datum.
Reading data is completed in the one cycle and no polling is necessary to check for a read
completion.
Example
#include <htc.h>
void
main (void)
{
unsigned char data;
unsigned int address = 0x0010;
data=eeprom_read(address);
eeprom_write(address, data);
}
See Also
261
Library Functions
Note
The high and low priority interrupt are disabled during sensitive sequences required to access EEP-
ROM. Interrupts are restored after the sequence has completed. eeprom_write() will clear the EEIF
hardware flag before returning.
Both eeprom_read() and eeprom_write() are available in a similar macro form. The essential
difference between the macro and function implementations is that EEPROM_READ(), the macro,
does not test nor wait for any prior write operations to complete.
262
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.
263
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()
264
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()
265
Library Functions
FLASH Routines
Synopsis
#include <plib.h>
Description
Flash routines are no long supported in the standard C libraries. Use the flash routines provided by
the peripheral libraries whose prototypes are shown above. These are descibed in Section 3.2.7 or in
the peripheral library documentation.
266
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.
267
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));
}
268
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()
269
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()
270
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.
271
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.
272
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
273
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.
274
Library Functions
IDLOC_READ(), IDLOC_WRITE()
Synopsis
#include <htc.h>
Description
These functions allow access to the user ID register which can be used to store small amounts of
information such as serial numbers, checksums etc.
idloc_read() accepts a single parameter to determine which user ID register to read. The value
contained in the register is returned.
idloc_write() doesn’t return any value. It accepts a second parameter which is a value to be
written to the selected register. Note that only the lower nibble is significant. The upper nibble of
the value written will always be 0xF as per Microchip’s documentation.
Example
#include <htc.h>
void
main (void)
{
unsigned char value;
See Also
device_id_read(),config_read(),config_write()
275
Library Functions
Return Value
idloc_read() returns the value contained in the nominated user ID register.
Note
The functions idloc_read() idloc_write() are only applicable to such devices that support this fea-
ture.
Note also that ICD2 breakpoints should not be set within the idloc_write() function. Doing so
can result in disrupting the operation of the debugger.
276
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.
277
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()
278
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.
279
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.
280
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.
281
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.
282
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
283
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]);
}
284
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.
285
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.
286
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;
287
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.
288
Library Functions
LTOA
Synopsis
#include <stdlib.h>
Description
The function ltoa 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];
ltoa(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.
289
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");
}
290
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.
291
Library Functions
MEMMOVE
Synopsis
#include <string.h>
Description
The memmove() function is similar to the function memcpy() except copying of overlapping blocks
is handled correctly. That is, it will copy forwards or backwards as appropriate to correctly copy one
block to another that overlaps it.
See Also
strncpy(), strncmp(), strchr(), memcpy()
Return Value
The function memmove() returns its first argument.
292
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;
See Also
ctime(), asctime()
293
Library Functions
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.
294
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.
295
Library Functions
NOP
Synopsis
#include <htc.h>
NOP();
Description
Execute NOP instruction here. This is often useful to finetune delays or create a handle for break-
points. The NOP instruction is sometimes required during some sensitive sequences in hardware.
Example
#include <htc.h>
void
crude_delay(unsigned char x) {
while(x--){
NOP(); /* Do nothing for 3 cycles */
NOP();
NOP();
}
}
296
Library Functions
OS_TSLEEP
Synopsis
#include <task.h>
Description
This routine causes the current task to be removed from the run queue for tcks clock ticks.
Example
#include <task.h>
void
task(void)
{
while(1) {
/* sleep for 100 ticks */
os_tsleep(100);
}
}
297
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.
298
Library Functions
PRINTF
Synopsis
#include <stdio.h>
Description
The printf() function is a formatted output routine, operating on stdout. There are corresponding
routines operating 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. The printf() function performs the text
formatting and calls on the putch() function to actually send the data to the destination.
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.
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:
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. 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.
l
Long integer conversion - Preceding the integer conversion key letter with an l indicates that the
argument list is long.
f
Floating point - m is the total width and n is the number of digits after the decimal point. If n is
299
Library Functions
omitted it defaults to 6. If the precision is zero, the decimal point will be omitted unless the alternate
format is specified.
Example
printf("Total = %4d%", 23)
yields ’Total = 23%’
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;
300
Library Functions
i = 3;
error("testing 1 2 %d", i);
}
See Also
sprintf()
Return Value
The printf() routine returns the number of characters written to stdout.
Note
To use printf(), the putch() function needs to be defined to output one byte of data to the required
destination.
301
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()
302
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
303
Library Functions
Note
This routine is not usable in a ROM based system.
304
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.
305
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;
306
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.
307
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()
308
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.
309
Library Functions
READTIMERx
Synopsis
#include <htc.h>
READTIMER0();
READTIMER1();
READTIMER3();
Description
The macros READTIMER0(), READTIMER1() and READTIMER3() will return the 16-Bit
value presently held in the device’s corresponding TMRxL and TMRxH register pair. Use of this
macro ensures that the registers are read in the correct order. Timer 2 is an 8-bit timer and does
Example
#include <htc.h>
void
main (void)
{
unsigned int timer1value;
timer1value = READTIMER1();
}
See Also
WRITETIMERx()
Return Value
An unsigned integer which is the value held in a 16-Bit timer.
310
Library Functions
RESET
Synopsis
#include <htc.h>
RESET();
Description
Execute RESET instruction here.
Example
#include <htc.h>
void
test_result(unsigned int error_count) {
if(error_count != 0){
printf(“An error has been detected - Rebooting...\n”);
RESET(); /* Perform software reset */
}
}
311
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()
312
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.
s
Skip white space, then copy a maximal length sequence of non-white-space characters. The pointer
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
313
Library Functions
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, and d may be preceded by an l to indicate that the correspond-
ing pointer argument is a pointer to long 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.
314
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");
315
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().
316
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.
317
Library Functions
SLEEP
Synopsis
#include <htc.h>
SLEEP();
Description
This macro is used to put the device into a low-power standby mode.
Example
#include <htc.h>
extern void init(void);
void
main (void)
{
init(); /* enable peripherals/interrupts */
while(1)
SLEEP(); /* save power while nothing happening */
}
318
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.
319
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()
320
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.
321
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.
322
Library Functions
Note
Although the function takes an integer argument for the character, only the lower 8 bits of the value
are used.
323
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
324
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).
325
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.
326
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.
327
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.
328
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
329
Library Functions
Return Value
The value of s1 is returned.
330
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 = strncmp("abcxyz", "abcxyz",6);
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()
331
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).
332
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
333
Library Functions
Return Value
The destination buffer pointer s1 is returned.
334
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.
335
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.
336
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.
337
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.
338
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()
339
Library Functions
Return Value
Returns a double representing the floating-point value of the converted input string.
340
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()
341
Library Functions
Return Value
Returns a long int representing the value of the converted input string using the specified base.
342
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 = ".,?! ";
343
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.
344
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.
345
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.
346
Library Functions
Note
The time() routine is not supplied, if required the user will have to implement this routine to the
specifications outlined above.
347
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.
348
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()
349
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.
350
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.
351
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()
352
Library Functions
UTOA
Synopsis
#include <stdlib.h>
Description
The function utoa 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];
utoa(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.
353
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, ...)
{
354
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");
}
355
Library Functions
WRITETIMERx
Synopsis
#include <htc.h>
WRITETIMER0(unsigned int);
WRITETIMER1(unsigned int);
WRITETIMER3(unsigned int);
Description
The WRITETIMER0, WRITETIMER1() and WRITETIMER3() macros will assign a 16-Bit
value to the TMRxL and TMRxH register pair of the corresponding device timer. Using this macro
will ensure that the bytes are written in the correct order.
Example
#include <htc.h>
void
main (void)
{
WRITETIMER1(0xF500);
}
See Also
READTIMERx()
356
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
An unsigned integer. If no number is found in the string, zero will be returned.
357
Library Functions
358
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. You should attempt to resolve errors or warnings in the order in which they are produced.
359
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
360
Error and Warning Messages
void cleardog(void)
{
clrwdt
#endasm /* in-line assembler ends here,
only where did it begin? */
}
#asm
move r0, #0aah
#asm ; previous #asm must be closed before opening another
sleep
#endasm
361
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
362
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 ? */
363
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.:
364
Error and Warning Messages
365
Error and Warning Messages
366
Error and Warning Messages
/* Here the comment begins. 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
367
Error and Warning Messages
368
Error and Warning Messages
369
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 370.
This option given to the component which caused the error is not recognized.
370
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:
371
Error and Warning Messages
372
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) ? */
373
Error and Warning Messages
int get_value(void);
void main(void)
{
int input;
input = get_value(6); /* oops --
parameter should not be here */
}
This function does not accept as many arguments as there are here.
This function requires more arguments than are provided in this call, e.g.:
In this context an expression is required that can be evaluated to a constant at compile time, e.g.:
int a;
switch(input) {
case a: /* oops!
can’t use variable as part of a case label */
input++;
}
374
Error and Warning Messages
int i, array[10];
i = array[3.5]; /* oops --
exactly which element do you mean? */
A typecast (an abstract type declarator enclosed in parentheses) must denote a type which is either
scalar (i.e. not an array or a structure) or the type void, e.g.:
This symbol has been used in the program, but has not been defined or declared. Check for spelling
errors if you think it has been defined.
This identifier is not a variable; it may be some other kind of object, e.g. a label.
A closing parenthesis, ), was expected here. This may indicate you have left out this character in an
expression, or you have some other syntax error. The error is flagged on the line at which the code
first starts to make no sense. This may be a statement following the incomplete expression, e.g.:
This expression is badly formed and cannot be parsed by the compiler, e.g.:
375
Error and Warning Messages
376
Error and Warning Messages
int array[10];
int * ip;
char c;
array = ip; /* array isn’t a variable,
it can’t be written to */
*(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 */
}
377
Error and Warning Messages
int * ip;
char * cp, * cp2;
cp = flag ? ip : cp2;
/* result of ? : will be int * or char * */
378
Error and Warning Messages
379
Error and Warning Messages
Pragmas for all the standard printf-like function are already contained in <stdio.h>.
float f;
f = 1.234e; /* oops -- what is the exponent? */
int a = 058;
/* leading 0 implies octal which has digits 0 - 7 */
380
Error and Warning Messages
381
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.
A simple integral expression is required after the operator @, used to associate an absolute address
with a variable, e.g.:
int address;
char LOCK @ address;
More than one definition for a function has been encountered in this module. Function overloading
is illegal, e.g.:
int twice(int a)
{
return a*2;
}
/* only one prototype & definition of rv can exist */
long twice(long a)
{
return a*2;
}
382
Error and Warning Messages
383
Error and Warning Messages
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 */
switch(a) {
default: /* if this is the default case... */
b = 9;
break;
default: /* then what is this? */
b = 10;
break;
384
Error and Warning Messages
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 */
start:
if(a > 256)
goto end;
start: /* error flagged here */
if(a == 0)
goto start; /* which start label do I jump to? */
385
Error and Warning Messages
void set(char a)
{
PORTA = a;
/* the closing brace was left out here */
void clear(void) /* error flagged here */
{
PORTA = 0;
}
386
Error and Warning Messages
struct {
int a, b, c;
} data;
if(data.d) /* oops --
there is no member d in this structure */
return;
far near int spooky; /* oops -- choose far or near, not both */
387
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); /* should be a pointer: int (*get)(int); */
} object;
388
Error and Warning Messages
struct FREG {
char b0:1; /* these must be part of an int, not char */
char :6;
char b7:1;
} freg;
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;
struct {
/* no additional qualifiers may be present with members */
static int first;
} ;
389
Error and Warning Messages
return foo * a;
}
A declaration has conflicting storage classes. Only one storage class should appear in a declaration,
e.g.:
Only function parameters or auto variables may be declared using the register qualifier, e.g.:
390
Error and Warning Messages
391
Error and Warning Messages
392
Error and Warning Messages
This is an internal compiler error. Contact HI-TECH Software technical support with details.
The identifier is missing in this declaration. This error can also occur where the compiler has been
confused by such things as missing closing braces, e.g.:
This declarator is too complex for the compiler to handle. Examine the declaration and find a way
to simplify it. If the compiler finds it too complex, so will anybody maintaining the code.
int a;
void b; /* this makes no sense */
The qualifier interrupt may not be applied to anything except a function, e.g.:
393
Error and Warning Messages
394
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 */
395
Error and Warning Messages
This is an internal compiler error. Contact HI-TECH Software technical support with details.
There are too many case labels in this switch statement. The maximum allowable number of case
labels in any one switch statement is 511.
There are too many symbols for the assembler’s symbol table. Reduce the number of symbols in
your program.
A closing square bracket was expected in an array declaration or an expression using an array index,
e.g.
process(carray[idx); /* oops --
should be: process(carray[idx]); */
Where a function declaration is encountered with K&R style arguments (i.e. argument names but no
types inside the parentheses) a function body is expected to follow, e.g.:
396
Error and Warning Messages
397
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 */
398
Error and Warning Messages
struct {
int a;
} my_struct;
(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.
399
Error and Warning Messages
400
Error and Warning Messages
char * cp = “hi”
“there”; /* this is okay,
but is it what you had intended? */
401
Error and Warning Messages
int get_value(void)
{
if(flag)
return val++;
return;
/* what is the return value in this instance? */
}
402
Error and Warning Messages
int process(int a)
{
/* this would be better outside the function */
extern int away;
return away + a;
}
int process(input)
int input; /* warning flagged here */
{
}
403
Error and Warning Messages
404
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;
A floating point value has been assigned or otherwise converted to an integral type. This could result
in truncation of the floating point value. A typecast will make this warning go away.
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;
An integer has been assigned to or otherwise converted to a pointer 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. This may also mean
you have forgotten the & address operator, e.g.:
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;
405
Error and Warning Messages
406
Error and Warning Messages
An array is being indexed with a constant value that is less than zero, or greater than or equal to the
number of elements in the array. This warning will not be issued when accessing an array element
via a pointer variable, e.g.:
Where the compiler encounters a function call of a function whose name is presently undefined, the
compiler will automatically declare the function to be of type int, with unspecified (K&R style)
parameters. If a definition of the function is subsequently encountered, it is possible that its type
and arguments will be different from the earlier implicit declaration, causing a compiler error. The
solution is to ensure that all functions are defined or at least declared before use, preferably with
prototyped parameters. If it is necessary to make a forward declaration of a function, it should be
preceded with the keywords extern or static as appropriate. For example:
The address operator & has been applied to an array. Since using the name of an array gives its
address anyway, this is unnecessary and has been ignored, e.g.:
int array[5];
int * ip;
/* array is a constant, not a variable; the & is redundant. */
ip = &array;
407
Error and Warning Messages
408
Error and Warning Messages
409
Error and Warning Messages
char c;
i; /* don’t let the compiler make assumptions, use : int i */
func(); /* ditto, use: extern int func(int); */
unsigned char a;
/* thinks: chat & b are unsigned, but where is the comma? */
unsigned chat b;
410
Error and Warning Messages
411
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.
412
Error and Warning Messages
413
Error and Warning Messages
414
Error and Warning Messages
415
Error and Warning Messages
-GA/f0+10
-GA/f0h+10
416
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
417
Error and Warning Messages
418
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
419
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=./.
420
Error and Warning Messages
421
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.:
422
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
423
Error and Warning Messages
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
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)
424
Error and Warning Messages
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.
_next:
move r0, #55
move [r1], r0
_next: ; oops -- choose a different name
425
Error and Warning Messages
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.
psect final,class=CODE
finish:
/* elsewhere: */
psect final,class=ENTRY
psect starttext,class=CODE,with=rext
; was that meant to be with text?
426
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
(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.8.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.9 for
information on how to generate a map file. Search for the string UNUSED ADDRESS RANGES. Under
427
Error and Warning Messages
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
4.4.4 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:
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.
This psect is absolute and should not have an address specified in a -P option. Either remove the
abs psect flag, or remove the -P linker option.
428
Error and Warning Messages
The origin of this psect is defined more than once. There is most likely more than one -p linker
option specifying this psect.
The -P option given to the linker is malformed. This option specifies placement of a psect, e.g.:
-Ptext=10g0h
-Ptext=10f0h
It is not legal to specify both the link and location of a psect as within a class, when that psect was
also defined using a with psect flag.
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.
429
Error and Warning Messages
430
Error and Warning Messages
There is an error in the object code format read by the linker. This either means you are using
a linker that is out of date, or that there is an internal error in the assembler or linker. Contact
HI-TECH Support with details if the object file was created by the compiler.
The linker was given a -R or -L option with file that contain complex relocation.
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.
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.
431
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.
432
Error and Warning Messages
(593) can’t find 0x* words (0x* withtotal) for psect "*" in segment "*" (Linker)
See error (491) on Page 427.
433
Error and Warning Messages
434
Error and Warning Messages
435
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.
436
Error and Warning Messages
(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.
(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.
437
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.
438
Error and Warning Messages
switch(in) {
case ’0’: /* if this is case ’0’... */
b++;
break;
case ’0’: /* then what is this case? */
b--;
break;
}
439
Error and Warning Messages
bit proc(int a)
{
bit bb; /* oops -- this should be: static bit bb; */
bb = (a > 66);
return bb;
}
switch(input) {
} /* there is nothing to match the value of input */
440
Error and Warning Messages
This is an internal compiler error. Contact HI-TECH Software technical support with details. See
Section 5.7.2 for more information.
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.
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.
441
Error and Warning Messages
442
Error and Warning Messages
443
Error and Warning Messages
bit b1 = 1; /* oops!
b1 must be assigned after its definition */
The code generator has been passed a pragma psect directive that has a badly formed string, e.g.:
The argument to the stack_size pragma is malformed. This pragma must be followed by a number
representing the maximum allowed stack size.
The #pragma switch directive has been used with an invalid switch code generation method. Pos-
sible arguments are: auto, simple and direct.
The compiler detected an error when closing a file. Contact HI-TECH Support with details.
The code generator has been passed a declaration that results in an array having a zero dimension.
444
Error and Warning Messages
struct {
unsigned flag : 1;
unsigned value : 12;
unsigned cont : 6; /* oops -- that’s 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;
}
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.
445
Error and Warning Messages
(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();
}
{
int a;
a = 6;
if(a || b) /* a is 6, therefore this is always true */
b++;
446
Error and Warning Messages
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:
char a;
int b, c;
a = b + c; /* int to char conversion
may result in truncation */
447
Error and Warning Messages
int input;
input < <= 33; /* oops -- that shifts the entire value out */
struct {
unsigned mask : 2; /* mask can hold values 0 to 3 */
} value;
int compare(void)
{
return (value.mask == 6); /* test can
}
448
Error and Warning Messages
{
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;
/* this loop must iterate at least once */
for(a=0; a!=10; a++)
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.
(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;
449
Error and Warning Messages
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:
This expression generates no output code. Check for things like leaving off the parentheses in a
function call, e.g.:
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.
Part of this expression has no side effects, and no effect on the value of the expression, e.g.:
int a, b, c;
a = b,c; /* “b” has no effect,
was that meant to be a comma? */
The code generator has taken the size of an object and found it to be zero. This almost certainly
indicates an error in your declaration of a pointer, e.g. you may have declared a pointer to a zero
length array. In general, pointers to arrays are of little use. If you require a pointer to an array of
objects of unknown length, you only need a pointer to a single object that can then be indexed or
incremented.
450
Error and Warning Messages
struct INPUT {
unsigned a : 3;
unsigned b : 5;
} input_grp;
input_grp.a = 0x12;
/* 12h cannot 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.
451
Error and Warning Messages
char c;
if(c >= -128)
will always be true, because an 8 bit signed char has a maximum negative value of -128.
struct INPUT {
unsigned a : 3;
unsigned b : 5;
} input_grp;
input_grp.a |= 0x13;
/* 13h to large for 3-bit wide object */
unsigned int a;
if(a == -10) /* if a is unsigned, how can it be -10? */
b = 9;
452
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.
453
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.
454
Error and Warning Messages
mmm macro a1
move r0, #a1
LOCAL a1 ; oops --
; the macro parameter cannot be used with local
ENDM
455
Error and Warning Messages
(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.
456
Error and Warning Messages
(825) too many RAMBANK lines in chipinfo file for "*" (Assembler)
The chipinfo file contains a processor section with too many RAMBANK fields. Reduce the number
of values.
457
Error and Warning Messages
(827) too many COMMON lines in chipinfo file for "*" (Assembler)
There are too many lines specifying common (access bank) memory in the chip configuration file.
LIST C=10 ; the page width will need to be wider than this
458
Error and Warning Messages
getval MACRO
mov r0, r1
ENDM
getval EQU 55h ; oops -- choose a different name to the macro
_next:
move r0, #55
move [r1], r0
_next: ; oops -- choose a different name
459
Error and Warning Messages
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.
460
Error and Warning Messages
461
Error and Warning Messages
(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
(866) argument to "reloc" psect flag must specify a positive constant (Assembler)
The parameter to the PSECT assembler directive’s reloc option must be a positive constant number,
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.:
462
Error and Warning Messages
(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.:
psect spdata,class=RAM,space=0
; elsewhere:
psect spdata,class=RAM,space=1
psect text,class=CODE
Look for other psect definitions that specify a different class name.
psect bss,with=data
Look for other psect definitions that specify a different with psect name.
463
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:
• 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.
464
Error and Warning Messages
(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.
(895) can’t request and specify options in the one command (Driver)
The usage of the driver options --getoption and --setoption is mutually exclusive.
465
Error and Warning Messages
(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.
(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.
(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.
466
Error and Warning Messages
(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.
467
Error and Warning Messages
468
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.
469
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.
470
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.
The only modifier that is legal with this format is l (for long).
The format specifier or modifier in the printf-style string is illegal for this particular format.
A field width may not appear at this point in a printf() type format specifier.
471
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 */
472
Error and Warning Messages
The type of this function or object has been redeclared. This can occur because of two incompatible
declarations, or because an implicit declaration is followed by an incompatible declaration, e.g.:
int a;
char a; /* oops -- what is the correct type? */
A member of an enumeration is defined twice or more with differing values. Does the member
appear twice in the same list or does the name of the member appear in more than one enum list?
The data types of the parameters passed to this function do not match its prototype.
The number of arguments in this function declaration does not agree with a previous declaration of
the same function.
This module has code below the address given, but the -C option has been used to specify that a
binary output file is to be created that is mapped to this address. This would mean code from this
module would have to be placed before the beginning of the file! Check for missing psect directives
in assembler files.
473
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.
474
Error and Warning Messages
(1013) argument to "limit" psect flag must specify a positive constant (Assembler)
The value of the limit flag as used in a psect’s declaration must be a positive constant. A negative
limit is not permissible.
(1016) missing argument* to "*" specification in chipinfo file "*" at line * (Driver)
This value of this attribute is blank in the chip configuration file.
(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.
(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.
475
Error and Warning Messages
(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.
476
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.
477
Error and Warning Messages
478
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? */
479
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.:
480
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.
481
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.
482
Error and Warning Messages
483
Error and Warning Messages
(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.
(1211) Memory type "*" is not valid for this device (Driver)
A command-line option attempted to add a type of memory to this device that is not supported by
this device. For example, adding external RAM to a device that does not have an external memory
interface.
484
Error and Warning Messages
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.
More than one RAMSIZE entry was found in the chipinfo file for this particular chip.
The chip configuration file was not able to be opened for reading. Check that the file’s pathname is
correct.
The chip configuration file was able to be opened but was found to be empty. This file may have
been corrupted.
The input command file could not be opened for reading. Check that the file’s pathname is correct.
The assembler attempted to create a cross reference file, but it could not be created. Check that the
file’s pathname is correct.
The assembler could not open or create an assembler listing file. Check that the file’s pathname is
correct. Is the file attempting to be created in a read-only directory or is the file already open in
another application?
485
Error and Warning Messages
486
Error and Warning Messages
(1232) persistent data may be corrupted during asynchronous reset (see errata) (Driver)
For some PIC18 chips, data may become corrupted during the event of an asynchronous reset. Refer
to the Microchip errata document for more details about how this chip is affected. This
(1234) ** (Driver)
Listing a silicon defect that the compiler is working around. Software workarounds generally in-
crease the overall code size. Refer to the errata document for the device you are using to see whether
the defect affects your program. If not, you may save space by disabling the workaround.
487
Error and Warning Messages
void (*fp)(int);
fp(23); /* oops -- what function does fp point to? */
488
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.
(1249) could not find space (* byte*) for variable * in access bank (Code Generator)
The code generator could not find space in the access bank RAM for the variable specified. Variables
qualifed as near are forced into this area of memory.
(1250) could not find space (* byte*) for variable * (Code Generator)
The code generator could not find space in the banked RAM for the variable specified.
Variables were qualified as far in the source code, but no memory has been specified to hold these
objects. Variables qualfiied as far will reside in the program space memory, but are writable. Mem-
ory can be secified using the --RAM option with address ranges above the top of the on-chip program
space memory.
(1252) could not find space (* byte*) for variable * in far RAM (Code Generator)
The code generator could not find space in RAM for the psect that holds variables qualified as far.
(1253) could not find space (* byte*) for auto/param block (Code Generator)
The code generator could not find space in RAM for the psect that holds auto and parameter vari-
ables.
(1254) could not find space (* byte*) for data block (Code Generator)
The code generator could not find space in RAM for the data psect that holds initialised variables.
489
Error and Warning Messages
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 was in src? */
(1258) possible stack overflow when calling function "*" (Code Generator)
The call tree analysis by the code generator indicates that the hardware stack may overflow. This
should be treated as a guide only. Interrupts, the assembler optimizer and the program structure may
affect the stack usage. The stack usuage is based on the C program and does not include any call
tree derived from assembly code.
The driver has been given contradictory options of compile for speed and compile for space, e.g.
--opt=speed,space
490
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 pointer to one kind of structure has been converted to another kind of structure and the structures
do not have a similar definition, e.g.
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 same struct as TWO? */
(1267) fixup overflow referencing * * (0x*) into * byte* at 0x* (*** */0x*) (Linker)
491
Error and Warning Messages
(1268) fixup overflow storing 0x* in * byte* at 0x* (*** */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.
(1269) there * * day* left until this licence will expire (Driver)
This compiler has not been activated and is running as a demo. The time indicated is how long the
demo period will continue.
(1284) malformed mapfile while generating summary: CLASS expected but not found(Driver)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
492
Error and Warning Messages
(1286) malformed mapfile while generating summary: no link address at position * (Driver)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
(1287) malformed mapfile while generating summary: no load address at position * (Driver)
This is an internal compiler error. Contact HI-TECH Software technical support with details.
(1294) there is only one day left until this licence expires (Driver)
The compiler was fully activated for a limited evaluation period. That period is about to expire in
one day. When expired the compiler will switch to Lite mode - if available - or cease to function. To
fully reactivate the compiler a valid serial number is required. Please contact our sales department
for more details.
493
Error and Warning Messages
(1295) there are * days left until this licence will expire (Driver)
The compiler was fully activated for a limited evaluation period. That period expire soon. When
expired the compiler will switch to Lite mode - if available - or cease to function. To fully reactivate
the compiler a valid serial number is required. Please contact our sales department for more details.
(1302) could not find valid ELF output extension for this device (Cromwell)
The extension could not be for the target device family.
494
Error and Warning Messages
--RUNTIME=default,speed:0y1234
(1310) specified speed (*Hz) exceeds max operating frequency (*Hz), defaulting to *Hz
(Driver)
The frequency specified to the perform suboption to --RUNTIME option is too large for the selected
device.
--RUNTIME=default,speed:0xffffffff
(1311) missing configuration setting for config word *, using default (Driver)
The configuration settings for the indicated word have not be supplied in the source code and a
default value will be used.
495
Error and Warning Messages
(1312) conflicting runtime perform sub-option and configuration word settings, assuming
*Hz (Driver)
The configuration settings and the value specified with the perform suboption of the --RUNTIME
options conflict and a default frequency has been selected.
--OUTPUT=intel:8
496
Error and Warning Messages
497
Error and Warning Messages
(1343) hexfile data at address 0x* (0x*) overwritten with 0x* (Objtohex)
The indicated address is about to be overwritten by additional data. This would indicate more than
one section of code contributing to the same address.
(1346) can’t find 0x* words for psect "*" in segment "*" (largest unused contiguous range
0x%lX) (Linker)
See also message (491). The new form of message also indicates the largest free block that the
linker could find. Unless there is a single space large enough to accommodate the psect, the linker
will issue this message. Often when there is banking or paging involved the largest free space is
much smaller than the total amount of space remaining.
(1347) can’t find 0x* words (0x* withtotal) for psect "*" in segment "*" (largest unused
contiguous range 0x%lX) (Linker)
See also message (593). The new form of message also indicates the largest free block that the
linker could find. Unless there is a single space large enough to accommodate the psect, the linker
will issue this message. Often when there is banking or paging involved the largest free space is
much smaller than the total amount of space remaining.
More than one enum tag with the same name has been defined, The previous definition is indicated
in the message.
(1350) pointer operands to "-" must reference the same array (Code Generator)
If two addresses are subtracted, the addresses must be of the same object to be ANSI compliant.
int * ip;
int fred, buf[20];
ip = &buf[0] - &fred; // oops --second operand must be an address of
// a "buf" element
498
Error and Warning Messages
#include <htc.h>
void main(void) {
delay(0x400000); /* oops -- cannot delay by this number of cycles */
}
(1356) fixup overflow referencing * * (0x*) into * byte* at 0x*/0x* -> 0x* (*** */0x*) (Linker)
See also message (477). This form of the message calculates the address of the offending instruction
taking into account the delta value of the psect which contains the instruction.
(1357) fixup overflow storing 0x* in * byte* at 0x*/0x* -> 0x* (*** */0x*) (Linker)
See also message (477). This form of the message calculates the address of the offending instruction
taking into account the delta value of the psect which contains the instruction.
499
Error and Warning Messages
500
Error and Warning Messages
(1371) float type can’t be bigger then double type; double has been changed to * bits (Driver)
Use of the --float and --double options has result in the size of the double type being smaller
than that of the float type. This is not permitted by the C Standard. The double type size has been
increased to be that indicated.
(1375) multiple interrupt functions (* and *) defined for device with only one interrupt vector
(Code Generator)
The named functions have both been qualified interrupt, but the target device only supports one
interrupt vector and hence one interrupt function.
interrupt void isr_lo(void) {
// ...
}
interrupt void isr_hi(void) {
// ...
}
(1376) initial value (*) too large for bitfield width (*) (Code Generator)
A structure with bit-fields has been defined an initialized with values. The value indicated it too
large to fit in the corresponding bitfield width.
struct {
unsigned flag :1;
unsigned mode :3;
}
foobar={1,100}; //oops, 100 is too large for a 3-bit wide object
501
Error and Warning Messages
(1390) identifier specifies insignificant characters beyond maximum identifier length (Parser)
An identifier has been used that is so long that it exceeds the set identifier length. This may mean
that long identifiers may not be correctly identified and the code will fail. The maximum identifier
length can be adjusted using the -N option.
(1393) possible hardware stack overflow detected, estimated stack depth: * (Code
Generator)
The compiler has detected that the call graph for a program may be using more stack space that
allocated on the target device. If this is the case, the code may fail. The compiler can only make
assumptions regarding the stack usage when interrupts are involved and these lead to a worst-case
estimate of stack usage. Confirm the function call nesting if this warning is issued.
(1394) attempting to create memory range ( * - * ) larger than page size, * (Driver)
The compiler driver has detected that the memory settings include a program memory “page” that
is larger than the page size for the device. This would mostly likely be the case if the --ROM option
is used to change the default memory settings. Consult you device data sheet to determine the page
size of the device you are using and ensure that any contiguous memory range you specify using the
--ROM option has a boundary that corresponds to the device page boundaries.
--ROM=100-1fff
502
Error and Warning Messages
The above may need to be paged. If the page size is 800h, the above could specified as
--ROM=100-7ff,800-fff,1000-17ff,1800-1fff
(1395) notable code sequence candidate suitable for compiler validation suite detected (*)
(Code Generator)
The compiler has in-built checks that can determine if combinations of internal code templates have
been encountered. Where unique combinations are uncovered when compiling code, this message
is issued. This message is not an error or warning, and its presence does not indicate possible code
failure, but if you are willing to participate, the code you are compiling can be sent to Support to
assist with the compiler testing process.
(1396) "*" positioned in the * memory region (0x* - 0x*) reserved by the compiler (Code
Generator)
Some memory regions are reserved for use by the compiler. These regions are not normally used
to allocate variables defined in your code. However, by making variables absolute, it is possible
to place variables in these regions and avoid errors that would normally be issued by the linker.
(Absolute variables can be placed at any location, even on top of other objects.) This warning from
the code generator indicates that an absolute has been detected that will be located at memory that
the compiler will be reserving. You must locate the absolute variable at a different location. This
message will commonly be issued when placing variables in the common memory space.
(1397) unable to implement non-stack call to "*"; possible hardware stack overflow (Code
Generator)
The compiler must encode a C function call without using a CALL assembly instruction and the
hardware stack (and instead use a lookup table), but is unable to. A call might be required if the
function is called indirectly via a pointer, but if the hardware stack is already full, an additional call
will cause a stack overflow.
(1401) eeprom qualified variables cannot be accessed from both interrupt and mainline code
(Code Generator)
All eeprom variables are accessed via routines which are not reentrant. Code might fail if an attempt
is made to access eeprom variables from interrupt and main-line code. Avoid accessing eeprom
variables in interrupt functions.
503
Error and Warning Messages
(1402) a pointer to eeprom cannot also point to other data types (Code Generator)
A pointer cannot have targets in both the eeprom space and ordinary data space.
(1410) Cannot assign the result of an invalid function pointer (Code Generator)
The compiler will allow some functions to be called via a constant cast to be a function pointer, but
not all. The address specified is not valid for this device.
foobar += ((int (*)(int))0x0)(77);
// oops -- you cannot call a function with a NULL pointer
504
Error and Warning Messages
Following the #pragma warning disable should be a comma-separated list of message numbers
to disable.
The librarian requires one or more modules to be listed for deletion when using the d key, e.g.:
libr d c:\ht-pic\lib\pic704-c.lib
The IDENT record in the object file was incomplete. Contact HI-TECH Support with details.
The SYM record in the object file was incomplete. Contact HI-TECH Support with details.
No symbols were found in the module’s object file. This may be what was intended, or it may mean
that part of the code was inadvertently removed or commented.
505
Error and Warning Messages
libr r lcd.lib
This command needs the name of a module (.obj file) after the library name.
506
Appendix C
Chip Information
The following table lists all devices currently supported by HI-TECH C Compiler for PIC18 MCUs.
507
Chip Information
508
Chip Information
509
Chip Information
510
Chip Information
511
Chip Information
512
Chip Information
513
Chip Information
514
Index
515
INDEX INDEX
516
INDEX INDEX
517
INDEX INDEX
518
INDEX INDEX
519
INDEX INDEX
520
INDEX INDEX
521
INDEX INDEX
522
INDEX INDEX
523
INDEX INDEX
524
INDEX INDEX
525
INDEX INDEX
526
INDEX INDEX
527
INDEX INDEX
528
INDEX INDEX
529
INDEX INDEX
530
INDEX INDEX
531
INDEX INDEX
startup.as, 31 file, 65
static variables, 114 hex, 65
STDIO, 152 mem, 65
storage class, 110 psect, 65
strcat function, 321 switch pragma directive, 146
strchr function, 322 symbol files, 43
strcmp function, 324 Avocet format, 197
strcpy function, 326 enhanced, 193
strcspn function, 327 generating, 193
strichr function, 322 local symbols in, 197
stricmp function, 324 old style, 191
string literals, 94, 224 removing local symbols from, 49
concatenation, 94 removing symbols from, 196
String packing, 225 source level, 43
strings symbol tables, 194, 196
assembly, 160 sorting, 194
storage location, 94, 224 symbols
type of, 94 assembler-generated, 161
stristr function, 338 global, 188, 205
strlen function, 328 linker defined, 152
strncat function, 329 undefined, 196
strncmp function, 331
strncpy function, 333 table read instruction, 116
strnicmp function, 331 tan function, 345
strpbrk function, 335 tanh function, 253
strrchr function, 336 temporary files, 57
strrichr function, 336 text psect, 125
strspn function, 337 time function, 346
strstr function, 338 time switch type, 146
strtod function, 339 Timers, 310
strtok function, 343 timers function, 356
strtol function, 341 TITLE assembler control, 179
struct psect, 119 toascii function, 348
structures tolower function, 348
bit-fields, 99 toupper function, 348
qualifiers, 100 translation unit, 23
SUBTITLE assembler control, 179 trunc function, 349
SUMMARY option type checking
class, 65 assembly routines, 131
532
INDEX INDEX
W register, 159
warning level, 65
setting, 197
533
INDEX INDEX
534
PICC18 Command-line Options
Option Meaning
-C Compile to object files only
-Dmacro Define preprocessor macro
-E+file Redirect and optionally append errors to a file
-Gfile Generate source-level debugging information
-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 Output file name
-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
--ADDRQUAL Set compiler response to memory qualifier
--ASMLIST Generate assembler list file
Calculate a checksum
--CHECKSUM=start-end@destination<,specs>
--CHIP=processor Selects which processor to compile for
--CHIPINFO Displays a list of supported processors
--CMODE Specify compiler compatibility mode
--CODEOFFSET=address Offset program code to address
--CR=file Generate cross-reference listing
--DEBUGGER=type Select the debugger that will be used
--DOUBLE=size Selects size of double type
--ECHO Echo command line
--EMI=type Select mode of the external memory interface
--ERRATA=type Add or remove specific software workarounds for sil-
icon errata issues.
--ERRFORMAT<=format> Format error message strings to the given style
--ERRORS=number Sets the maximun number of errors displayed
--FILL Specify fill value for unused program memory
--FLOAT=size Selects size of float type
continued. . .
PICC18 Command-line Options
Option Meaning
--GETOPTION=app,file Get the command line options for the named applica-
tion
--HELP<=option> Display the compiler’s command line options
--HTML Generate HTML debug files
--IDE=ide Configure the compiler for use by the named IDE
--LANG=language Specify language for compiler messages
--MEMMAP=file Display memory summary information for the map
file
--MODE=mode Choose compiler operating mode
--MSGDISABLE=messagelist Disable Warning Messages
--MSGFORMAT<=format> Format general message strings to the given style
--NODEL Do not remove temporary files generated by the com-
piler
--NOEXEC Go through the motions of compiling without actually
compiling
--OBJDIR=path Specify intermediate files’ directory
--OPT<=type> Enable general compiler optimizations
--OUTDIR=path Specify output files directory
--OUTPUT=type Generate output file type
--PRE Produce preprocessed source files
--PROTO Generate function prototype information
--RAM=lo-hi<,lo-hi,...> Specify and/or reserve RAM ranges
--ROM=lo-hi<,lo-hi,...> Specify and/or reserve ROM ranges
--RUNTIME=type Configure the C runtime libraries to the specified type
--SCANDEP Generate file dependency “.DEP files”
--SERIAL=hexcode@address Store a value in program memory
--SETOPTION=app,file Set the command line options for the named applica-
tion
--SETUP=argument Setup the product
--SHROUD Obfusate p-code files
--STRICT Enable strict ANSI keyword conformance
--SUMMARY=type Selects the type of memory summary output
--TIME Report compilation times
--VER Display the compiler’s version number
--WARN=level Set the compiler’s warning level
continued. . .
PICC18 Command-line Options
Option Meaning
--WARNFORMAT=format Format warning message strings to given style