Microchip Technology MPLAB® C Compiler User’s Guide

MPLAB® C Compiler
for PIC24 MCUs
and dsPIC® DSCs
User’s Guide
2002-2011 Microchip Technology Inc. DS51284K
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
EELOQ, KEELOQ logo, MPLAB, PIC, PICmicro, PICSTART,
32
PIC
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.
© 2002-2011, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.
Printed on recycled paper.
ISBN: 978-1-61341-294-7
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
MPLAB® C COMPILER FOR
®
PIC24 MCUs AND dsPIC
DSCs
USER’S GUIDE

Table of Contents

Preface ...........................................................................................................................7
Chapter 1. Compiler Overview
1.1 Introduction ...................................................................................................13
1.2 Highlight s ......... .. ........................................................................................... 13
1.3 Compiler Des c ription and Do cu mentation .............. .. ........................... .. ....... 1 3
1.4 Compiler and Other Development Tools ......................................................14
1.5 Compiler Feature Set ...................................................................................16
Chapter 2. Differences Between 16-Bit Device C and ANSI C
2.1 Introduction ...................................................................................................17
2.2 Highlight s ......... .. ........................................................................................... 17
2.3 Keyword Di ffe r e n ce s ........ ............................. ............................................... 17
2.4 Statement Difference s .................................................................................. 37
2.5 Expressi on D if fe rences .. ............. ... .. ............. .. .. ........................... .. .. ............ 38
Chapter 3. Using the Compiler on the Command Line
3.1 Introduction ...................................................................................................39
3.2 Highlight s ......... .. ........................................................................................... 39
3.3 Overview ............. ......................................................................................... 39
3.4 File Naming Conventions ............................................................................. 40
3.5 Options ....... .................................................................................................. 40
3.6 Environme n t V a ri a bl e s ........................................................................ .. .. ..... 6 4
3.7 Predefined Macro Names .............................................................................65
3.8 Compiling a Single File on the Command Line ............................................ 66
3.9 Compiling Multiple Files on the Command Line ...........................................67
3.10 Notab le Sym b o l s ....................................................................................... . 67
Chapter 4. Run Time Environment
4.1 Introduction ...................................................................................................69
4.2 Highlight s ......... .. ........................................................................................... 69
4.3 Address Sp a ce s ......... .................................................................................. 69
4.4 Startup and Initialization .......................... .......................................... ...........70
4.5 Memory Sp ac e s ............. ..................................................... .. ... .................... 71
4.6 Memory Models ............................................................................................72
4.7 Locating Code and Data ....................................................................... .. ......74
4.8 Software St a ck ......... ......................................... ........................................... 75
4.9 The C Stack U s a ge .......... ............................................................................ 76
4.10 The C Heap Usage .....................................................................................78
4.11 Function Call Conventions ......................................................................... 79
4.12 Regist e r C o n ven tions ................................................................................. 81
2003-2011 Microchip Technology Inc. Update Draft DS51284J3-page 3
16-Bit C Compiler User’s Guide
4.13 Bit Reversed and Modulo Addressing ........................................................82
4.14 Program Space Visibility (PSV) Usage ......................................................82
4.15 Using L a rg e A rra y s .... ................................................................................. 84
Chapter 5. Data Types
5.1 Introduction ................................................................................................... 85
5.2 Highlight s . ... .................................................................................................. 85
5.3 Data Repre se ntation .................................................................................... 85
5.4 Integer ..........................................................................................................85
5.5 Floating P o in t ... .. .......................................... ................................................ 86
5.6 Pointers ........................................................ ................................................ 86
Chapter 6. Additional C Pointer Types
6.1 Introduction ................................................................................................... 87
6.2 Managed PSV Pointers ................................................................................87
6.3 PMP Pointe rs ... .. .......................................................................................... 89
6.4 External Po in te r s ..... ..................................................................................... 91
6.5 Extended Data Space Pointers ....................................................................95
Chapter 7. Device Support Files
7.1 Introduction ................................................................................................... 97
7.2 Highlight s . ... .................................................................................................. 97
7.3 Processor Header Files ................................................................................97
7.4 Register D e fi n ition Files ..... .. ........................... .. .. ......................................... 9 8
7.5 Using SFRs .. .. .. ............................................................................................ 9 9
7.6 Using Macro s ... .. ........................................................................................ 101
7.7 Accessing EEDATA from C Code – PIC24F MCUS, dsPIC30F/33F DSCs only 102
Chapter 8. Interrupts
8.1 Introduction .................................................................................................105
8.2 Highlight s . ... ................................................................................................ 105
8.3 Writing an Interrupt Service Routine .......................................................... 106
8.4 Writing the In te r ru p t V e c to r .... ................ .......................................... .......... 10 8
8.5 Interrupt S e rv ic e R o u tin e Co ntext Saving ........................................ .. .. ...... 118
8.6 Latency .... ... ............. .. .. ................................................................... .. .. ........ 118
8.7 Nesting In te r ru p ts ............. .. ............................. ........................................... 118
8.8 Enabling/D isabling Interrupts ............................................................... ...... 119
8.9 Sharing Memory Between Interrupt Service Routines and Mainline Code 120
8.10 PSV Usage with Interrupt Service Routines ............................. ................123
Chapter 9. Mixing Assembly Language and C Modules
9.1 Introduction .................................................................................................125
9.2 Highlight s . ... ................................................................................................ 125
9.3 Mixing Assembly Language and C Variables and Functions ................ .. ... 125
9.4 Using Inline Assembly Language ............................................................... 127
Appendix A. Implementation-Defined Behavior
A.1 Introduction ................................................................................................135
DS51284J3-page 4 Update Draft 2003-2011 Microchip Technology Inc.
Table of Contents
A.2 Highlight s .......... .. ....................................................................................... 135
A.3 Translati o n .......... .. ..................................................................................... 13 6
A.4 Environme n t ........................................................................................ .. .. ... 136
A.5 Identifiers ...................................................................................................137
A.6 Character s ............ ..................................................................................... 1 3 7
A.7 Integers ......................................................................................................138
A.8 Floating Po in t ...... .. .................................................................................. ... 138
A.9 Arrays and P o in te r s ............ ....................................................................... 139
A.10 Registers .................. ............... ................................................................. 139
A.11 Structures, Unions, Enumerations and Bit fields ......................................140
A.12 Qualifiers .................. .................................................................... ............ 140
A.13 Declara to r s .......... .............. .. .. ..................................................... .. .. .......... 140
A.14 Stateme nt s ................... .. .......................................................................... 140
A.15 Preproce s s in g Di re c tives .... .....................................................................141
A.16 Library F u n ct io n s .............................................................................. .. .. ... 142
A.17 Signals .....................................................................................................143
A.18 Streams and Files ....................................................................................143
A.19 tmpfile ............. .. .. ..................................................................................... 1 4 4
A.20 errno ......................................................................................................... 144
A.21 Memory ...... ... .. ......................................................................................... 144
A.22 abort .................... ... ..................................................................................144
A.23 exit ................ .. ............................................................................... ... .. ..... 1 4 4
A.24 getenv ........ ... ........................................................................................... 145
A.25 system ........... .. ......................................................................................... 145
A.26 strerror .......... ............. .. .. ................................................................... .. .. ... 145
Appendix B. Built-in Functions
B.1 Introduction ................................................................................................147
B.2 Built-In Fun ction List .. ............................ .................................................... 148
Appendix C. MPLAB C Compiler for PIC18 MCUs vs. 16-Bit Devices
C.1 Introduction ................................................................................................173
C.2 Highlight s ........ ............................................................................... .. ... ....... 173
C.3 Data Forma ts ...... ....................................................................................... 174
C.4 Pointers ........... .. .................................................................................. ....... 174
C.5 Storage Cla s s e s ........................................................................................ 174
C.6 Stack Usage ..............................................................................................174
C.7 Storage Qu a lif ie r s ...... .. .......................................... .................................... 175
C.8 Predefined Macro Names ..........................................................................175
C.9 Integer Pr om o tions .... .. .............................................................................. 175
C.10 String Con s ta n t s ........................................................................ .. .. .......... 175
C.11 Access Memory .. ... .................................................................................. 175
C.12 Inline Ass embly ... ................ ..................................................................... 175
C.13 Pragmas ............. ... .................................................................................. 176
C.14 Memory Models .......................................................................................177
C.15 Calling Co n v en t io n s ................ ............. ... .. ............................................... 1 7 7
2003-2011 Microchip Technology Inc. Update Draft DS51284J3-page 5
16-Bit C Compiler User’s Guide
C.16 Startup Code ............................................................................................177
C.17 Compiler-Managed Resources ................................................................177
C.18 Optimiz ations ................... .. ...................................................................... 178
C.19 Object Module Format ............................................................................. 178
C.20 Implementation-Defined Behavior ...........................................................178
C.21 Bit fields ... .. .. ............................................................................................ 1 7 9
Appendix D. Diagnostics
D.1 Introduction ................................................................................................ 181
D.2 Errors ............... .. .................................................................................. ...... 181
D.3 Warnings . ... .. .......................................... .......................................... .......... 20 0
Appendix E. Deprecated Features
E.1 Introduction ................................................................................................221
E.2 Highlight s ... .. .. ............................................................................................ 2 2 1
E.3 Predefined Constants ................................................................................221
E.4 Variable s in Sp ecified Regist e rs ................................................................ 22 2
Appendix F. ASCII Character Set .............................................................................225
Appendix G. GNU Free Documentation License
G.1 PREAMBLE ............ .. .. ............................................................................... 2 2 7
G.2 APPLICABILITY AND DEFINITIONS ........................................................ 227
G.3 VERBATI M COPYING ..... .. .......................................... .............................. 229
G.4 COPYING IN Q U AN T IT Y ............. ....................................................... ...... 229
G.5 MODIFICA TIONS ................ .. ............................. ....................................... 23 0
G.6 COMBINI N G DOCUMENTS .. ... ................................................................. 2 3 1
G.7 COLLECTIONS OF DOCUMENTS ........................................................... 231
G.8 AGGREGATION WITH INDEPENDENT WORKS .................................... 232
G.9 TRANSLAT ION .................................................... ..................................... 23 2
G.10 TERMIN A T ION ... ..................................................................................... 232
G.11 FUTURE REVISIONS OF THIS LICENSE .............................................. 233
G.12 RELICENSING ....... .. ... ............................................................................ 233
Glossary .....................................................................................................................235
Index ...........................................................................................................................255
Worldwide Sales and Service ...................................................................................265
DS51284J3-page 6 Update 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
• Customer Support
®
DSCs. Items discussed include:
2002-2011 Microchip Technology Inc. DS51284K-page 7
16-Bit C Compiler User’s Guide
DOCUMENT LAYOUT
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.
CONVENTIONS USED IN THIS GUIDE
STD
DD
The following conventions may appear in this documentation:
DOCUMENTATION CONVENTIONS
Description Represents Examples
Arial font:
Italic chara c ters Referenced books MPLAB
Initial caps A window the Output window
Quotes A field name in a window or
Underlined, italic text with right angle bracket
Bold characters A dialog button Click OK
Text in angle brackets < > A key on the keyboard Press <Enter>, <F1>
Courier font:
Plain Courier Sample source code #define START
Italic Courier A variable argument file.o, where file can be
Square brackets [ ] Optional arguments mpasmwin [options]
Curly brackets and pipe character: { | }
Ellipses... Replaces r epeated text var_name [,
Sidebar T e xt
Preface
®
IDE User’s Guide
Emphasized text ...is the only compiler...
A dialog the Settings dialog A menu selection select Enable Programmer
“Save project before build”
dialog A menu path File>Save
A tab Click the Power tab
Filenames autoexec.bat File paths c:\mcc18\h Keywords _asm, _endasm, static Command-line options -Opa+, -Opa- Bit values 0, 1 Constants 0xFF, ’A’
any valid filename
file [options]
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 sup­ported will be listed in the title or text.
errorlevel {0|1}
var_name...] void main (void)
{ ... }
-mpa option
xmemory attribute
2002-2011 Microchip Technology Inc. DS51284K-page 9
16-Bit C Compiler User’s Guide
RECOMMENDED READING
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.
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
Edition. Prentice Hall, Englewood Cliffs, N.J. 07632.
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
Preface
2002-2011 Microchip Technology Inc. DS51284K-page 11
16-Bit C Compiler User’s Guide
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

