Note the following details of the code protection feature on Microchip devices:
•Microchip products meet the specification contained in their particular Microchip Data Sheet.
•Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the
intended manner and under normal conditions.
•There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our
knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data
Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
•Microchip is willing to work with the customer who is concerned about the integrity of their code.
•Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not
mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our
products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts
allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Information contained in this publication regarding device
applications and t he lik e is provided only for your convenience
and may be su perseded by upda t es . It is y our responsibility to
ensure that your application meets with your specifications.
MICROCHIP MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND WHETHER EXPRESS OR
IMPLIED, WRITTEN OR ORAL, STATUTORY OR
OTHERWISE, RELATED TO THE INFORMATION,
INCLUDING BUT NOT LIMITED TO ITS CONDITION,
QUALITY, PERFORMANCE, MERCHANTABILITY OR
FITNESS FOR PURPOSE. Microchip disclaims all liability
arising from this information and its use. Use of Microchip
devices in life supp ort and/or safety ap plications is entir ely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless M icrochip from any and all dama ges, claims,
suits, or expenses re sulting from such use. No licens es are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, dsPIC,
K
logo, rfPIC and UNI/O are registered trademarks of
Microchip Technology Incorporated in the U.S.A. and other
countries.
FilterLab, Hampshire, HI-TECH C, Linear Active Thermistor,
MXDEV, MXLAB, SEEVAL and The Embedded Control
Solutions Company are registered trademarks of Microchip
Technology Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, chipKIT,
chipKIT logo, CodeGuard, dsPICDEM, dsPICDEM.net,
dsPICworks, dsSPEAK, ECAN, ECONOMONITOR,
FanSense, HI-TIDE, In-Circuit Serial Programming, ICSP,
Mindi, MiWi, MPASM, MPLAB Certified logo, MPLIB,
MPLINK, mTouch, Omniscient Code Generation, PICC,
PICC-18, PICDEM, PICDEM.net, PICkit, PICtail, REAL ICE,
rfLAB, Select Mode, Total Endurance, TSHARC,
UniWinDriver, WiperLock and ZENA are trademarks of
Microchip Technology Incorporated in the U.S.A. and other
countries.
SQTP is a service mark of Microchip Technology Incorporated
in the U.S.A.
All other trademarks mentioned herein are property of their
respective companies.
Microchip received ISO/TS-16949:2002 certification for its worldwide
headquarters, design and wafer fabrication facilities in Chandler and
Tempe, Arizona; Gresham, Oregon and design centers in California
and India. The Company’s quality system processes and procedures
are for its PIC
devices, Serial EEPROMs, microperipherals, nonvolatile memory and
analog products. In addition, Microchip’s quality system for the design
and manufacture of development systems is ISO 9001:2000 certified.
®
MCUs and dsPIC® DSCs, KEELOQ
®
code hopping
DS51284K-page 2 2002-2011 Microchip Technology Inc.
Index ...........................................................................................................................255
Worldwide Sales and Service ...................................................................................265
DS51284J3-page 6Update Draft 2003-2011 Microchip Technology Inc.
MPLAB® C COMPILER FOR
PIC24 MCUs AND dsPIC
®
DSCs
USER’S GUIDE
Preface
NOTICE TO CUSTOMERS
All documentation becomes dated, and this manual is no exception. Microchip tools and
documentation are constantly evolving to meet customer needs, so some actual dialogs
and/or tool descriptions may differ from those in this document. Please refer to our web site
(www.microchip.com) to obtain the latest documentation available.
Documents are identified with a “DS” number. This number is located on the bottom of each
page, in front of the p age number. The numbering convention for the DS number is
“DSXXXXXA”, where “XXXXX” is the document number and “A” is the revision level of the
document.
For the most up-to-date information on development tools, see the MPLAB
Select the Help menu, and then Topics to open a list of available on-line help files.
®
IDE on-line help.
INTRODUCTION
This chapter contains general information that will be useful to know before using the
MPLAB C Compiler for PIC24 MCUs and dsPIC
• Document Layout
• Conventions Used in this Guide
• Recommended Reading
• The Microchip Web Site
• Development Systems Customer Change Notification Service
This document describes how to use GNU language tools to write code for 16-bit
applications. The document layout is as follows:
• Chapter 1: Compiler Overview – describes the compiler, development tools and
feature set.
• Chapter 2: Differences between 16-Bit Device C and ANSI C – describes the
differences between the C language supported by the compiler syntax and the
standard ANSI-89 C.
• Chapter 3: Using the Compiler on the Command Line – describes how to use
the compiler from the command line.
• Chapter 4: Run Time Environment – describes the compiler run-time model,
including information on sections, initialization, memory models, the software stack
and much more.
• Chapter 5: Data Types – describes the compiler integer, floating point and pointer
data types.
• Chapter 6: Additional C Pointers – describes additional C pointers available.
• Chapter 7: Device Support Files – describes the compiler header and register
definition files, as well as how to use with SFRs.
• Chapter 8: Interrupts – describes how to use interrupts.
• Chapter 9: Mixing Assembly Language and C Modules – provides guidelines to
using the compiler with 16-bit assembly language modules.
• Appendix A: Implementation-Defined Behavior – details compiler-specific
parameters described as implementation-defined in the ANSI standard.
• Appendix B: Built-in Functions – lists the built-in functions of the C compiler.
• Appendix C: Diagnostics – lists error and warning messages generated by the
compiler.
• Appendix D: MPLAB C C o mpi ler f or PIC 18 MC Us v s. 16 -Bi t D evice s – highlights
the differences be tween the PI C18 MCU C compil er and th e 16-bit C com piler.
• Appendix E: Deprecated Features – details features that are considered
obsolete.
• Appendix F: ASCII Character Set – contains the ASCII character set.
• Appendix G: GNU Free Documentation License – usage license for the Free
Software Foundation.
DS51284K-page 8 2002-2011 Mic rochip Technology Inc.
CONVENTIONS USED IN THIS GUIDE
STD
DD
The following conventions may appear in this documentation:
DOCUMENTATION CONVENTIONS
DescriptionRepresentsExamples
Arial font:
Italic chara c tersReferenced booksMPLAB
Initial capsA windowthe Output window
QuotesA field name in a window or
Underlined, italic text with
right angle bracket
Bold charactersA dialog buttonClick OK
Text in angle brackets < >A key on the keyboardPress <Enter>, <F1>
Courier font:
Plain CourierSample source code#define START
Italic CourierA variable argumentfile.o, where file can be
Choice of mut ually exclus ive
arguments; an OR selection
Represents code supplied by
user
Standard edition only.
This feature su ppo rted only in
the standard edition of the
software, i.e., not suppo rted in
standard evaluation (after 60
days) or lite editions.
Device Dependent.
This feature is not supported
on all devices. Devices supported will be listed in the title
or text.
This documentation describes how to use the MPLAB C Compiler for PIC24 MCUs and
dsPIC DSCs. Other useful documents are listed below. The following Microchip
documents are available and recommended as supplemental reference resources.
Readme Files
For the latest information on Microchip tools, read the associated Readme files (HTML
files) included with the software.
16-Bit Language Tools Getting Started (DS70094)
A guide to installing and working with the Microchip language tools for 16-bit devices.
Examples using the 16-bit simulator SIM30 (a component of MPLAB SIM) are
provided.
MPLAB
User’s Guide (DS51317 )
A guide to using the 16-bit assembler, object linker, object archiver/librarian and various
utilities.
16-Bit Language Tools Libraries (DS51456)
A descriptive listing of libraries available for Microchip 16-bit devices. This includes
standard (including math) libraries and C compiler built-in functions. DSP and 16-bit
peripheral libraries are described in Readme files provided with each peripheral library
type.
Device-Specific Documentation
The Microchip website contains many documents that describe 16-bit device functions
and features. Among these are:
• Individual and family data sheets
• Family reference manuals
• Programmer’s reference manuals
C Standards Information
American National Standard for Information Systems – Programming Language – C.
®
Assembler, Linker and Utilities for PIC24 MCUs and dsPIC® DSCs
American National Standards Institute (ANSI), 11 West 42nd. Street, New York,
New York, 10036.
This standard specifies the form and establishes the interpretation of programs
expressed in the programming language C. Its purpose is to promote portability,
reliability, maintainability and efficient execution of C language program s on a
variety of computing systems.
DS51284K-page 10 2002-2011 Microchip Technology Inc.
C Reference Manuals
Harbison, Samuel P . and Steele, Guy L., C A Reference Manual, Fourth Edition,
Prentice-Hall, Englewood Cliffs, N.J. 07632.
Kernighan, Brian W. and Ritchie, Dennis M., The C Programming Language, Secon d
Kochan, Steven G., Programming In ANSI C, Revised Edition. Hayden Books,
Indianapolis, Indiana 46268.
Plauger, P.J., The Standard C Library, Prentice-Hall, Englewood Cliffs, N.J. 07632.
Van Sickle, Ted., Programming Microcontrollers in C, First Edition. LLH Technology
Publishing, Eagle Rock, Virginia 24085.
THE MICROCHIP WEB SITE
Microchip provides online support via our web site at www.microchip.com. This web
site is used as a means to make files and information easily available to customers.
Accessible by using your favorite Internet browser, the web site contains the following
information:
• Product Support – Data sheets and errata, application notes and sample
programs, design resources, user’s guides and hardware support documents,
latest software releases and archived software
• General Technical Support – Frequently Asked Questions (FAQs), technical
support requests, online discussion groups, Microchip consultant program
member listing
• Business of Microchip – Product selector and ordering guides, latest Microchip
press releases, listing of seminars and events, listings of Microchip sales offices,
distributors and factory representatives
DEVELOPMENT SYSTEMS CUSTOMER CHANGE NOTIFICATION SERVICE
Microchip’s customer notification service helps keep customers current on Microchip
products. Subscribers will receive e-mail notification whenever there are changes,
updates, revisions or errata related to a specified product family or development tool of
interest.
To register, access the Microchip web site at www.microchip.com, click on Customer
Change Notification and follow the registration instructions.
The Development Systems product group categories are:
• Compilers – The latest info rmatio n on Microc hip C comp ilers, as semblers , linkers
and other language tools. These include all MPLAB C compilers; all MPLAB
assemblers (including MPASM™ assembler); all MPLAB linkers (including
MPLINK™ object linker); and all MPLAB librarians (including MPLIB™ object
librarian).
• Emulators – The latest information on Microchip in-circuit emulators. These
include the MPLAB REAL ICE™ and MPLAB ICE 2000 in-circuit emulators
• In-Circuit Debuggers – The latest information on Microchip in-circuit debuggers.
These include the MPLAB ICD 2 and 3 in-circuit debuggers and PICkit™ 2 and 3
debug express.
• MPLAB
Integrated Development Environment for development systems tools. This list is
focused on the MPLAB IDE, MPLAB IDE Project Manager, MPLAB Editor and
MPLAB SIM simulator, as well as general editing and debugging features.
• Programmers – The latest information on Microchip programmers. These include
the device (production) programmers MPLAB REAL ICE in-circuit emulator,
MPLAB ICD 3 in-circuit debugger, MPLAB PM3, and PRO MATE II and
development (nonproduction) programmers MPLAB ICD 2 in-circuit debugger,
PICSTART
®
IDE – The latest information on Microchip MPLAB IDE, the Windows®
®
Plus and PICkit 1, 2 and 3.
CUSTOMER SUPPORT
Users of Microchip products can receive assistance through several channels:
• Distributor or Representative
• Local Sales Office
• Field Application Engineer (FAE)
• Technical Support
Customers should contact their distributor, representative or field application engineer
(FAE) for support. Local sales offices are also available to help customers. A listing of
sales offices and locations is included in the back of this document.
Technical support is available through the web site at: http://support.microchip.com
DS51284K-page 12 2002-2011 Microchip Technology Inc.
Chapter 1. Compiler Overview
1.1INTRODUCTION
The dsPIC® family of Digital Signal Controllers (dsPIC30F and dsPIC33F DSCs) combines the high performance required in DSP applications with standard microcontroller
features needed for embedded applications. PIC24 MCUs are identical to the dsPIC
DSCs with the exception that they do not have the digital signal controller module or
that subset of instructions. They are a subset and are high-performance microcontrollers intended for applications that do not require the power of the DSC
capabilities.
All of these devices are fully supported by a complete set of software development
tools, including an optimizing C compiler, an assembler, a linker and an archiver/
librarian.
This chapter provides an overview of these tools and introduces the features of the
optimizing C compiler, including how it works with the assembler and linker. The
assembler and linker are discussed in detail in the “MPLAB
Utilities for PIC24 MCUs and dsPIC
MPLAB® C COMPILER FOR
PIC24 MCUs AND dsPIC
USER’S GUIDE
®
®
DSCs User’s Guide” (DS51317).
Assembler, Linker and
®
DSCs
1.2HIGHLIGHTS
Items discussed in this chapter are:
• Compiler Description and Documentation
• Compiler and Other Development Tools
• Compiler Feature Set
1.3COMPILER DESCRIPTION AND DOCUMENTATION
There are three Microchip compilers that support various Microchip 16-bit devices.
Also, each one of these compilers comes in different editions, which support different
levels of optimization.
MPLAB® C Compiler forDevice SupportEdition Support
1 PIC24 MCUs and dsPIC
2 dsPIC DSCsdsPIC30F/33F DSCsStd, Std Eval, Lite
3 PIC24 MCUsPIC24F/H MCUsStd, Std Eval, Lite
Each compiler is an ANSI x3.159-1989-compliant, optimizing C compiler. Each compiler is a Windows
Each compiler is a port of the GCC compiler from the Free Software Foundation.
The first and second compilers include language extensions for dsPIC DSC
embedded-control applications.
®
console application that provides a platform for developing C code.
Each of the three compilers in Section 1.3 “Compiler Description and Documentation” come in one or more of the following editions:
• Standard (Purchased Compiler) – All optimization levels enabled.
• Standard Evaluation (Free) – All optimization levels enabled for 60 days, but then
reverts to optimization level 1 only.
• Lite (Free) – Optimization level 1 only.
1.3.2Compiler Documented in this Manual
This manual describes the standard edition of the Standard (purchased) compiler,
since the Standard Evaluation and Lite compilers are subsets of the first. Features that
are unique to specific devices, and therefore specific compilers, are noted with “DD”
text the column (see the Preface) and text identifying the devices to which the
information applies.
1.4COMPILER AND OTHER DEVELOPMENT TOOLS
The MPLAB C Compiler for PIC24 MCUs and dsPIC DSCs compiles C source files,
producing assembly language files. These compiler-generated files are assembled and
linked with other object files and libraries to produce the final application program in
executable COFF or ELF file format. The COFF or ELF file can be loaded into the
MPLAB IDE, where it can be tested and debugged, or the conversion utility can be used
to convert the COFF or ELF file to Intel
mand-line simulator or a device programmer. See Figure 1-1 for an overview of the
software development data flow.
®
hex format, suitable for loading into the com-
DS51284K-page 14 2002-2011 Microchip Technology Inc.
The compiler is a full-featured, optimizing compiler that translates standard ANSI C
programs into 16-bit device assembly language source. The compiler also supports
many command-line options and language extensions that allow full access to the
16-bit device hardware capabilities, and affords fine control of the compiler code generator. This section describes key features of the compiler.
1.5.1ANSI C Standard
The compiler is a fully validated compiler that conforms to the ANSI C standard as
defined by the ANSI specification and described in Kernighan and Ritchie’s The C Pro-gramming Language (second edition). The ANSI standard includes extensions to the
original C definition that are now standard features of the language. These extensions
enhance portability and offer increased capability.
1.5.2Optimization
The compiler uses a set of sophisticated optimization passes that employ many
advanced techniques for generating efficient, compact code from C source. The
optimization passes include high-level optimizations that are applicable to any C code,
as well as 16-bit device-specific optimizations that take advantage of the particular
features of the device architecture.
1.5.3ANSI Standard Library Support
The compiler is distributed with a complete ANSI C standard library. All library functions
have been validated, and conform to the ANSI C library standard. The library includes
functions for string manipulation, dynamic memory allocation, data conversion, timekeeping and math functions (trigonometric, exponential and hyperbolic). The standard
I/O functions for file handling are also included, and, as distributed, they support full
access to the host file system using the command-line simulator. The fully functional
source code for the low-level file I/O functions is provided in the compiler distribution,
and may be used as a starting point for applications that require this capability.
1.5.4Flexible Memory Models
The compiler supports both large and small code and data models. The small code
model takes advantage of more efficient forms of call and branch instructions, while the
small data model supports the use of compact instructions for accessing data in SFR
space.
The compiler supports two models for accessing constant data. The “constants in data”
model uses d ata memory, which is initiali ze d b y t h e ru n -t ime li brary. The “constants in
code” model uses program memory, which is accessed through the Program Space
Visibility (PSV) window.
1.5.5Compiler Driver
The compiler includes a powerful command-line driver program. Using the driver
program, application programs can be compiled, assembled and linked in a single step
(see Figure 1-1).
DS51284K-page 16 2002-2011 Microchip Technology Inc.
MPLAB® C COMPILER FOR
PIC24 MCUs AND dsPIC® DSCs
USER’S GUIDE
Chapter 2. Differences Between 16-Bit Device C and ANSI C
2.1INTRODUCTION
This section discusses the differences between the C language supported by MPLAB
C Compiler for PIC24 MCUs and dsPIC
1989 standard ANSI C.
2.2HIGHLIGHTS
Items discussed in this chapter are:
• Keyword Differences
• Statement Differences
• Expression Differences
2.3KEYWORD DIFFERENCES
This section describes the keyword differences between plain ANSI C and the C
accepted by the 16-bit device compiler. The new keywords are part of the base GCC
implementation, and the discussion in t his section is b ased on the st andard GCC do cumentation, tailored for the specific syntax and semantics of the 16-bit compiler por t of
GCC.
The compiler keyword __attribute__ allows you to specify special attributes of
variables or structure fields. This keyword is followed by an attribute specification inside
double parentheses. The following attributes are currently supported for variables:
• address (addr)
• aligned (alignment)
• boot
• deprecated
• eds
• fillupper
• far
• mode (mode)
• near
• noload
• page
• packed
• persistent
• reverse (alignment)
• section ("section-name")
• secure
• sfr (address)
• space (space)
• transparent_union
• unordered
• unused
• weak
You may also specify attributes with __ (double underscore) preceding and following
each keyword (e.g., __aligned__ instead of aligned). This allows you to use them
in header files without being concerned about a possible macro of the same name.
To specify multiple attributes, separate them by commas within the double
parentheses, for example:
__attribute__ ((aligned (16), packed)).
Note:It is important to use variable attributes consistently throughout a project.
For example, if a variable is defined in file A with the far attribute, and
declared extern in file B without far, then a link error may result.
address (addr)
The address attribute specifies an absolute address for the variable. This attribute
can be used in conjunction with a section attribute. This can be used to start a group
of variables at a specific address:
int foo __attribute__((section("mysection"),address(0x900)));
int bar
int baz
A variable with the address attribute cannot be placed into the auto_psv space (see
the space() attribute or the -mconst-in-code option); attempts to do so will cause
a warning and the compiler will place the variable into the PSV space. If the variable is
to be placed into a PSV section, the address should be a program memory address.
DS51284K-page 18 2002-2011 Microchip Technology Inc.
This attribute specifies a minimum alignment for the variable, measured in bytes. The
alignment must be a power of two. For example, the declaration:
int x __attribute__ ((aligned (16))) = 0;
causes the compiler to allocate the global variable x on a 16-byte boundary. On the
dsPIC DSC device, this could be used in conjunction with an asm expression to access
DSP instructions and addressing modes that require aligned operands.
As in the preceding example, you can explicitly specify the alignment (in bytes) that you
wish the compiler to use for a given variable. Alternatively, you can leave out the
alignment factor and just ask the compiler to align a variable to the maximum useful
alignment for the dsPIC DSC device. For example, you could write:
short array[3] __attribute__ ((aligned));
Whenever you leave out the alignment factor in an aligned attribute specification, the
compiler automatically sets the alignment for the declared variable to the largest
alignment for any data type on the target machine – which in the case of the dsPIC DSC
device is two bytes (one word).
The aligned attribute can only increase the alignment; but you can decrease it by
specifying packed (see below). The aligned attribute conflicts with the reverse
attribute. It is an error condition to specify both.
The aligned att ribute can be combin ed with th e section attribute. This will allow the
alignment to take place in a named section. By default, when no section is specified,
the compiler will generate a unique section for the variable. This will provide the linker
with the best opportunity for satisfying the alignment restriction without using internal
padding that may happen if other definitions appear within the same aligned section.
boot
This attribute can be used to define protected variables in Boot Segment (BS) RAM:
int __attribute__((boot)) boot_dat[16];
V ariables defined in BS RAM will not be initialized on startup. Therefore all variables in
BS RAM must be initialized using inline code. A diagnostic will be reported if initial
values are specified on a boot variable.
An example of initialization is as follows:
int __attribute__((boot)) time = 0; /* not supported */
int __attribute__((boot)) time2;
void __attribute__((boot)) foo()
{
time2 = 55; /* initial value must be assigned explicitly */
}
The deprecated attribute causes the declaration to which it is attached to be specially
recognized by the compiler. When a deprecated function or variable is used, the
compiler will emit a warning.
A deprecated definition is still defined and, therefore, present in any object file. For
example, compiling the following file:
int __attribute__((__deprecated__)) i;
int main() {
return i;
}
will produce the warning:
deprecated.c:4: warning: `i’ is deprecated (declared
at deprecated.c:1)
i is still defined in the resulting object file in the normal way.
eds
In the attribute context the eds, for extended data space, attribute indicates to the compiler that the variable will may be allocated anywhere within data memory. Variables
with this attribute will likely also need the __eds__ type qualifier (see Chapter
6. “Additional C Pointer Types”) in order for the compiler to properly generate the
correct access sequence. Note that the __eds__ qualifier and the eds attribute are
closely related, but not identical. On some devices, eds may need to be specified when
allocating variables into certain memory spaces such as space(ymemory) or
space(dma) as this memory may only exist in the extended data space.
fillupper
This attribute can be used to specify the upper byte of a variable stored into a
space(prog) section.
For example:
int foo[26] __attribute__((space(prog),fillupper(0x23))) = { 0xDEAD };
will fill the upper bytes of array foo with 0x23, instead of 0x00. foo[0] will still be
initialized to 0xDEAD.
The command line option -mfillupper=0x23 will perform the same function.
far
The far attribute tells the compiler that the variable will not necessarily be allocated in
near (first 8 KB) data space, (i.e., the variable can be located anywhere in data memory
between 0x0000 and 0x7FFF).
mode (mode)
This attribute specifies the data type for the declaration as whichever type corresponds
to the mode mode. This in effect lets you request an integer or floating point type
according to its width. Valid values for mode are as follows:
ModeWidthCompiler Type
QI8 bitschar
HI16 bitsint
SI32 bitslong
DI64 bitslong long
SF32 bitsfloat
DF64 bitslong double
DS51284K-page 20 2002-2011 Microchip Technology Inc.
Differences Between 16-Bit Device C and ANSI C
This attribute is useful for writing code that is portable across all supported compiler targets. For example, the following function adds two 32-bit signed integers and returns a
32-bit signed integer result:
typedef int __attribute__((__mode__(SI))) int32;
int32
add32(int32 a, int32 b)
{
return(a+b);
}
Y ou may also specify a mode of byte or __byte__ to indicate the mode corresponding to a one-byte integer, word or __word__ for the mode of a one-word integer, and
pointer or __pointer__ for the mode used to represent pointers.
near
The near attribute tells the compiler that the variable is allocated in near data space
(the first 8 KB of data memory). Such variables can sometimes be accessed more
efficiently than variables not allocated (or not known to be allocated) in near data
space.
int num __attribute__ ((near));
noload
The noload attribute indicates that space should be allocated for the variable, but that
initial values should not be loaded. This attribute could be useful if an application is
designed to load a variable into memory at run time, such as from a serial EEPROM.
int table1[50] __attribute__ ((noload)) = { 0 };
page
The page attribute places variable definitions into a specific page of memory. The page
size depends on the type of memory selected by a space attribute. Objects residing in
RAM will be constrained to a 32K page while objects residing in Flash will be constrained to a 64K page (upper byte not included).
unsigned int var[10] __attribute__ ((space(auto_psv)));
The space(auto_psv) or space(psv) attribute will use a single memory page by
default.
__eds__ unsigned int var[10] __attribute__ ((space(eds), page));
When dealing with space(eds), please refer to Chapter 6. “Additional C Pointer
Types” for more information.
packed
The packed attribute specifies that a structure member should have the smallest
possible alignment unless you specify a larger value with the aligned attribute.
Here is a structure in which the member x is packed, so that it immediately follows a,
with no padding for alignment:
struct foo
{
char a;
int x[2]
};
__attribute__ ((packed));
Note:The device architecture requires that words be aligned on even byte
boundaries, so care must be taken when using the packed attribute to
avoid run-time addressing errors.
The persistent attribute specifies that the variable should not be initialized or
cleared at startup. A variable with the persistent attribute could be used to store state
information that will remain valid after a device reset.
int last_mode __attribute__ ((persistent));
Persistent data is not normally initialized by the C run-time. However, from a
cold-restart, persistent data may not have any meaningful value. This code example
shows how to safely initialize such data:
#include "p24Fxxxx.h"
int last_mode __attribute__((persistent));
int main()
{
if ((RCONbits.POR == 0) &&
(RCONbits.BOR == 0)) {
/* last_mode is valid */
} else {
/* initialize persistent data */
last_mode = 0;
}
}
reverse (alignment)
The reverse attribute specifies a minimum alignment for the ending address of a
variable, plus one. The alignment is specified in bytes and must be a power of two.
Reverse-aligned variables can be used for decrementing modulo buffers in dsPIC DSC
assembly language. This attribute could be useful if an application defines variables in
C that will be accessed from assembly language.
int buf1[128] __attribute__ ((reverse(256)));
The reverse attribute conflicts with the aligned and section attributes. An attempt
to name a section for a reverse-aligned variable will be ignored with a warning. It is an
error conditi on to specify both reverse and aligned for the same variable. A variable
with the reverse attribute cannot be placed into the auto_psv space (see the
space() attribute or the -mconst-in-code option); attempts to do so will cause a
warning and the compiler will place the variable into the PSV space.
section ("section-name")
By default, the compiler places the objects it generates in sections such as .data and
.bss. The section attribute allows you to override this behavior by specifying that a
variable (or function) lives in a particular section.
struct a { int i[32]; };
struct a buf
__attribute__((section("userdata"))) = {{0}};
secure
This attribute can be used to define protected variables in Secure Segment (SS) RAM:
int __attribute__((secure)) secure_dat[16];
V ariables defined in SS RAM will not be initialized on startup. Therefore all variables in
SS RAM must be initialized using inline code. A diagnostic will be reported if initial
values are specified on a secure variable.
DS51284K-page 22 2002-2011 Microchip Technology Inc.
Differences Between 16-Bit Device C and ANSI C
DD
DD
String literals can be assigned to secure variables using inline code, but they require
extra processing by the compiler. For example:
In this case, storage must be allocated for the string literal in a memory space which is
accessible to the enclosing secure function. The compiler will allocate the string in a
psv constant section designated for the secu re segment.
sfr (address)
The sfr attribute tells the compiler that the variable is an SFR and also specifies the
run-time address of the variable, using the address parameter.
extern volatile int __attribute__ ((sfr(0x200)))u1mod;
The use of the extern specifier is required in order to not produce an error.
Note:By convention, the sfr attribute is used only in processor header files. To
define a general user variable at a specific address use the address attribute in conjunction with near or far to specify the correct addressing
mode.
space (space)
Normally, the compiler allocates variables in general data space. The space attribute
can be used to direct the compiler to allocate a variable in specific memory spaces.
Memory spaces are discussed further in Section 4.5 “Memory Spaces”. The
following arguments to the space attribute are accepted:
data
Allocate the variable in general data space. V ariables in general data space can
be accessed using ordinary C statements. This is the default allocation.
eds
Allocate the variable in the extended data space. For devices that do not have
extended data space, this is equivalent to space(data). Variables in
space(eds) will generally require special handling to access. Refer to Chapter
6. “Additional C Pointer Types” for more information.
space(eds) has been deprecated in favour of the eds attribute.
xmemory - dsPIC30F/33F DSCs only
Allocate the variable in X data space. Variables in X data space can be accessed
using ordinary C statements. An example of xmemory space allocation is:
int x[32] __attribute__ ((space(xmemory)));
ymemory - dsPIC30F/33F DSCs only
Allocate the variable in Y data space. Variables in Y data space can be accessed
using ordinary C statements. An example of ymemory space allocation is:
Allocate the variable in program space, in a section designated for executable
code. Variables in program space can not be accessed using ordinary C
statements. They must be explicitly accessed by the programmer, usually using
table-access inline assembly instructions, or using the program space visibility
window.
auto_psv
Allocate the variable in program space, in a compiler-managed section
designated for automatic program space visibility window access. Variables in
auto_psv space can be read (but not written) using ordinary C statements, and
are subject to a maximum of 32K total space allocated. When specifying
space(auto_psv), it is not possible to assign a section name using the section attribute; any section name will be ignored with a warning. A variable in the
auto_psv space cannot be placed at a specific address or given a reverse
alignment.
Note:Variables placed in the auto_psv section are not loaded into data
memory at startup. This attribute may be useful for reducing RAM
usage.
dma - PIC24H MCUs, dsPIC33F DSCs only
Allocate the variable in DMA memory. Variables in DMA memory can be
accessed using ordinary C statements and by the DMA peripheral.
__builtin_dmaoffset() (see Appendix B. “Built-in Functions”) can be
used to find the correct offset for configuring the DMA peripheral.
#include <p24Hxxxx.h>
unsigned int BufferA[8]
unsigned int BufferB[8]
int main()
{
DMA1STA =
DMA1STB =
/* ... */
}
psv
Allocate the variable in program space, in a section designated for program sp ace
visibility window access. The linker will locate the section so that the entire variable can be accessed using a single setting of the PSVPAG register. Variables in
PSV space are not managed by the compiler and can not be accessed using ordinary C statements. They must be explicitly accessed by the programmer , usually
using table-access inline assembly instructions, or using the program space
visibility window.
eedata - PIC24F, dsPIC30F/33F DSCs only
Allocate the variable in EEData space. Variables in EEData space can not be
accessed using ordinary C statements. They must be explicitly accessed by the
programmer, usually using table-access inline assembly instructions, or using
the program space visibility window.
pmp
Allocate the variable in off chip memory associated with the PMP peripheral. For
complete details please see Section 6.3 “PMP Pointers”.
DS51284K-page 24 2002-2011 Microchip Technology Inc.
Differences Between 16-Bit Device C and ANSI C
external
Allocate the variable in a user defined memory space. For complete details
please see Section 6.4 “External Pointers”.
transparent_union
This attribute, attached to a function parameter which is a union, means that the
corresponding argument may have the type of any union member, but the argument is
passed as if its type were that of the first union member. The argument is passed to the
function using the calling conventions of the first member of the transparent union, not
the calling conventions of the union itself. All members of the union must have the same
machine representation; this is necessary for this argument passing to work properly.
unordered
The unordered attribute indicates that the placement of this variable may move
relative to other variables within the current C source file.
const int __attribute__ ((unordered)) i;
unused
This attribute, attached to a variable, means that the variable is meant to be possibly
unused. The compiler will not produce an unused variable warning for this variable.
weak
The weak attribute causes the declaration to be emitted as a weak symbol. A weak
symbol may be superseded by a global definition. When weak is applied to a reference
to an external symbol, the symbol is not required for linking. For example:
extern int __attribute__((__weak__)) s;
int foo() {
if (&s) return s;
return 0; /* possibly some other value */
}
In the above program, if s is not defined by some other module, the program will still
link but s will not be given an address. The conditional verifies that s has been defined
(and returns its value if it has). Otherwise ‘0’ is returned. There are many uses for this
feature, mostly to provide generic code that can link with an optional library.
The weak attribute may be applied to functions as well as variables:
extern int __attribute__((__weak__)) compress_data(void *buf);
int process(void *buf) {
if (compress_data) {
if (compress_data(buf) == -1) /* error */
}
/* process buf */
}
In the above code, the function compress_data will be used only if it is linked in from
some other module. Deciding whether or not to use the feature becomes a link-time
decision, not a compile time decisio n.
The affect of the weak attribute on a definition is more complicated and requires
multiple files to describe:
/* weak1.c */
int
void foo() {
i = 1;
}
/* weak2.c */
int i;
extern void foo(void);
void bar() {
i = 2;
}
main() {
foo();
bar();
}
Here the definition in weak2.c of i causes the symbol to become a strong definition.
No link error is emitted and both i’s refer to the same storage location. Storage is
allocated for weak1.c’s version of i, but this space is not accessible.
There is no check to ensure that both versions of i have the same type; changing i in
weak2.c to be of type float will still allow a link, but the behavior of function foo will
be unexpected. foo will write a value into the least significant portion of our 32-bit float
value. Conversely, changing the type of the weak definition of i in weak1.c to type
float may cause disastrous results. We will be writing a 32-bit floating point value into
a 16-bit integer allocation, overwriting any variable stored immediately after our i.
In the cases wh ere only weak definitions exist, the linker will choose the storage of the
first such definition. The remaining definitions become in-accessible.
The behavior is identical, regardless of the type of the symbol; functions and variables
behave in the same manner.
__attribute__((__weak__)) i;
DS51284K-page 26 2002-2011 Microchip Technology Inc.
Differences Between 16-Bit Device C and ANSI C
2.3.2Specifying Attributes of Functions
In the compiler, you declare certain things about functions called in your program which
help the compiler optimize function calls and check your code more carefully.
The keyword __attribute__ allows you to specify special attributes when making a
declaration. This keyword is followed by an attribute specification inside double
parentheses. The following attributes are currently supported for functions:
• address (addr)
• alias ("target")
• auto_psv, no_auto_psv
• boot
• const
• deprecated
• far
• format (archetype, string-index, first-to-check)
You may also specify attributes with __ (double underscore) preceding and following
each keyword (e.g., __shadow__ instead of shadow). This allows you to use them in
header files without being concerned about a possible macro of the same name.
You can specify multiple attributes in a declaration by separating them by commas
within the double parentheses or by immediately following an attribute declaration with
another attribute declaration.
address (addr)
The address attribute specifies an absolute address for the function. This attribute
cannot be used in conjunction with a section attribute; the address attribute will take
precedence.
The auto_psv attribute, when combined with the interrupt attribute, will cause the
compiler to generate additional code in the function prologue to set the PSVPAG SFR
to the correct value for accessing space(auto_psv) (or constants in the constants-in-code memory model) variables. Use this option when using 24-bit pointers
and an interrupt may occur while the PSVP AG has been modified and the interrupt routine, or a function it calls, uses an auto_psv variable. Compare this with
no_auto_psv. If neither auto_psv nor no_auto_psv option is specified for an
interrupt routine, the compiler will issue a warning and select this option.
The no_auto_psv attribute, when combined with the interrupt attribute, will cause the
compiler to not generate additional code for accessing space(auto_psv) (or constants in the constants-in-code memory model) variables. Use this option if none of the
conditions under auto_psv hold true. If neither auto_psv nor no_auto_psv option
is specified for an interrupt routine, the compiler will issue a warning and assume
auto_psv.
boot
This attribute directs the compiler to allocate a function in the boot segment of program
Flash.
For example, to declare a protected function:
void __attribute__((boot)) func();
An optional argument can be used to specify a protected access entry point within the
boot segment. The argument may be a literal integer in the range 0 to 31 (except 16),
or the word unused. Integer arguments correspond to 32 instruction slots in the segment access area, which occupies the lowest address range of each secure segment.
The value 16 is excluded because access entry 16 is reserved for the secure segment
interrupt vector. The value unused is used to specify a function for all of the unused
slots in the access area.
Access entry points facilitate the creation of application segments from different vendors that are combined at run time. They can be specified for external functions as well
as locally defined functions. For example:
/* an external function that we wish to call */
extern void __attribute__((boot(3))) boot_service3();
/* local function callable from other segments */
void __attribute__((secure(4))) secure_service4()
{
boot_service3();
}
Note:In order to allocate functions with the boot or secure attribute, memory
for the boot and/or secure segment must be reserved. This can be accomplished by setting configuration words in source code, or by specifying
linker command options. For more information, see Chapter 8.8, “Options
that Specify CodeGuard Security Features”, in the linker manual
(DS51317).
If attributes boot or secure are used, and memory is not reserved, then a
link error will result.
To specify a secure interrupt handler, use the boot attribute in combination with the
interrupt attribute:
DS51284K-page 28 2002-2011 Microchip Technology Inc.
Differences Between 16-Bit Device C and ANSI C
When an access entry point is specified for an external secure function, that function
need not be included in the project for a successful link. All references to that function
will be resolved to a fixed location in Flash, depending on the security model selected
at link time.
When an access entry point is specified for a locally defined function, the linker will
insert a branch instruction into the secure segment access area. The exception is for
access entry 16, which is represented as a vector (i.e, an instruction address) rather
than an instruction. The actual function definition will be located beyond the access
area; therefore the access area will contain a jump table through which control can be
transferred from another security segment to functions with defined entry points.
Automatic variables are owned by the enclosing function and do not need the boot
attribute. They may be assigned initial values, as shown:
void __attribute__((boot)) chuck_cookies()
{
int hurl;
int them = 55;
char *where = "far";
splat(where);
/* ... */
}
Note that the initial value of where is based on a string literal which is allocated in the
PSV constant section .boot_const. The compiler will set PSVPAG to the correct
value upon entrance to the function. If necessary, the compiler will also restore
PSVPAG after the call to splat().
const
Many functions do not examine any values except their arguments, and have no effects
except the return value. Such a function can be subject to common subexpression
elimination and loop optimization just as an arithmetic operator would be. These
functions should be declared with the attribute const. For example:
int square (int) __attribute__ ((const int));
says that the hypothetical function square is safe to call fewer times than the program
says.
Note that a function that has pointer arguments and examines the data pointed to must
not be declared const. Likewise, a function that calls a non-const function usually
must not be const. It does not make sense for a const function to have a void return
type.
deprecated
See Section 2.3.1 “Specifying Attributes of Variables” for information on the
deprecated attribute.
far
The far attribute tells the compiler that the function should not be called using a more
efficient form of the call instruction.
format (archetype, string-index, first-to-check)
The format attribute specifies that a function takes printf, scanf or strftime
style arguments which should be type-checked against a format string. For example,
consider the declaration:
extern int
my_printf (void *my_object, const char *my_format, ...)
This causes the compiler to check the arguments in calls to my_printf for
consistency with the printf style format string argument my_format.
The parameter archetype determines how the format string is interpreted, and should
be one of printf, scanf or strftime. The parameter string-index specifies
which argument is the format string argument (arguments are numbered from the left,
starting from 1), while first-to-check is the number of the first argument to check
against the format string. For functions where the arguments are not available to be
checked (such as vprintf), specify the third parameter as zero. In this case, the
compiler only checks the format string for consistency.
In the example above, the format string (my_format) is the second argument of the
function my_print, and the arguments to check start with the third argument, so the
correct parameters for the format attribute are 2 and 3.
The format attribute allows you to identify your own functions that take format strings
as arguments, so that the compiler can check the calls to these functions for errors. The
compiler always checks formats for the ANSI library functions printf, fprintf,
sprintf, scanf, fscanf, sscanf, strftime, vprintf, vfprintf and
vsprintf, whenever such warnings are requested (using -Wformat), so there is no
need to modify the header file stdio.h.
format_arg (string-index)
The format_arg attribute specifies that a function takes printf or scanf style
arguments, modifies it (for example, to translate it into another language), and passes
it to a printf or scanf style function. For example, consider the declaration:
This causes the compiler to check the arguments in calls to my_dgettext, whose
result is passed to a printf, scanf or strftime type function for consistency with
the printf style format string argument my_format.
The parameter string-index specifies which argument is the format string
argument (starting from 1).
The format-arg attribute allows you to identify your own functions which modify
format strings, so that the compiler can check the calls to printf, scanf or
strftime function, whose operands are a call to one of your own functions.
Use this option to indicate that the specified function is an interrupt handler. The compiler
will generate function prologue and epilogue sequences suitable f or u se in an interrupt handl er wh en t his at tr ibute is pr esen t. Th e op tion al p arame ter save specifies a list
of variables to be saved and restored in the function prologue and epilogue, respectively.
The optional parameters irq and altirq spec ify interrupt ve ctor table ID’s to be used.
The optiona l p a ram et e r preprologue specif ie s asse mbly co de th at is to be emi tte d
before the comp il er -g en era t ed p rol og ue cod e. See Chapter 8. “Interrupts” for a full
description, including examples.
When using the interrupt attribute, please specify either auto_psv or
no_auto_psv. If none is specified a warning will be produced and auto_psv will be
assumed.
near
The near attribute tells the compiler that the function can be called using a more
efficient form of the call instruction.
DS51284K-page 30 2002-2011 Microchip Technology Inc.
Loading...
+ 234 hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.