Chapter 1. Compiler Overview

1.1 INTRODUCTION

The dsPIC® family of Digital Signal Controllers (dsPIC30F and dsPIC33F DSCs) com­bines 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 micro­controllers 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.2 HIGHLIGHTS

Items discussed in this chapter are:
• Compiler Description and Documentation
• Compiler and Other Development Tools
• Compiler Feature Set

1.3 COMPILER 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 for Device Support Edition Support
1 PIC24 MCUs and dsPIC 2 dsPIC DSCs dsPIC30F/33F DSCs Std, Std Eval, Lite 3 PIC24 MCUs PIC24F/H MCUs Std, Std Eval, Lite
Each compiler is an ANSI x3.159-1989-compliant, optimizing C compiler. Each com­piler 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.
®
DSCs All 16-bit devices Std, Std Eval
2002-2011 Microchip Technology Inc. DS51284K-page 13
16-Bit C Compiler User’s Guide
1.3.1 Compiler Editions
Each of the three compilers in Section 1.3 “Compiler Description and Documenta­tion” 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.2 Compiler 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.4 COMPILER 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.
Compiler Overview
Object File Libraries
(*.a)
Assembler
Linker
C Source Files
(*.c)
C Compiler
Source Files (*.s)
Assembly Source
Files (*.s)
COFF/ELF Object Files
(*.o)
Executable File
(*.exe)
Archiver (Librarian)
Command-Line
Simulator
Compiler Driver Program
MPLAB
®
IDE
Debug Tool
FIGURE 1-1: SOFTWARE DEVELOPMENT TOOLS DATA FLOW
2002-2011 Microchip Technology Inc. DS51284K-page 15
16-Bit C Compiler User’s Guide

1.5 COMPILER FEATURE SET

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 gen­erator. This section describes key features of the compiler.
1.5.1 ANSI 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.2 Optimization
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.3 ANSI 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, time­keeping 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.4 Flexible 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.5 Compiler 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.1 INTRODUCTION

This section discusses the differences between the C language supported by MPLAB C Compiler for PIC24 MCUs and dsPIC 1989 standard ANSI C.

2.2 HIGHLIGHTS

Items discussed in this chapter are:
• Keyword Differences
• Statement Differences
• Expression Differences

2.3 KEYWORD 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 cu­mentation, tailored for the specific syntax and semantics of the 16-bit compiler por t of GCC.
• Specifying Attributes of Variables
• Specifying Attributes of Functions
• Inline Functions
• Variables in Specified Registers
• Complex Numbers
• Double-Word Integers
• Referring to a Type with typeof
®
DSCs (formerly MPLAB C30) syntax and the
2002-2011 Microchip Technology Inc. DS51284K-page 17
16-Bit C Compiler User’s Guide
2.3.1 Specifying Attributes of Variables
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.
__attribute__((section("mysection"))); __attribute__((section("mysection")));
Differences Between 16-Bit Device C and ANSI C
int var __attribute__ ((address(0x800)));
aligned (alignment)
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 */ }
2002-2011 Microchip Technology Inc. DS51284K-page 19
16-Bit C Compiler User’s Guide
deprecated
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 com­piler 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:
Mode Width Compiler Type
QI 8 bits char HI 16 bits int SI 32 bits long
DI 64 bits long long SF 32 bits float DF 64 bits long 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 tar­gets. 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 correspond­ing 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 con­strained 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.
2002-2011 Microchip Technology Inc. DS51284K-page 21
16-Bit C Compiler User’s Guide
persistent
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:
char *msg __attribute__((secure)) = "Hello!\n"; /* not supported */ char *msg2 __attribute__((secure)); void __attribute__((secure)) foo2() { *msg2 = "Goodbye..\n"; /* value assigned explicitly */ }
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 attri­bute 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:
int y[32] __attribute__ ((space(ymemory)));
2002-2011 Microchip Technology Inc. DS51284K-page 23
16-Bit C Compiler User’s Guide
DD
DD
prog
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 sec­tion 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 vari­able 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 ordi­nary 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”.
__builtin_dmaoffset(BufferA); __builtin_dmaoffset(BufferB);
__attribute__((space(dma))); __attribute__((space(dma)));
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.
2002-2011 Microchip Technology Inc. DS51284K-page 25
16-Bit C Compiler User’s Guide
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.2 Specifying 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)
format_arg (string-index)
• interrupt [ ( [ save(list) ] [, irq(irqid) ] [, altirq(altirqid)] [, preprologue(asm) ] ) ]
near
no_instrument_function
noload
noreturn
section ("section-name")
secure
shadow
unused
user_init
weak
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.
void __attribute__ ((address(0x100))) foo() { ... }
Alternatively, you may define the address in the function prototype:
void foo() __attribute__ ((address(0x100)));
alias ("target")
The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified.
Use of this attribute results in an external reference to target, which must be resolved during the link phase.
2002-2011 Microchip Technology Inc. DS51284K-page 27
16-Bit C Compiler User’s Guide
auto_psv, no_auto_psv
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 con­stants-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 rou­tine, 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 con­stants 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 seg­ment 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 ven­dors 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 accom­plished 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:
void __attribute__((boot,interrupt)) boot_interrupts();
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, ...)
__attribute__ ((format (printf, 2, 3)));
2002-2011 Microchip Technology Inc. DS51284K-page 29
16-Bit C Compiler User’s Guide
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:
extern char * my_dgettext (char *my_domain, const char *my_format) __attribute__ ((format_arg (2)));
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.
interrupt [ ( [ save(list) ] [, irq(irqid) ] [, altirq(altirqid)] [, preprologue(asm) ] ) ]
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 inter­rupt 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