MPLAB® XC32 C/C++ Compiler
User’s Guide
2012 Microchip Technology Inc.
DS51686E
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 the like is provided only for your convenience
and may be superseded by updates. It is your 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 support and/or safety applications is entirely at
the buyer’s risk, and the buyer agrees to defend, indemnify and
hold harmless Microchip from any and all damages, claims,
suits, or expenses resulting from such use. No licenses are
conveyed, implicitly or otherwise, under any Microchip
intellectual property rights.
Trademarks
The Microchip name and logo, the Microchip logo, dsPIC,
KEELOQ, KEELOQ logo, MPLAB, PIC, PICmicro, PICSTART,
PIC32 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.
© 2012, Microchip Technology Incorporated, Printed in the
U.S.A., All Rights Reserved.
Printed on recycled paper.
ISBN: 978-1-62076-455-8
Microchip received ISO/TS-16949:2009 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® MCUs and dsPIC® DSCs, KEELOQ® code hopping
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.
DS51686E-page 2
2012 Microchip Technology Inc.
MPLAB® XC32 C/C++ COMPILER
USER’S GUIDE
Table of Contents
Preface ........................................................................................................................... 7
Chapter 1. Compiler Overview
1.1 Introduction ................................................................................................... 13
1.2 Device Description ....................................................................................... 13
1.3 Compiler Description and Documentation .................................................... 13
1.4 Compiler and Other Development Tools ...................................................... 15
Chapter 2. Common C Interface
2.1 Introduction ................................................................................................... 17
2.2 Background – The Desire for Portable Code ............................................... 17
2.3 Using the CCI ............................................................................................... 20
2.4 ANSI Standard Refinement .......................................................................... 21
2.5 ANSI Standard Extensions ........................................................................... 29
2.6 Compiler Features ........................................................................................ 43
Chapter 3. Compiler Command Line Driver
3.1 Introduction ................................................................................................... 45
3.2 Invoking the Compiler ................................................................................... 45
3.3 The C Compilation Sequence ...................................................................... 49
3.4 The C++ Compilation Sequence .................................................................. 51
3.5 Runtime Files ............................................................................................... 55
3.6 Start-up and Initialization .............................................................................. 58
3.7 Compiler Output ........................................................................................... 58
3.8 Compiler Messages ...................................................................................... 60
3.9 Driver Option Descriptions ........................................................................... 60
Chapter 4. Device-Related Features
4.1 Introduction ................................................................................................... 85
4.2 Device Support ............................................................................................. 85
4.3 Device Header Files ..................................................................................... 85
4.4 Stack ............................................................................................................ 86
4.5 Using SFRs From C Code ............................................................................ 88
Chapter 5. ANSI C Standard Issues
5.1 Divergence from the ANSI C Standard ........................................................ 91
5.2 Extensions to the ANSI C Standard ............................................................. 91
5.3 Implementation-defined behavior ................................................................. 92
Chapter 6. Supported Data Types and Variables
6.1 Introduction ................................................................................................... 93
6.2 Identifiers ...................................................................................................... 93
2012 Microchip Technology Inc.
DS51686E-page 3
MPLAB® XC32 C/C++ Compiler User’s Guide
6.3 Data Representation .................................................................................... 93
6.4 Integer Data Types ....................................................................................... 94
6.5 Floating-Point Data Types ............................................................................ 96
6.6 Structures and Unions .................................................................................. 98
6.7 Pointer Types ............................................................................................. 100
6.8 Complex Data Types .................................................................................. 102
6.9 Constant Types and Formats ..................................................................... 102
6.10 Standard Type Qualifiers .......................................................................... 104
6.11 Compiler-Specific Qualifiers ..................................................................... 105
6.12 Variable Attributes .................................................................................... 105
Chapter 7. Memory Allocation and Access
7.1 Introduction ................................................................................................. 109
7.2 Address Spaces ......................................................................................... 109
7.3 Variables in Data Memory .......................................................................... 110
7.4 Auto Variable Allocation and Access .......................................................... 112
7.5 Variables in Program Memory .................................................................... 113
7.6 Variables in Registers ................................................................................ 114
7.7 Dynamic Memory Allocation ....................................................................... 114
7.8 Memory Models .......................................................................................... 114
Chapter 8. Operators and Statements
8.1 Introduction ................................................................................................. 117
8.2 Integral Promotion ...................................................................................... 117
8.3 Type References ........................................................................................ 118
8.4 Labels as Values ........................................................................................ 119
8.5 Conditional Operator Operands ................................................................. 120
8.6 Case Ranges .............................................................................................. 120
Chapter 9. Register Usage
9.1 Introduction ................................................................................................. 121
9.2 Register Usage ........................................................................................... 121
9.3 Register Conventions ................................................................................. 121
Chapter 10. Functions
10.1 Writing Functions ...................................................................................... 123
10.2 Function Attributes and Specifiers ............................................................ 123
10.3 Allocation of Function Code ..................................................................... 127
10.4 Changing the Default Function Allocation ................................................ 127
10.5 Function Size Limits ................................................................................. 128
10.6 Function Parameters ................................................................................ 128
10.7 Function Return Values ............................................................................ 130
10.8 Calling Functions ...................................................................................... 130
10.9 Inline Functions ........................................................................................ 130
Chapter 11. Interrupts
11.1 Introduction ............................................................................................... 133
11.2 Interrupt Operation ................................................................................... 133
DS51686E-page 4
2012 Microchip Technology Inc.
11.3 Writing an Interrupt Service Routine ........................................................ 134
11.4 Associating a Handler Function with an Exception Vector ....................... 139
11.5 Exception Handlers .................................................................................. 141
11.6 Interrupt Service Routine Context Switching ............................................ 141
11.7 Latency ..................................................................................................... 142
11.8 Nesting Interrupts ..................................................................................... 142
11.9 Enabling/Disabling Interrupts ................................................................... 142
11.10 ISR Considerations ................................................................................ 142
Chapter 12. Main, Runtime Start-up and Reset
12.1 Introduction ............................................................................................... 143
12.2 The Main Function .................................................................................... 143
12.3 Runtime Start-up Code ............................................................................. 143
12.4 The On Reset Routine .............................................................................. 157
Chapter 13. Library Routines
13.1 Using Library Routines ............................................................................. 159
Chapter 14. Mixing C/C++ and Assembly Language
14.1 Introduction ............................................................................................... 161
14.2 Using Inline Assembly Language ............................................................. 161
14.3 Predefined Assembly Macros ................................................................... 164
Chapter 15. Optimizations
15.1 Introduction ............................................................................................... 167
Chapter 16. Preprocessing
16.1 Introduction ............................................................................................... 169
16.2 C/C++ Language Comments .................................................................... 169
16.3 Preprocessor Directives ........................................................................... 169
16.4 Pragma Directives .................................................................................... 171
16.5 Predefined Macros ................................................................................... 172
Chapter 17. Linking Programs
17.1 Introduction ............................................................................................... 175
17.2 Replacing Library Symbols ....................................................................... 175
17.3 Linker-Defined Symbols ........................................................................... 175
17.4 Default Linker Script ................................................................................. 176
Appendix 18. Implementation-Defined Behavior
18.1 Introduction ............................................................................................... 191
18.2 Highlights .................................................................................................. 191
18.3 Overview .................................................................................................. 191
18.4 Translation ................................................................................................ 192
18.5 Environment ............................................................................................. 192
18.6 Identifiers .................................................................................................. 193
18.7 Characters ................................................................................................ 193
18.8 Integers .................................................................................................... 194
18.9 Floating-Point ........................................................................................... 194
18.10 Arrays and Pointers ................................................................................ 196
2012 Microchip Technology Inc.
DS51686E-page 5
MPLAB® XC32 C/C++ Compiler User’s Guide
18.11 Hints ....................................................................................................... 196
18.12 Structures, Unions, Enumerations, and Bit fields ................................... 197
18.13 Qualifiers ................................................................................................ 197
18.14 Declarators ............................................................................................. 198
18.15 Statements ............................................................................................. 198
18.16 Pre-Processing Directives ...................................................................... 198
18.17 Library Functions .................................................................................... 199
18.18 Architecture ............................................................................................ 202
Appendix 19. ASCII Character Set
Appendix 20. Deprecated Features
20.1 Introduction ............................................................................................... 205
20.2 Variables in Specified Registers ............................................................... 205
Glossary .....................................................................................................................207
Index ...........................................................................................................................225
Worldwide Sales and Service ...................................................................................238
DS51686E-page 6
2012 Microchip Technology Inc.
MPLAB® XC32 C/C++ COMPILER
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.
For the most up-to-date information on development tools, see the MPLAB® IDE or MPLAB X IDE
Help. Select the Help menu and then “Topics” or “Help Contents” to open a list of available Help files.
For the most current PDFs, please refer to our web site (http://www.microchip.com). Documents are
identified by “DSXXXXXA”, where “XXXXX” is the document number and “A” is the revision level of
the document. This number is located on the bottom of each page, in front of the page number.
MPLAB® XC32 C/C++ Compiler documentation and support information is discussed
in the sections below:
•
•
•
•
•
•
•
Document Layout
Conventions Used
Recommended Reading
myMicrochip Personalized Notification Service
The Microchip Web Site
Microchip Forums
Customer Support
2012 Microchip Technology Inc.
DS51686E-page 7
MPLAB® XC32 C/C++ Compiler User’s Guide
DOCUMENT LAYOUT
This document describes how to use GNU language tools to write code for 32-bit
applications. The document layout is as follows:
• Chapter 1. Compiler Overview – describes the compiler, development tools and
feature set.
• Chapter 2. Common C Interface – explains what you need to know about
making code portable.
• Chapter 3. Compiler Command Line Driver – describes how to use the
compiler from the command line.
• Chapter 4. Device-Related Features – describes the compiler header and
register definition files, as well as how to use with the SFRs.
• Chapter 5. ANSI C Standard Issues – describes the differences between the
C/C++ language supported by the compiler syntax and the standard ANSI-89 C.
• Chapter 6. Supported Data Types and Variables – describes the compiler
integer and pointer data types.
• Chapter 7. Memory Allocation and Access – describes the compiler run-time
model, including information on sections, initialization, memory models, the
software stack and much more.
• Chapter 8. Operators and Statements – discusses operators and statements.
• Chapter 9. Register Usage – explains how to access and use SFRs.
• Chapter 10. Functions – details available functions.
• Chapter 11. Interrupts – describes how to use interrupts.
• Chapter 12. Main, Runtime Start-up and Reset – describes important elements
of C/C++ code.
• Chapter 13. Library Routines – explains how to use libraries.
• Chapter 14. Mixing C/C++ and Assembly Language – provides guidelines for
using the compiler with 32-bit assembly language modules.
• Chapter 15. Optimizations – describes optimization options.
• Chapter 16. Preprocessing – details the preprocessing operation.
• Chapter 17. Linking Programs – explains how linking works.
• Appendix 18. Implementation-Defined Behavior – details compiler-specific
parameters described as implementation-defined in the ANSI standard.
• Appendix 19. ASCII Character Set” – contains the ASCII character set.
• Appendix 20. Deprecated Features – details features that are considered
obsolete.
DS51686E-page 8
2012 Microchip Technology Inc.
Preface
CONVENTIONS USED
The following conventions may appear in this documentation:
DOCUMENTATION CONVENTIONS
Description
Represents
Examples
Arial font:
Italic characters
Initial caps
Referenced books
MPLAB® IDE User’s Guide
Emphasized text
...is the only compiler...
A window
the Output window
A dialog
the Settings dialog
A menu selection
select Enable Programmer
Quotes
A field name in a window or dia- “Save project before build”
log
Underlined, italic text with
right angle bracket
A menu path
File>Save
Bold characters
A dialog button
Click OK
A tab
Click the Power tab
A key on the keyboard
Press ,
Sample source code
#define START
Filenames
autoexec.bat
File paths
c:\mcc18\h
Keywords
_asm, _endasm, static
Command-line options
-Opa+, -Opa-
Bit values
0, 1
Constants
0xFF, ’A’
A variable argument
file.o, where file can be
Text in angle brackets < >
Courier font:
Plain Courier
Italic Courier
any valid filename
Square brackets [ ]
Optional arguments
mpasmwin [options]
file [options]
Curly brackets and pipe
character: { | }
Choice of mutually exclusive
arguments; an OR selection
errorlevel {0|1}
Ellipses...
Replaces repeated text
var_name [,
var_name...]
Represents code supplied by
user
void main (void)
{ ...
}
Sidebar Text
DD
2012 Microchip Technology Inc.
xmemory attribute
Device Dependent.
This feature is not supported on
all devices. Devices supported
will be listed in the title or text.
DS51686E-page 9
MPLAB® XC32 C/C++ Compiler User’s Guide
RECOMMENDED READING
This documentation describes how to use the MPLAB XC32 C/C++ Compiler. Other
useful documents are listed below. The following Microchip documents are available
and recommended as supplemental reference resources.
Release Notes (Readme Files)
For the latest information on Microchip tools, read the associated Release Notes
(HTML files) included with the software.
MPLAB® Assembler, Linker and Utilities for PIC32 MCUs User’s Guide (DS51833)
A guide to using the 32-bit assembler, object linker, object archiver/librarian and various
utilities.
32-Bit Language Tools Libraries (DS51685)
Lists all library functions provided with the MPLAB XC32 C/C++ Compiler with detailed
descriptions of their use.
Dinkum Compleat Libraries
The Dinkum Compleat Libraries are organized into a number of headers, files that you
include in your program to declare or define library facilities. A link to the Dinkum libraries is available in the MPLAB X IDE application, on the My MPLAB X IDE tab, References & Featured Links section.
PIC32MX Configuration Settings
Lists the Configuration Bit settings for the Microchip PIC32MX devices supported by
the MPLAB XC32 C/C++ Compiler’s #pragma config.
Device-Specific Documentation
The Microchip website contains many documents that describe 32-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.
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 programs on a
variety of computing systems.
C++ Standards Information
Stroustrup, Bjarne, C++ Programming Language: Special Edition, 3rd Edition.
Addison-Wesley Professional; Indianapolis, Indiana, 46240.
ISO/IEC 14882 C++ Standard. The ISO C++ Standard is standardized by ISO (The
International Standards Organization) in collaboration with ANSI (The American
National Standards Institute), BSI (The British Standards Institute) and DIN (The
German national standards organization).
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 programs on a
variety of computing systems.
DS51686E-page 10
2012 Microchip Technology Inc.
Preface
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, Second
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.
GCC Documents
http://gcc.gnu.org/onlinedocs/
http://sourceware.org/binutils/
myMICROCHIP PERSONALIZED NOTIFICATION SERVICE
Microchip's personal notification service helps keep customers current on their Microchip products of interest. Subscribers will receive e-mail notification whenever there are
changes, updates, revisions or errata related to a specified product family or development tool.
Please visit http://www.microchip.com/pcn to begin the registration process and select
your preferences to receive personalized notifications. A FAQ and registration details
are available on the page, which can be opened by selecting the link above.
When you are selecting your preferences, choosing “Development Systems” will populate the list with available development tools. The main categories of tools are listed
below:
• Compilers – The latest information on Microchip C/C++ compilers, assemblers,
linkers and other language tools. These include all MPLAB C/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 IDE/MPLAB X IDE – The latest information on Microchip MPLAB IDE,
the Windows® Integrated Development Environment, or MPLAB X IDE, the open
source, cross-platform Integrated Development Environment. These lists focus on
the IDE, Project Manager, Editor and 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 development (nonproduction)
programmers MPLAB ICD 2 in-circuit debugger, PICSTART® Plus and PICkit 2
and 3.
• Starter/Demo Boards – These include MPLAB Starter Kit boards, PICDEM™
demo boards, and various other evaluation boards.
2012 Microchip Technology Inc.
DS51686E-page 11
MPLAB® XC32 C/C++ Compiler User’s Guide
THE MICROCHIP WEB SITE
Microchip provides online support via our web site at http://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
MICROCHIP FORUMS
Microchip provides additional online support via our web forums at
http://www.microchip.com/forums. Currently available forums are:
•
•
•
•
Development Tools
8-bit PIC® MCUs
16-bit PIC MCUs
32-bit PIC MCUs
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. See our web site
for a complete, up-to-date listing of sales offices.
Technical support is available through the web site at http://support.microchip.com.
Documentation errors or comments may be emailed to docerrors@microchip.com.
DOCUMENT REVISION HISTORY
Revision D (January 2012)
• Changed product name from MPLAB C32 C Compiler to MPLAB XC32 C/C++
Compiler. Completely reorganized document to align with other Microchip
compiler documentation.
Revision E (July 2012)
• Added information pertaining to C++ throughout the document.
• Added new section describing the Common Compiler Interface (CCI) Standard
DS51686E-page 12
2012 Microchip Technology Inc.
MPLAB® XC32 C/C++ COMPILER
USER’S GUIDE
Chapter 1. Compiler Overview
1.1
INTRODUCTION
The MPLAB XC32 C/C++ Compiler is defined and described in the following topics:
• Device Description
• Compiler Description and Documentation
• Compiler and Other Development Tools
1.2
DEVICE DESCRIPTION
The MPLAB XC32 C/C++ Compiler fully supports all Microchip 32-bit devices.
1.3
COMPILER DESCRIPTION AND DOCUMENTATION
The MPLAB XC32 C/C++ Compiler is a full-featured, optimizing compiler that translates standard ANSI C programs into 32-bit device assembly language source. The
compiler also supports many command-line options and language extensions that
allow full access to the 32-bit device hardware capabilities, and affords fine control of
the compiler code generator.
The compiler is a port of the GCC compiler from the Free Software Foundation.
The compiler is available for several popular operating systems, including 32 and 64-bit
Windows®, Linux and Apple OS X.
The compiler can run in one of three operating modes: Free, Standard or PRO. The
Standard and PRO operating modes are licensed modes and require an activation key
and Internet connectivity to enable them. Free mode is available for unlicensed customers. The basic compiler operation, supported devices and available memory are
identical across all modes. The modes only differ in the level of optimization employed
by the compiler.
1.3.1
Conventions
Throughout this manual, the term “the compiler” is often used. It can refer to either all,
or some subset of, the collection of applications that form the MPLAB XC32 C/C++
Compiler. Often it is not important to know, for example, whether an action is performed
by the parser or code generator application, and it is sufficient to say it was performed
by “the compiler”.
It is also reasonable for “the compiler” to refer to the command-line driver (or just driver)
as this is the application that is always executed to invoke the compilation process. The
driver for the MPLAB XC32 C/C++ Compiler package is called xc32-gcc. The driver
for the C/ASM projects is also xc32-gcc. The driver for C/C++/ASM projects is
xc32-g++. The drivers and their options are discussed in Section 3.9 “Driver Option
Descriptions”. Following this view, “compiler options” should be considered command-line driver options, unless otherwise specified in this manual.
Similarly “compilation” refers to all, or some part of, the steps involved in generating
source code into an executable binary image.
2012 Microchip Technology Inc.
DS51686E-page 13
MPLAB® XC32 C/C++ Compiler User’s Guide
1.3.2
ANSI C Standards
The compiler is a fully validated compiler that conforms to the ANSI C standard as
defined by the ANSI specification (ANSI x3.159-1989) and described in Kernighan and
Ritchie’s The C Programming 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. In addition, language extensions for PIC32 MCU embedded-control applications are included.
1.3.3
Optimization
The compiler uses a set of sophisticated optimization passes that employ many
advanced techniques for generating efficient, compact code from C/C++ source. The
optimization passes include high-level optimizations that are applicable to any C/C++
code, as well as PIC32 MCU-specific optimizations that take advantage of the particular features of the device architecture.
For more on optimizations, see Chapter 15. “Optimizations”.
1.3.4
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, 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.3.5
ISO/IEC C++ Standard
The compiler is distributed with the 2003 Standard C++ Library.
Note:
1.3.6
Do not specify an MPLAB XC32 system include directory (e.g.
/pic32mx/include/) in your project properties. The xc32-gcc and
xc32-g++ compilation drivers automatically select the XC libc or the Dinkumware libc and their respective include-file directory for you. Manually
adding a system include file path may disrupt this mechanism and cause
the incorrect libc include files to be compiled into your project, causing a
conflict between the include files and the library. Note that adding a system
include path to your project properties has never been a recommended
practice.
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.
1.3.7
Documentation
The C compiler is supported under both the MPLAB IDE v8.xx or higher, and the
MPLAB X IDE. For C++, MPLAB X IDE v1.40 or higher is required. For simplicity, both
IDEs are referred to throughout the book as simply MPLAB IDE.
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.
DS51686E-page 14
2012 Microchip Technology Inc.
Compiler Overview
1.4
COMPILER AND OTHER DEVELOPMENT TOOLS
The compiler works with many other Microchip tools including:
• MPLAB XC32 assembler and linker - see the “MPLAB® Assembler, Linker and
Utilities for PIC32 MCUs User’s Guide”.
• MPLAB IDE v8.xx and MPLAB X IDE (C++ required MPLAB X IDE v1.30 or
higher)
• The MPLAB Simulator
• All Microchip debug tools and programmers
• Demo boards and starter kits that support 32-bit devices
2012 Microchip Technology Inc.
DS51686E-page 15
MPLAB® XC32 C/C++ Compiler User’s Guide
NOTES:
DS51686E-page 16
2012 Microchip Technology Inc.
MPLAB® XC32 C/C++ COMPILER
USER’S GUIDE
Chapter 2. Common C Interface
2.1
INTRODUCTION
The Common C Interface (CCI) is available with all MPLAB XC C compilers and is
designed to enhance code portability between these compilers. For example,
CCI-conforming code would make it easier to port from a PIC18 MCU using the MPLAB
XC8 C compiler to a PIC32 MCU using the MPLAB XC32 C/C++ Compiler.
The CCI assumes that your source code already conforms to the ANSI Standard. If you
intend to use the CCI, it is your responsibility to write code that conforms. Legacy projects will need to be migrated to achieve conformance. A compiler option must also be
set to ensure that the operation of the compiler is consistent with the interface when the
project is built.
The following topics are examined in this chapter:
•
•
•
•
•
2.2
Background — The Desire for Portable Code
Using the CCI
ANSI Standard Refinement
ANSI Standard Extensions
Compiler Features
BACKGROUND – THE DESIRE FOR PORTABLE CODE
All programmers want to write portable source code.
Portability means that the same source code can be compiled and run in a different
execution environment than that for which it was written. Rarely can code be one hundred percent portable, but the more tolerant it is to change, the less time and effort it
takes to have it running in a new environment.
Embedded engineers typically think of code portability as being across target devices,
but this is only part of the situation. The same code could be compiled for the same
target but with a different compiler. Differences between those compilers might lead to
the code failing at compile time or runtime, so this must be considered as well.
You may only write code for one target device and only use one brand of compiler, but
if there is no regulation of the compiler’s operation, simply updating your compiler version may change your code’s behavior.
Code must be portable across targets, tools, and time to be truly flexible.
Clearly, this portability cannot be achieved by the programmer alone, since the compiler vendors can base their products on different technologies, implement different features and code syntax, or improve the way their product works. Many a great compiler
optimization has broken many an unsuspecting project.
Standards for the C language have been developed to ensure that change is managed
and code is more portable. The American National Standards Institute (ANSI) publishes standards for many disciplines, including programming languages. The ANSI C
Standard is a universally adopted standard for the C programming language.
2012 Microchip Technology Inc.
DS51686E-page 17
MPLAB® XC32 C/C++ Compiler User’s Guide
2.2.1
The ANSI Standard
The ANSI C Standard has to reconcile two opposing goals: freedom for compilers vendors to target new devices and improve code generation, with the known functional
operation of source code for programmers. If both goals can be met, source code can
be made portable.
The standard is implemented as a set of rules which detail not only the syntax that a
conforming C program must follow, but the semantic rules by which that program will
be interpreted. Thus, for a compiler to conform to the standard, it must ensure that a
conforming C program functions as described by the standard.
The standard describes implementation, the set of tools and the runtime environment
on which the code will run. If any of these change, e.g., you build for, and run on, a different target device, or if you update the version of the compiler you use to build, then
you are using a different implementation.
The standard uses the term behavior to mean the external appearance or action of the
program. It has nothing to do with how a program is encoded.
Since the standard is trying to achieve goals that could be construed as conflicting,
some specifications appear somewhat vague. For example, the standard states that an
int type must be able to hold at least a 16-bit value, but it does not go as far as saying
what the size of an int actually is; and the action of right-shifting a signed integer can
produce different results on different implementations; yet, these different results are
still ANSI C compliant.
If the standard is too strict, device architectures may not allow the compiler to conform1.
But, if it is too weak, programmers would see wildly differing results within different
compilers and architectures, and the standard would loose its effectiveness.
The standard organizes source code whose behavior is not fully defined into groups
that include the following behaviors:
Implementation-defined behavior
This is unspecified behavior where each implementation documents how the choice
is made.
Unspecified behavior
The standard provides two or more possibilities and imposes no further requirements
on which possibility is chosen in any particular instance.
Undefined behavior
This is behavior for which the standard imposes no requirements.
Code that strictly conforms to the standard does not produce output that is dependent
on any unspecified, undefined, or implementation-defined behavior. The size of an
int, which we used as an example earlier, falls into the category of behavior that is
defined by implementation. That is to say, the size of an int is defined by which compiler is being used, how that compiler is being used, and the device that is being targeted.
All the MPLAB XC compilers conform to the ANS X3.159-1989 Standard for programming languages (with the exception of the XC8 compiler’s inability to allow recursion,
as mentioned in the footnote). This is commonly called the C89 Standard. Some features from the later standard, C99, are also supported.
1. Case in point: The mid-range PIC® microcontrollers do not have a data stack. Because
a compiler targeting this device cannot implement recursion, it (strictly speaking) cannot
conform to the ANSI C Standard. This example illustrate a situation in which the standard is too strict for mid-range devices and tools.
DS51686E-page 18
2012 Microchip Technology Inc.
Common C Interface
For freestanding implementations – or for what we typically call embedded applications
– the standard allows non-standard extensions to the language, but obviously does not
enforce how they are specified or how they work. When working so closely to the
device hardware, a programmer needs a means of specifying device setup and interrupts, as well as utilizing the often complex world of small-device memory
architectures. This cannot be offered by the standard in a consistent way.
While the ANSI C Standard provides a mutual understanding for programmers and
compiler vendors, programmers need to consider the implementation-defined behavior
of their tools and the probability that they may need to use extensions to the C language
that are non-standard. Both of these circumstances can have an impact on code
portability.
2.2.2
The Common C Interface
The Common C Interface (CCI) supplements the ANSI C Standard and makes it easier
for programmers to achieve consistent outcomes on all Microchip devices when using
any of the MPLAB XC C compilers.
It delivers the following improvements, all designed with portability in mind.
Refinement of the ANSI C Standard
The CCI documents specific behavior for some code in which actions are implementation-defined behavior under the ANSI C Standard. For example, the result of
right-shifting a signed integer is fully defined by the CCI. Note that many
implementation-defined items that closely couple with device characteristics, such as
the size of an int, are not defined by the CCI.
Consistent syntax for non-standard extensions
The CCI non-standard extensions are mostly implemented using keywords with a uniform syntax. They replace keywords, macros and attributes that are the native compiler implementation. The interpretation of the keyword may differ across each compiler, and any arguments to the keywords may be device specific.
Coding guidelines
The CCI may indicate advice on how code should be written so that it can be ported
to other devices or compilers. While you may choose not to follow the advice, it will
not conform to the CCI.
2012 Microchip Technology Inc.
DS51686E-page 19
MPLAB® XC32 C/C++ Compiler User’s Guide
2.3
USING THE CCI
The CCI allows enhanced portability by refining implementation-defined behavior and
standardizing the syntax for extensions to the language.
The CCI is something you choose to follow and put into effect, thus it is relevant for new
projects, although you may choose to modify existing projects so they conform.
For your project to conform to the CCI, you must do the following things.
Enable the CCI
Select the MPLAB IDE widget Use CCI Syntax in your project, or use the
command-line option that is equivalent.
Include in every module
Some CCI features are only enabled if this header is seen by the compiler.
Ensure ANSI compliance
Code that does not conform to the ANSI C Standard does not confirm to the CCI.
Observe refinements to ANSI by the CCI
Some ANSI implementation-defined behavior is defined explicitly by the CCI.
Use the CCI extensions to the language
Use the CCI extensions rather than the native language extensions
The next sections detail specific items associated with the CCI. These items are segregated into those that refine the standard, those that deal with the ANSI C Standard
extensions, and other miscellaneous compiler options and usage. Guidelines are indicated with these items.
If any implementation-defined behavior or any non-standard extension is not discussed
in this document, then it is not part of the CCI. For example, GCC case ranges, label
addresses and 24-bit short long types are not part of the CCI. Programs which use
these features do not conform to the CCI. The compiler may issue a warning or error
to indicate when you use a non-CCI feature and the CCI is enabled.
DS51686E-page 20
2012 Microchip Technology Inc.
Common C Interface
2.4
ANSI STANDARD REFINEMENT
The following topics describe how the CCI refines the implementation-defined
behaviors outlined in the ANSI C Standard.
2.4.1
Source File Encoding
Under the CCI, a source file must be written using characters from the 7-bit ASCII set.
Lines may be terminated using a line feed (\n) or carriage return (\r) that is immediately
followed by a line feed. Escaped characters may be used in character constants or
string literals to represent extended characters not in the basic character set.
2.4.1.1
EXAMPLE
The following shows a string constant being defined that uses escaped characters.
const char myName[] = "Bj\370rk\n";
2.4.1.2
DIFFERENCES
All compilers have used this character set.
2.4.1.3
MIGRATION TO THE CCI
No action required.
2.4.2
The Prototype for main
The prototype for the main() function is
int main(void);
2.4.2.1
EXAMPLE
The following shows an example of how main() might be defined
int main(void)
{
while(1)
process();
}
2.4.2.2
DIFFERENCES
The 8-bit compilers used a void return type for this function.
2.4.2.3
MIGRATION TO THE CCI
Each program has one definition for the main() function. Confirm the return type for
main() in all projects previously compiled for 8-bit targets.
2.4.3
Header File Specification
Header file specifications that use directory separators do not conform to the CCI.
2.4.3.1
EXAMPLE
The following example shows two conforming include directives.
#include
#include "global.h"
2012 Microchip Technology Inc.
DS51686E-page 21
MPLAB® XC32 C/C++ Compiler User’s Guide
2.4.3.2
DIFFERENCES
Header file specifications that use directory separators have been allowed in previous
versions of all compilers. Compatibility problems arose when Windows-style separators "\" were used and the code compiled under other host operating systems. Under
the CCI, no directory specifiers should be used.
2.4.3.3
MIGRATION TO THE CCI
Any #include directives that use directory separators in the header file specifications
should be changed. Remove all but the header file name in the directive. Add the directory path to the compiler’s include search path or MPLAB IDE equivalent. This will force
the compiler to search the directories specified with this option.
For example, the following code:
#include
should be changed to:
#include
and the path to the inc directory added to the compiler’s header search path in your
MPLAB IDE project properties, or on the command-line as follows:
-Ilcd
2.4.4
Include Search Paths
When you include a header file under the CCI, the file should be discoverable in the
paths searched by the compiler detailed below.
For any header files specified in angle bracket delimiters < >, the search paths should
be those specified by -I options (or the equivalent MPLAB IDE option), then the standard compiler include directories. The -I options are searched in the order in which
they are specified.
For any file specified in quote characters " ", the search paths should first be the current working directory. In the case of an MPLAB X project, the current working directory
is the directory in which the C source file is located. If unsuccessful, the search paths
should be the same directories searched when the header files is specified in angle
bracket delimiters.
Any other options to specify search paths for header files do not conform to the CCI.
2.4.4.1
EXAMPLE
If including a header file as in the following directive
#include "myGlobals.h"
The header file should be locatable in the current working directory, or the paths specified by any -I options, or the standard compiler directories. If it is located elsewhere,
this does not conform to the CCI.
2.4.4.2
DIFFERENCES
The compiler operation under the CCI is not changed. This is purely a coding guide line.
2.4.4.3
MIGRATION TO THE CCI
Remove any option that specifies header file search paths other than the -I option (or
the equivalent MPLAB IDE option), and use the -I option in place of this. Ensure the
header file can be found in the directories specified in this section.
DS51686E-page 22
2012 Microchip Technology Inc.
Common C Interface
2.4.5
The Number of Significant Initial Characters in an Identifier
At least the first 255 characters in an identifier (internal and external) are significant.
This extends upon the requirement of the ANSI C Standard which states a lower number of significant characters are used to identify an object.
2.4.5.1
EXAMPLE
The following example shows two poorly named variables, but names which are
considered unique under the CCI.
int stateOfPortBWhenTheOperatorHasSelectedAutomaticModeAndMotorIsRunningFast;
int stateOfPortBWhenTheOperatorHasSelectedAutomaticModeAndMotorIsRunningSlow;
2.4.5.2
DIFFERENCES
Former 8-bit compilers used 31 significant characters by default, but an option allowed
this to be extended.
The 16- and 32-bit compilers did not impose a limit on the number of significant characters.
2.4.5.3
MIGRATION TO THE CCI
No action required. You may take advantage of the less restrictive naming scheme.
2.4.6
Sizes of Types
The sizes of the basic C types, for example char, int and long, are not fully defined
by the CCI. These types, by design, reflect the size of registers and other architectural
features in the target device. They allow the device to efficiently access objects of this
type. The ANSI C Standard does, however, indicate minimum requirements for these
types, as specified in .
If you need fixed-size types in your project, use the types defined in , e.g.,
uint8_t or int16_t. These types are consistently defined across all XC compilers,
even outside of the CCI.
Essentially, the C language offers a choice of two groups of types: those that offer sizes
and formats that are tailored to the device you are using; or those that have a fixed size,
regardless of the target.
2.4.6.1
EXAMPLE
The following example shows the definition of a variable, native, whose size will allow
efficient access on the target device; and a variable, fixed, whose size is clearly indicated and remains fixed, even though it may not allow efficient access on every device.
int native;
int16_t fixed;
2.4.6.2
DIFFERENCES
This is consistent with previous types implemented by the compiler.
2.4.6.3
MIGRATION TO THE CCI
If you require a C type that has a fixed size, regardless of the target device, use one of
the types defined by .
2012 Microchip Technology Inc.
DS51686E-page 23
MPLAB® XC32 C/C++ Compiler User’s Guide
2.4.7
Plain char Types
The type of a plain char is unsigned char. It is generally recommended that all definitions for the char type explicitly state the signedness of the object.
2.4.7.1
EXAMPLE
The following example
char foobar;
defines an unsigned char object called foobar.
2.4.7.2
DIFFERENCES
The 8-bit compilers have always treated plain char as an unsigned type.
The 16- and 32-bit compilers used signed char as the default plain char type. The
-funsigned-char option on those compilers changed the default type to be
unsigned char.
2.4.7.3
MIGRATION TO THE CCI
Any definition of an object defined as a plain char and using the 16- or 32-bit compilers
needs review. Any plain char that was intended to be a signed quantity should be
replaced with an explicit definition, for example.
signed char foobar;
You may use the -funsigned-char option on XC16/32 to change the type of plain
char, but since this option is not supported on XC8, the code is not strictly conforming.
2.4.8
Signed Integer Representation
The value of a signed integer is determined by taking the two’s complement of the integer.
2.4.8.1
EXAMPLE
The following shows a variable, test, that is assigned the value -28 decimal.
signed char test = 0xE4;
2.4.8.2
DIFFERENCES
All compilers have represented signed integers in the way described in this section.
2.4.8.3
MIGRATION TO THE CCI
No action required.
DS51686E-page 24
2012 Microchip Technology Inc.
Common C Interface
2.4.9
Integer conversion
When converting an integer type to a signed integer of insufficient size, the original
value is truncated from the most-significant bit to accommodate the target size.
2.4.9.1
EXAMPLE
The following shows an assignment of a value that will be truncated.
signed char destination;
unsigned int source = 0x12FE;
destination = source;
Under the CCI, the value of destination after the alignment will be -2 (i.e., the bit
pattern 0xFE).
2.4.9.2
DIFFERENCES
All compilers have performed integer conversion in an identical fashion to that
described in this section.
2.4.9.3
MIGRATION TO THE CCI
No action required.
2.4.10
Bit-wise Operations on Signed Values
Bitwise operations on signed values act on the two’s complement representation,
including the sign bit. See also Section 2.4.11 “Right-shifting Signed Values”.
2.4.10.1
EXAMPLE
The following shows an example of a negative quantity involved in a bitwise AND operation.
signed char output, input = -13;
output = input & 0x7E;
Under the CCI, the value of output after the assignment will be 0x72.
2.4.10.2
DIFFERENCES
All compilers have performed bitwise operations in an identical fashion to that
described in this section.
2.4.10.3
MIGRATION TO THE CCI
No action required.
2.4.11
Right-shifting Signed Values
Right-shifting a signed value will involve sign extension. This will preserve the sign of
the original value.
2.4.11.1
EXAMPLE
The following shows an example of a negative quantity involved in a bitwise AND operation.
signed char input, output = -13;
output = input >> 3;
Under the CCI, the value of output after the assignment will be -2 (i.e., the bit pattern
0xFE).
2012 Microchip Technology Inc.
DS51686E-page 25
MPLAB® XC32 C/C++ Compiler User’s Guide
2.4.11.2
DIFFERENCES
All compilers have performed right shifting as described in this section.
2.4.11.3
MIGRATION TO THE CCI
No action required.
2.4.12
Conversion of Union Member Accessed Using Member With
Different Type
If a union defines several members of different types and you use one member identifier to try to access the contents of another (whether any conversion is applied to the
result) is implementation-defined behavior in the standard. In the CCI, no conversion is
applied and the bytes of the union object are interpreted as an object of the type of the
member being accessed, without regard for alignment or other possible invalid conditions.
2.4.12.1
EXAMPLE
The following shows an example of a union defining several members.
union {
signed char code;
unsigned int data;
float offset;
} foobar;
Code that attempts to extract offset by reading data is not guaranteed to read the
correct value.
float result;
result = foobbar.data;
2.4.12.2
DIFFERENCES
All compilers have not converted union members accessed via other members.
2.4.12.3
MIGRATION TO THE CCI
No action required.
2.4.13
Default Bit-field int Type
The type of a bit-field specified as a plain int will be identical to that of one defined
using unsigned int. This is quite different to other objects where the types int,
signed and signed int are synonymous. It is recommended that the signedness of
the bit-field be explicitly stated in all bit-field definitions.
2.4.13.1
EXAMPLE
The following shows an example of a structure tag containing bit-fields which are
unsigned integers and with the size specified.
struct
int
int
int
};
DS51686E-page 26
OUTPUTS {
direction :1;
parity
:3;
value
:4;
2012 Microchip Technology Inc.
Common C Interface
2.4.13.2
DIFFERENCES
The 8-bit compilers have previously issued a warning if type int was used for bit-fields,
but would implement the bit-field with an unsigned int type.
The 16- and 32-bit compilers have implemented bit-fields defined using int as having
a signed int type, unless the option -funsigned-bitfields was specified.
2.4.13.3
MIGRATION TO THE CCI
Any code that defines a bit-field with the plain int type should be reviewed. If the intention was for these to be signed quantities, then the type of these should be changed to
signed int, for example, in:
struct WAYPT {
int log
int direction
};
:3;
:4;
the bit-field type should be changed to signed int, as in:
struct WAYPT {
signed int log
:3;
signed int direction :4;
};
2.4.14
Bit-fields Straddling a Storage Unit Boundary
Whether a bit-field can straddle a storage unit boundary is implementation-defined
behavior in the standard. In the CCI, bit-fields will not straddle a storage unit boundary;
a new storage unit will be allocated to the structure, and padding bits will fill the gap.
Note that the size of a storage unit differs with each compiler as this is based on the
size of the base data type (e.g., int) from which the bit-field type is derived. On 8-bit
compilers this unit is 8-bits in size; for 16-bit compilers, it is 16 bits; and for 32-bit compilers, it is 32 bits in size.
2.4.14.1
EXAMPLE
The following shows a structure containing bit-fields being defined.
struct {
unsigned first : 6;
unsigned second :6;
} order;
Under the CCI and using XC8, the storage allocation unit is byte sized. The bit-field
second, will be allocated a new storage unit since there are only 2 bits remaining in
the first storage unit in which first is allocated. The size of this structure, order, will
be 2 bytes.
2.4.14.2
DIFFERENCES
This allocation is identical with that used by all previous compilers.
2.4.14.3
MIGRATION TO THE CCI
No action required.
2.4.15
The Allocation Order of Bits-field
The memory ordering of bit-fields into their storage unit is not specified by the ANSI C
Standard. In the CCI, the first bit defined will be the least significant bit of the storage
unit in which it will be allocated.
2012 Microchip Technology Inc.
DS51686E-page 27
MPLAB® XC32 C/C++ Compiler User’s Guide
2.4.15.1
EXAMPLE
The following shows a structure containing bit-fields being defined.
struct {
unsigned lo : 1;
unsigned mid :6;
unsigned hi : 1;
} foo;
The bit-field lo will be assigned the least significant bit of the storage unit assigned to
the structure foo. The bit-field mid will be assigned the next 6 least significant bits, and
hi, the most significant bit of that same storage unit byte.
2.4.15.2
DIFFERENCES
This is identical with the previous operation of all compilers.
2.4.15.3
MIGRATION TO THE CCI
No action required.
2.4.16
The NULL macro
The NULL macro is defined in ; however, its definition is implementation-defined behavior. Under the CCI, the definition of NULL is the expression (0).
2.4.16.1
EXAMPLE
The following shows a pointer being assigned a null pointer constant via the NULL
macro.
int * ip = NULL;
The value of NULL, (0), is implicitly cast to the destination type.
2.4.16.2
DIFFERENCES
The 32-bit compilers previously assigned NULL the expression ((void *)0).
2.4.16.3
MIGRATION TO THE CCI
No action required.
2.4.17
Floating-point sizes
Under the CCI, floating-point types must not be smaller than 32 bits in size.
2.4.17.1
EXAMPLE
The following shows the definition for outY, which will be at least 32-bit in size.
float outY;
2.4.17.2
DIFFERENCES
The 8-bit compilers have allowed the use of 24-bit float and double types.
2.4.17.3
MIGRATION TO THE CCI
When using 8-bit compilers, the float and double type will automatically be made
32 bits in size once the CCI mode is enabled. Review any source code that may have
assumed a float or double type and may have been 24 bits in size.
No migration is required for other compilers.
DS51686E-page 28
2012 Microchip Technology Inc.
Common C Interface
2.5
ANSI STANDARD EXTENSIONS
The following topics describe how the CCI provides device-specific extensions to the
standard.
2.5.1
Generic Header File
A single header file must be used to declare all compiler- and device-specific
types and SFRs. You must include this file into every module to conform with the CCI.
Some CCI definitions depend on this header being seen.
2.5.1.1
EXAMPLE
The following shows this header file being included, thus allowing conformance with the
CCI, as well as allowing access to SFRs.
#include
2.5.1.2
DIFFERENCES
Some 8-bit compilers used as the equivalent header. Previous versions of
the 16- and 32-bit compilers used a variety of headers to do the same job.
2.5.1.3
MIGRATION TO THE CCI
Change:
#include
used previously in 8-bit compiler code, or family-specific header files as in the following
examples:
#include
#include
#include
#include
#include
"p30f6014.h"
to:
#include
2.5.2
Absolute addressing
Variables and functions can be placed at an absolute address by using the __at()
construct.qualifier Note that XC16/32 may require the variable or function to be placed
in a special section for absolute addressing to work. Stack-based (auto and parameter) variables cannot use the __at() specifier.
2.5.2.1
EXAMPLE
The following shows two variables and a function being made absolute.
int scanMode __at(0x200);
const char keys[] __at(123) = { ’r’, ’s’, ’u’, ’d’};
int modify(int x) __at(0x1000) {
return x * 2 + 3;
}
2.5.2.2
DIFFERENCES
The 8-bit compilers have used an @ symbol to specify an absolute address.
The 16- and 32-bit compilers have used the address attribute to specify an object’s
address.
2012 Microchip Technology Inc.
DS51686E-page 29
MPLAB® XC32 C/C++ Compiler User’s Guide
2.5.2.3
MIGRATION TO THE CCI
Avoid making objects and functions absolute if possible.
In XC8, change absolute object definitions such as the following example:
int scanMode @ 0x200;
to:
int scanMode __at(0x200);
In XC16/32, change code such as:
int scanMode __attribute__(address(0x200)));
to:
int scanMode __at(0x200);
2.5.2.4
CAVEATS
If the __at() and __section() specifiers are both applied to an object when using
XC8, the __section() specifier is currently ignored.
2.5.3
Far Objects and Functions
The __far qualifier may be used to indicate that variables or functions may be located
in ‘far memory’. Exactly what constitutes far memory is dependent on the target device,
but it is typically memory that requires more complex code to access. Expressions
involving far-qualified objects may generate slower and larger code.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this qualifier.
Some devices may not have such memory implemented, in which case, use of this
qualifier will be ignored. Stack-based (auto and parameter) variables cannot use the
__far specifier.
2.5.3.1
EXAMPLE
The following shows a variable and function qualified using __far.
__far int serialNo;
__far int ext_getCond(int selector);
2.5.3.2
DIFFERENCES
The 8-bit compilers have used the qualifier far to indicate this meaning. Functions
could not be qualified as far.
The 16-bit compilers have used the far attribute with both variables and functions.
The 32-bit compilers have used the far attribute with functions, only.
DS51686E-page 30
2012 Microchip Technology Inc.
Common C Interface
2.5.3.3
MIGRATION TO THE CCI
For 8-bit compilers, change any occurrence of the far qualifier, as in the following
example:
far char template[20];
to __far, i.e., __far char template[20];
In the 16- and 32-bit compilers, change any occurrence of the far attribute, as in the
following
void bar(void) __attribute__ ((far));
int tblIdx __attribute__ ((far));
to
void __far bar(void);
int __far tblIdx;
2.5.3.4
CAVEATS
None.
2.5.4
Near Objects
The __near qualifier may be used to indicate that variables or functions may be
located in ‘near memory’. Exactly what constitutes near memory is dependent on the
target device, but it is typically memory that can be accessed with less complex code.
Expressions involving near-qualified objects may be faster and result in smaller code.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this qualifier.
Some devices may not have such memory implemented, in which case, use of this
qualifier will be ignored. Stack-based (auto and parameter) variables cannot use the
__near specifier.
2.5.4.1
EXAMPLE
The following shows a variable and function qualified using __near.
__near int serialNo;
__near int ext_getCond(int selector);
2.5.4.2
DIFFERENCES
The 8-bit compilers have used the qualifier near to indicate this meaning. Functions
could not be qualified as near.
The 16-bit compilers have used the near attribute with both variables and functions.
The 32-bit compilers have used the near attribute for functions, only.
2012 Microchip Technology Inc.
DS51686E-page 31
MPLAB® XC32 C/C++ Compiler User’s Guide
2.5.4.3
MIGRATION TO THE CCI
For 8-bit compilers, change any occurrence of the near qualifier, as in the following
example:
near char template[20];
to __near, i.e., __near char template[20];
In 16- and 32-bit compilers, change any occurrence of the near attribute, as in the following
void bar(void) __attribute__ ((near));
int tblIdx __attribute__ ((near));
to
void __near bar(void);
int __near tblIdx;
2.5.4.4
CAVEATS
None.
2.5.5
Persistent Objects
The __persistent qualifier may be used to indicate that variables should not be
cleared by the runtime startup code.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this qualifier.
2.5.5.1
EXAMPLE
The following shows a variable qualified using __persistent.
__persistent int serialNo;
2.5.5.2
DIFFERENCES
The 8-bit compilers have used the qualifier, persistent, to indicate this meaning.
The 16- and 32-bit compilers have used the persistent attribute with variables to
indicate they were not to be cleared.
2.5.5.3
MIGRATION TO THE CCI
With 8-bit compilers, change any occurrence of the persistent qualifier, as in the following example:
persistent char template[20];
to __persistent, i.e., __persistent char template[20];
For the 16- and 32-bit compilers, change any occurrence of the persistent attribute,
as in the following
int tblIdx __attribute__ ((persistent));
to
int __persistent tblIdx;
2.5.5.4
CAVEATS
None.
DS51686E-page 32
2012 Microchip Technology Inc.
Common C Interface
2.5.6
X and Y Data Objects
The __xdata and __ydata qualifiers may be used to indicate that variables may be
located in special memory regions. Exactly what constitutes X and Y memory is dependent on the target device, but it is typically memory that can be accessed independently
on separate buses. Such memory is often required for some DSP instructions.
Use the native keywords discussed in the Differences section to look up information on
the semantics of these qualifiers.
Some devices may not have such memory implemented; in which case, use of these
qualifiers will be ignored.
2.5.6.1
EXAMPLE
The following shows a variable qualified using __xdata, as well as another variable
qualified with __ydata.
__xdata char data[16];
__ydata char coeffs[4];
2.5.6.2
DIFFERENCES
The 16-bit compilers have used the xmemory and ymemory space attribute with
variables.
Equivalent specifiers have never been defined for any other compiler.
2.5.6.3
MIGRATION TO THE CCI
For 16-bit compilers, change any occurrence of the space attributes xmemory or
ymemory, as in the following example:
char __attribute__((space(xmemory)))template[20];
to __xdata, or __ydata, i.e., __xdata char template[20];
2.5.6.4
CAVEATS
None.
2.5.7
Banked Data Objects
The __bank(num) qualifier may be used to indicate that variables may be located in
a particular data memory bank. The number, num, represents the bank number. Exactly
what constitutes banked memory is dependent on the target device, but it is typically a
subdivision of data memory to allow for assembly instructions with a limited address
width field.
Use the native keywords discussed in the Differences section to look up information on
the semantics of these qualifiers.
Some devices may not have banked data memory implemented, in which case, use of
this qualifier will be ignored. The number of data banks implemented will vary from one
device to another.
2.5.7.1
EXAMPLE
The following shows a variable qualified using __bank().
__bank(0) char start;
__bank(5) char stop;
2012 Microchip Technology Inc.
DS51686E-page 33
MPLAB® XC32 C/C++ Compiler User’s Guide
2.5.7.2
DIFFERENCES
The 8-bit compilers have used the four qualifiers bank0, bank1, bank2 and bank3 to
indicate the same, albeit more limited, memory placement.
Equivalent specifiers have never been defined for any other compiler.
2.5.7.3
MIGRATION TO THE CCI
For 8-bit compilers, change any occurrence of the bankx qualifiers, as in the following
example:
bank2 int logEntry;
to __bank(, i.e., __bank(2) int logEntry;
2.5.7.4
CAVEATS
None.
2.5.8
Alignment of Objects
The __align(alignment) specifier may be used to indicate that variables must be
aligned on a memory address that is a multiple of the alignment specified. The alignment term must be a power of two. Positive values request that the object’s start
address be aligned; negative values imply the object’s end address be aligned.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this specifier.
2.5.8.1
EXAMPLE
The following shows variables qualified using __align() to ensure they end on an
address that is a multiple of 8, and start on an address that is a multiple of 2,
respectively.
__align(-8) int spacer;
__align(2) char coeffs[6];
2.5.8.2
DIFFERENCES
An alignment feature has never been implemented on 8-bit compilers.
The 16- and 32-bit compilers used the aligned attribute with variables.
2.5.8.3
MIGRATION TO THE CCI
For 16- and 32-bit compilers, change any occurrence of the aligned attribute, as in
the following example:
char __attribute__((aligned(4)))mode;
to __align, i.e., __align(4) char mode;
2.5.8.4
CAVEATS
This feature is not yet implemented on XC8.
DS51686E-page 34
2012 Microchip Technology Inc.
Common C Interface
2.5.9
EEPROM Objects
The __eeprom qualifier may be used to indicate that variables should be positioned in
EEPROM.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this qualifier.
Some devices may not implement EEPROM. Use of this qualifier for such devices will
generate a warning. Stack-based (auto and parameter) variables cannot use the
__eeprom specifier.
2.5.9.1
EXAMPLE
The following shows a variable qualified using __eeprom.
__eeprom int serialNos[4];
2.5.9.2
DIFFERENCES
The 8-bit compilers have used the qualifier, eeprom, to indicate this meaning for some
devices.
The 16-bit compilers have used the space attribute to allocate variables to the memory
space used for EEPROM.
2.5.9.3
MIGRATION TO THE CCI
For 8-bit compilers, change any occurrence of the eeprom qualifier, as in the following
example:
eeprom char title[20];
to __eeprom, i.e., __eeprom char title[20];
For 16-bit compilers, change any occurrence of the eedata space attribute, as in the
following
int mainSw __attribute__ ((space(eedata)));
to
int __eeprom mainSw;
2.5.9.4
CAVEATS
XC8 does not implement the __eeprom qualifiers for any PIC18 devices; this qualifier
will work as expected for other 8-bit devices.
2.5.10
Interrupt Functions
The __interrupt(type) specifier may be used to indicate that a function is to act
as an interrupt service routine. The type is a comma-separated list of keywords that
indicate information about the interrupt function.
The current interrupt types are:
Implement the default interrupt function
low_priority
The interrupt function corresponds to the low priority interrupt source (XC8 – PIC18
only)
high_priority
The interrupt function corresponds to the high priority interrupt source (XC8)
2012 Microchip Technology Inc.
DS51686E-page 35
MPLAB® XC32 C/C++ Compiler User’s Guide
save(symbol-list)
Save on entry and restore on exit the listed symbols (XC16)
irq(irqid)
Specify the interrupt vector associated with this interrupt (XC16)
altirq(altirqid)
Specify the alternate interrupt vector associated with this interrupt (XC16)
preprologue(asm)
Specify assembly code to be executed before any compiler-generated interrupt code
(XC16)
shadow
Allow the ISR to utilise the shadow registers for context switching (XC16)
auto_psv
The ISR will set the PSVPAG register and restore it on exit (XC16)
no_auto_psv
The ISR will not set the PSVPAG register (XC16)
Use the native keywords discussed in the Differences section to look up information on
the semantics of this specifier.
Some devices may not implement interrupts. Use of this qualifier for such devices will
generate a warning. If the argument to the __interrupt specifier does not make
sense for the target device, a warning or error will be issued by the compiler.
2.5.10.1
EXAMPLE
The following shows a function qualified using __interrupt.
__interrupt(low_priority) void getData(void) {
if (TMR0IE && TMR0IF) {
TMR0IF=0;
++tick_count;
}
}
2.5.10.2
DIFFERENCES
The 8-bit compilers have used the interrupt and low_priority qualifiers to indicate this meaning for some devices. Interrupt routines were by default high priority.
The 16- and 32-bit compilers have used the interrupt attribute to define interrupt
functions.
2.5.10.3
MIGRATION TO THE CCI
For 8-bit compilers, change any occurrence of the interrupt qualifier, as in the
following examples:
void interrupt myIsr(void)
void interrupt low_priority myLoIsr(void)
to the following, respectively
void __interrupt(high_priority) myIsr(void)
void __interrupt(low_priority) myLoIsr(void)
For 16-bit compilers, change any occurrence of the interrupt attribute, as in the following example:
void __attribute__((interrupt,auto_psv,(irq(52)))) myIsr(void);
DS51686E-page 36
2012 Microchip Technology Inc.
Common C Interface
to
void __interrupt(auto_psv,(irq(52)))) myIsr(void);
For 32-bit compilers, the __interrupt() keyword takes two parameters, the vector
number and the (optional) IPL value. Change code which uses the interrupt attribute, similar to these examples:
void __attribute__((vector(0), interrupt(IPL7AUTO), nomips16))
myisr0_7A(void) {}
void __attribute__((vector(1), interrupt(IPL6SRS), nomips16))
myisr1_6SRS(void) {}
/* Determine IPL and context-saving mode at runtime */
void __attribute__((vector(2), interrupt(), nomips16))
myisr2_RUNTIME(void) {}
to
void __interrupt(0,IPL7AUTO) myisr0_7A(void) {}
void __interrupt(1,IPL6SRS) myisr1_6SRS(void) {}
/* Determine IPL and context-saving mode at runtime */
void __interrupt(2) myisr2_RUNTIME(void) {}
2.5.10.4
CAVEATS
None.
2.5.11
Packing Objects
The __pack specifier may be used to indicate that structures should not use memory
gaps to align structure members, or that individual structure members should not be
aligned.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this specifier.
Some compilers may not pad structures with alignment gaps for some devices and use
of this specifier for such devices will be ignored.
2.5.11.1
EXAMPLE
The following shows a structure qualified using __pack as well as a structure where
one member has been explicitly packed.
__pack struct DATAPOINT {
unsigned char type;
int value;
} x-point;
struct LINETYPE {
unsigned char type;
__pack int start;
long total;
} line;
2.5.11.2
DIFFERENCES
The __pack specifier is a new CCI specifier available with XC8. This specifier has no
apparent effect since the device memory is byte addressable for all data objects.
The 16- and 32-bit compilers have used the packed attribute to indicate that a structure member was not aligned with a memory gap.
2012 Microchip Technology Inc.
DS51686E-page 37
MPLAB® XC32 C/C++ Compiler User’s Guide
2.5.11.3
MIGRATION TO THE CCI
No migration is required for XC8.
For 16- and 32-bit compilers, change any occurrence of the packed attribute, as in the
following example:
struct DOT
{
char a;
int x[2] __attribute__ ((packed));
};
to:
struct DOT
{
char a;
__pack int x[2];
};
Alternatively, you may pack the entire structure, if required.
2.5.11.4
CAVEATS
None.
2.5.12
Indicating Antiquated Objects
The __deprecate specifier may be used to indicate that an object has limited longevity and should not be used in new designs. It is commonly used by the compiler vendor
to indicate that compiler extensions or features may become obsolete, or that better
features have been developed and which should be used in preference.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this specifier.
2.5.12.1
EXAMPLE
The following shows a function which uses the __deprecate keyword.
void __deprecate getValue(int mode)
{
//...
}
2.5.12.2
DIFFERENCES
No deprecate feature was implemented on 8-bit compilers.
The 16- and 32-bit compilers have used the deprecated attribute (note different spelling) to indicate that objects should be avoided if possible.
2.5.12.3
MIGRATION TO THE CCI
For 16- and 32-bit compilers, change any occurrence of the deprecated attribute, as
in the following example:
int __attribute__(deprecated) intMask;
to:
int __deprecate intMask;
2.5.12.4
CAVEATS
None.
DS51686E-page 38
2012 Microchip Technology Inc.
Common C Interface
2.5.13
Assigning Objects to Sections
The __section() specifier may be used to indicate that an object should be located
in the named section (or psect, using the XC8 terminology). This is typically used when
the object has special and unique linking requirements which cannot be addressed by
existing compiler features.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this specifier.
2.5.13.1
EXAMPLE
The following shows a variable which uses the __section keyword.
int __section("comSec") commonFlag;
2.5.13.2
DIFFERENCES
The 8-bit compilers have used the #pragma psect directive to redirect objects to a
new section, or psect. The operation of the __section() specifier is different to this
pragma in several ways, described below.
Unlike with the pragma, the new psect created with __section() does not inherit the
flags of the psect in which the object would normally have been allocated. This means
that the new psect can be linked in any memory area, including any data bank. The
compiler will also make no assumptions about the location of the object in the new section. Objects redirected to new psects using the pragma must always be linked in the
same memory area, albeit at any address in that area.
The __section() specifier allows objects that are initialized to be placed in a different
psect. Initialization of the object will still be performed even in the new psect. This will
require the automatic allocation of an additional psect (whose name will be the same
as the new psect prefixed with the letter i), which will contain the initial values. The
pragma cannot be used with objects that are initialized.
Objects allocated a different psect with __section() will be cleared by the runtime
startup code, unlike objects which use the pragma.
You must reserve memory, and locate via a linker option, for any new psect created with
a __section() specifier in the current XC8 compiler implementation.
The 16- and 32-bit compilers have used the section attribute to indicate a different
destination section name. The __section() specifier works in a similar way to the
attribute.
2.5.13.3
MIGRATION TO THE CCI
For XC8, change any occurrence of the #pragma psect directive, such as
#pragma psect text%%u=myText
int getMode(int target) {
//...
}
to the __section() specifier, as in
int __section ("myText") getMode(int target) {
//...
}
For 16- and 32-bit compilers, change any occurrence of the section attribute, as in
the following example:
int __attribute__((section("myVars"))) intMask;
to:
int __section("myVars") intMask;
2012 Microchip Technology Inc.
DS51686E-page 39
MPLAB® XC32 C/C++ Compiler User’s Guide
2.5.13.4
CAVEATS
With XC8, the __section() specifier cannot be used with any interrupt function.
2.5.14
Specifying Configuration Bits
The #pragma config directive may be used to program the configuration bits for a
device. The pragma has the form:
#pragma config setting = state|value
#pragma config register = value
where setting is a configuration setting descriptor (e.g., WDT), state is a descriptive
value (e.g., ON) and value is a numerical value. The register token may represent a
whole configuration word register, e.g., CONFIG1L.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this directive.
2.5.14.1
EXAMPLE
The following shows configuration bits being specified using this pragma.
#pragma config WDT=ON, WDTPS = 0x1A
2.5.14.2
DIFFERENCES
The 8-bit compilers have used the __CONFIG() macro for some targets that did not
already have support for the #pragma config.
The 16-bit compilers have used a number of macros to specify the configuration settings.
The 32-bit compilers supported the use of #pragma config.
2.5.14.3
MIGRATION TO THE CCI
For the 8-bit compilers, change any occurrence of the __CONFIG() macro, such as
__CONFIG(WDTEN & XT & DPROT)
to the #pragma config directive, as in
#pragma config WDTE=ON, FOSC=XT, CPD=ON
No migration is required if the #pragma config was already used.
For the 16-bit compilers, change any occurrence of the _FOSC() or _FBORPOR()
macros attribute, as in the following example:
_FOSC(CSW_FSCM_ON & EC_PLL16);
to:
#pragma config FCKSMEM = CSW_ON_FSCM_ON,
FPR = ECIO_PLL16
No migration is required for 32-bit code.
2.5.14.4
CAVEATS
None.
DS51686E-page 40
2012 Microchip Technology Inc.
Common C Interface
2.5.15
Manifest Macros
The CCI defines the general form for macros that manifest the compiler and target
device characteristics. These macros can be used to conditionally compile alternate
source code based on the compiler or the target device.
The macros and macro families are details in Table 2-1.
TABLE 2-1:
MANIFEST MACROS DEFINED BY THE CCI
Name
Meaning if defined
Example
__XC__
Compiled with an MPLAB XC compiler
__CCI__
Compiler is CCI compliant and CCI enforce- __CCI__
ment is enabled
__XC##__
The specific XC compiler used (## can be 8, __XC8__
16 or 32)
__DEVICEFAMILY__
The family of the selected target device
__dsPIC30F__
__DEVICENAME__
The selected target device name
__18F452__
2.5.15.1
__XC__
EXAMPLE
The following shows code which is conditionally compiled dependent on the device
having EEPROM memory.
#ifdef __XC16__
void __interrupt(__auto_psv__) myIsr(void)
#else
void __interrupt(low_priority) myIsr(void)
#endif
2.5.15.2
DIFFERENCES
Some of these CCI macros are new (for example __CCI__), and others have different
names to previous symbols with identical meaning (for example __18F452 is now
__18F452__).
2.5.15.3
MIGRATION TO THE CCI
Any code which uses compiler-defined macros will need review. Old macros will continue to work as expected, but they are not compliant with the CCI.
2.5.15.4
CAVEATS
None.
2012 Microchip Technology Inc.
DS51686E-page 41
MPLAB® XC32 C/C++ Compiler User’s Guide
2.5.16
In-line Assembly
The asm() statement may be used to insert assembly code in-line with C code. The
argument is a C string literal which represents a single assembly instruction. Obviously,
the instructions contained in the argument are device specific.
Use the native keywords discussed in the Differences section to look up information on
the semantics of this statement.
2.5.16.1
EXAMPLE
The following shows a MOVLW instruction being inserted in-line.
asm("MOVLW _foobar");
2.5.16.2
DIFFERENCES
The 8-bit compilers have used either the asm() or #asm ... #endasm constructs to
insert in-line assembly code.
This is the same syntax used by the 16- and 32-bit compilers.
2.5.16.3
MIGRATION TO THE CCI
For 8-bit compilers change any instance of #asm ... #endasm so that each instruction
in this #asm block is placed in its own asm() statement, for example:
#asm
MOVLW 20
MOVWF _i
CLRF
Ii+1
#endasm
to
asm("MOVLW20");
asm("MOVWF _i");
asm("CLRFIi+1");
No migration is required for the 16- or 32-bit compilers.
2.5.16.4
CAVEATS
None.
DS51686E-page 42
2012 Microchip Technology Inc.
Common C Interface
2.6
COMPILER FEATURES
The following items detail compiler options and features that are not directly associated
with source code that
2.6.1
Enabling the CCI
It is assumed you are using the MPLAB X IDE to build projects that use the CCI. The
widget in the MPLAB X IDE Project Properties to enable CCI conformance is Use CCI
Syntax in the Compiler category. A widget with the same name is available in MPLAB
IDE v8 under the Compiler tab.
If you are not using this IDE, then the command-line options are --CCI for XC8 or
-mcci for XC16/32.
2.6.1.1
DIFFERENCES
This option has never been implemented previously.
2.6.1.2
MIGRATION TO THE CCI
Enable the option.
2.6.1.3
CAVEATS
None.
2012 Microchip Technology Inc.
DS51686E-page 43
MPLAB® XC32 C/C++ Compiler User’s Guide
NOTES:
DS51686E-page 44
2012 Microchip Technology Inc.
MPLAB® XC32 C/C++ COMPILER
USER’S GUIDE
Chapter 3. Compiler Command Line Driver
3.1
INTRODUCTION
The command line driver (xc32-gcc or xc32-g++) is the application that can be
invoked to perform all aspects of compilation, including C/C++ code generation,
assembly and link steps. Even if you use an IDE to assist with compilation, the IDE will
ultimately call xc32-gcc for C projects or xc32-g++ for C++ projects.
Although the internal compiler applications can be called explicitly from the command
line, using the xc32-gcc or xc32-g++ driver is the recommended way to use the
compiler as it hides the complexity of all the internal applications used and provides a
consistent interface for all compilation steps.
This chapter describes the steps the driver takes during compilation, files that the driver
can accept and produce, as well as the command line options that control the compiler’s operation. It also shows the relationship between these command line options
and the controls in the MPLAB IDE Build Options dialog.
Topics concerning the command line use of the driver are discussed below.
•
•
•
•
•
•
•
•
3.2
Invoking the Compiler
The C Compilation Sequence
The C++ Compilation Sequence
Runtime Files
Start-up and Initialization
Compiler Output
Compiler Messages
Driver Option Descriptions
INVOKING THE COMPILER
The compiler is invoked and runs on the command line as specified in the next section.
Additionally, environmental variables and input files used by the compiler are discussed
in the following sections.
3.2.1
Driver Command Line Format
The compilation driver program (xc32-gcc) compiles, assembles and links C and
assembly language modules and library archives. The xc32-g++ driver must be used
when the module source is written in C++. Most of the compiler command line options
are common to all implementations of the GCC toolset (MPLAB XC16 uses the GCC
toolset; XC8 does not). A few are specific to the compiler.
The basic form of the compiler command line is:
xc32-gcc [options] files
xc32-g++ [options] files
For example, to compile, assemble and link the C source file hello.c, creating the
absolute executable hello.elf,execute this command:
xc32-gcc -o hello.elf hello.c
2012 Microchip Technology Inc.
DS51686E-page 45
MPLAB® XC32 C/C++ Compiler User’s Guide
Or, to compile, assemble and link the C++ source file hello.cpp, creating the
absolute executable hello.elf, execute:
xc32-g++ -o hello.elf hello.cpp
The available options are described in Section 3.9 “Driver Option Descriptions”. It
is conventional to supply options (identified by a leading dash “-” before the
filenames), although this is not mandatory.
The files may be any mixture of C/C++ and assembler source files, relocatable
object files (.o) or archive files. The order of the files is important. It may affect the
order in which code or data appears in memory or the search order for symbols. Typically archive files are specified after source files. The file types are described in
Section 3.2.2 “Input File Types”.
Note:
Command line options and file name extensions are case sensitive.
Libraries is a list of user-defined object code library files that will be searched by the
linker, in addition to the standard C libraries. The order of these files will determine the
order in which they are searched. They are typically placed after the source filenames,
but this is not mandatory.
It is assumed in this manual that the compiler applications are either in the console’s
search path, the appropriate environment variables have been specified, or the full path
is specified when executing any application.
Environment Variables
The variables in this section are optional, but, if defined, they will be used by the
compiler. The compiler driver, or other subprogram, may choose to determine an
appropriate value for some of the following environment variables if they are not set.
The driver, or other subprogram, takes advantage of internal knowledge about the
installation of the compiler. As long as the installation structure remains intact, with all
subdirectories and executables remaining in the same relative position, the driver or
subprogram will be able to determine a usable value. The “XC32” variables should be
used for new projects; however, the “PIC32” variables may be used for legacy projects.
TABLE 3-1:
COMPILER-RELATED ENVIRONMENTAL VARIABLES
Option
Definition
XC32_C_INCLUDE_PATH This variable’s value is a semicolon-separated list of directories,
PIC32_C_INCLUDE_PATH much like PATH. When the compiler searches for header files, it
tries the directories listed in the variable, after the directories
specified with -I but before the standard header file directories.
If the environment variable is undefined, the preprocessor
chooses an appropriate value based on the standard installation.
By default, the following directories are searched for include
files:
\pic32mx\include
XC32_COMPILER_PATH
PIC32_COMPILER_PATH
DS51686E-page 46
The value of PIC32_COMPILER_PATH is a semicolon-separated
list of directories, much like PATH. The compiler tries the directories thus specified when searching for subprograms, if it can’t
find the subprograms using PIC32_EXEC_PREFIX.
2012 Microchip Technology Inc.
Compiler Command Line Driver
TABLE 3-1:
COMPILER-RELATED ENVIRONMENTAL VARIABLES
Option
Definition
XC32_EXEC_PREFIX
PIC32_EXEC_PREFIX
If PIC32_EXEC_PREFIX is set, it specifies a prefix to use in the
names of subprograms executed by the compiler. No directory
delimiter is added when this prefix is combined with the name of
a subprogram, but you can specify a prefix that ends with a slash
if you wish. If the compiler cannot find the subprogram using the
specified prefix, it tries looking in your PATH environment
variable.
If the PIC32_EXEC_PREFIX environment variable is unset or
set to an empty value, the compiler driver chooses an appropriate value based on the standard installation. If the installation
has not been modified, this will result in the driver being able to
locate the required subprograms.
Other prefixes specified with the -B command line option take
precedence over the user- or driver-defined value of
PIC32_EXEC_PREFIX.
Under normal circumstances it is best to leave this value undefined and let the driver locate subprograms itself.
XC32_LIBRARY_PATH
PIC32_LIBRARY_PATH
This variable’s value is a semicolon-separated list of directories,
much like PATH. This variable specifies a list of directories to be
passed to the linker. The driver’s default evaluation of this variable is:
\lib; \pic32mx\lib.
TMPDIR
If TMPDIR is set, it specifies the directory to use for temporary
files. The compiler uses temporary files to hold the output of one
stage of compilation that is to be used as input to the next stage:
for example, the output of the preprocessor, which is the input to
the compiler proper.
2012 Microchip Technology Inc.
DS51686E-page 47
MPLAB® XC32 C/C++ Compiler User’s Guide
3.2.2
Input File Types
The compilation driver recognizes the following file extensions, which are case
sensitive.
TABLE 3-2:
FILE NAMES
Extensions
file.c
file.cpp
Definition
A C source file that must be preprocessed.
A C++ source file that must be preprocessed.
file.h
A header file (not to be compiled or linked).
file.i
A C source file that has already been pre-processed.
file.o
An object file.
file.ii
A C++ source file that has already been pre-processed.
file.s
An assembly language source file.
file.S
An assembly language source file that must be preprocessed.
other
A file to be passed to the linker.
There are no compiler restrictions imposed on the names of source files, but be aware
of case, name-length and other restrictions imposed by your operating system. If you
are using an IDE, avoid assembly source files whose base name is the same as the
base name of any project in which the file is used. This may result in the source file
being overwritten by a temporary file during the build process.
The terms “source file” and “module” are often used when talking about computer
programs. They are often used interchangeably, but they refer to the source code at
different points in the compilation sequence.
A source file is a file that contains all or part of a program. They may contain C/C++
code, as well as preprocessor directives and commands. Source files are initially
passed to the preprocessor by the driver.
A module is the output of the preprocessor, for a given source file, after inclusion of any
header files (or other source files) which are specified by #include preprocessor
directives. All preprocessor directives and commands (with the possible exception of
some commands for debugging) have been removed from these files. These modules
are then passed to the remainder of the compiler applications. Thus, a module may be
the amalgamation of several source and header files. A module is also often referred
to as a translation unit. These terms can also be applied to assembly files, as they too
can include other header and source files.
DS51686E-page 48
2012 Microchip Technology Inc.
Compiler Command Line Driver
3.3
THE C COMPILATION SEQUENCE
3.3.1
Single-step C Compilation
A single command-line instruction can be used to compile one file or multiple files.
3.3.1.1
COMPILING A SINGLE C FILE
This section demonstrates how to compile and link a single file. For the purpose of this
discussion, it is assumed the compiler's /bin directory has been
added to your PATH variable. The following are other directories of note:
• /pic32mx/include the directory for standard C header files.
• /pic32mx/include/proc the directory for PIC32MX
device-specific header files.
• /pic32mx/lib the directory structure for standard libraries
and start-up files.
• /pic32mx/include/peripheral the directory for PIC32MX
peripheral library include files.
• /pic32mx/lib/proc the directory for device-specific linker
script fragments, register definition files and configuration data may be found.
The following is a simple C program that adds two numbers. Create the following
program with any text editor and save it as ex1.c.
#include
#include
// Device-Specific Configuration-Bit settings
// SYSCLK = 80 MHz (8MHz Crystal/ FPLLIDIV * FPLLMUL / FPLLODIV)
// PBCLK = 40 MHz
// Primary Osc w/PLL (XT+,HS+,EC+PLL)
// WDT OFF
// Other options are don't care
//
#pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1,
FWDTEN = OFF
#pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_8
unsigned int x, y, z;
unsigned int
add(unsigned int a, unsigned int b)
{
return(a+b);
}
int
main(void)
{
/* Configure the target for maximum performance at 80 MHz. */
SYSTEMConfigPerformance(80000000UL);
x = 2;
y = 5;
z = add(x,y);
return 0;
}
2012 Microchip Technology Inc.
DS51686E-page 49
MPLAB® XC32 C/C++ Compiler User’s Guide
The first line of the program includes the header file xc.h, which provides definitions
for all Special Function Registers (SFRs) on that part.
Compile the program by typing the following at the prompt:
xc32-gcc
–mprocessor=32MX795F512L -o ex1.out ex1.c
The command line option -o ex1.out names the output executable file (if the -o
option is not specified, then the output file is named a.out). The executable file may
be loaded into MPLAB IDE.
If a hex file is required, for example, to load into a device programmer, then use the
following command:
xc32-bin2hex ex1.out
This creates an Intel hex file named ex1.hex.
3.3.1.2
COMPILING MULTIPLE C FILES
This section demonstrates how to compile and link multiple files in a single step. Move
the Add() function into a file called add.c to demonstrate the use of multiple files in
an application. That is:
File 1
/* ex1.c */
#include
#include
// Device-Specific Configuration-Bit settings
// SYSCLK = 80 MHz (8MHz Crystal/ FPLLIDIV * FPLLMUL / FPLLODIV)
// PBCLK = 40 MHz
// Primary Osc w/PLL (XT+,HS+,EC+PLL)
// WDT OFF
// Other options are don't care
//
#pragma config FPLLMUL = MUL_20, FPLLIDIV = DIV_2, FPLLODIV = DIV_1,
FWDTEN = OFF
#pragma config POSCMOD = HS, FNOSC = PRIPLL, FPBDIV = DIV_8
int main(void);
unsigned int add(unsigned int a, unsigned int b);
unsigned int x, y, z;
int main(void)
{
/* Configure the target for maximum performance at 80 MHz. */
SYSTEMConfigPerformance(80000000UL);
x = 2;
y = 5;
z = Add(x,y);
return 0;
}
File 2
/* add.c */
#include
unsigned int
add(unsigned int a, unsigned int b)
{
return(a+b);
}
DS51686E-page 50
2012 Microchip Technology Inc.
Compiler Command Line Driver
Compile both files by typing the following at the prompt:
xc32-gcc
-mprocessor=32MX795F512L -o ex1.out ex1.c add.c
This command compiles the modules ex1.c and add.c. The compiled modules are
linked with the compiler libraries and the executable file ex1.out is created.
3.3.2
Multi-step C Compilation
Make utilities and IDEs, such as MPLAB IDE, allow for an incremental build of projects
that contain multiple source files. When building a project, they take note of which
source files have changed since the last build and use this information to speed up
compilation.
For example, if compiling two source files, but only one has changed since the last
build, the intermediate file corresponding to the unchanged source file need not be
regenerated.
If the compiler is being invoked using a make utility, the make file will need to be configured to use the intermediate files (.o files) and the options used to generate the
intermediate files (-c, see Section 3.9.2 “Options for Controlling the Kind of Output”). Make utilities typically call the compiler multiple times: once for each source file
to generate an intermediate file, and once to perform the second stage compilation.
For example, the files ex1.c and add.c are to be compiled using a make utility. The
command lines that the make utility should use to compile these files might be
something like:
xc32-gcc -mprocessor=32MX795F512L -c ex1.c
xc32-gcc -mprocessor=32MX795F512L -c add.c
xc32-gcc -mprocessor=32MX795F512L -o ex1.out ex1.o add.o
3.4
THE C++ COMPILATION SEQUENCE
3.4.1
Single-step C++ Compilation
A single command-line instruction can be used to compile one file or multiple files.
3.4.1.1
COMPILING A SINGLE C++ FILE
This section demonstrates how to compile and link a single file. For the purpose of this
discussion, it is assumed the compiler's /bin directory has been
added to your PATH variable. The following are other directories of note:
• /pic32mx/include/cpp the directory for standard C++
header files.
• /pic32mx/include/proc the directory for
PIC32MXdevice-specific header files.
• /pic32mx/lib the directory structure for standard libraries
and start-up files.
• /pic32mx/include/peripheral the directory for PIC32
peripheral library include files.
• /pic32mx/lib/proc the directory for device-specific linker
script fragments, register definition files, and configuration data may be found.
2012 Microchip Technology Inc.
DS51686E-page 51
MPLAB® XC32 C/C++ Compiler User’s Guide
The following is a simple C++ program. Create the following program with any
plain-text editor and save it as ex2.cpp.
/* ex2.cpp */
#include
#include
// __XC_UART
// SYSTEMConfigPerformance()
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
// Device-Specific Configuration-bit settings
#pragma config FPLLMUL=MUL_20, FPLLIDIV=DIV_2, FPLLODIV=DIV_1,
FWDTEN=OFF
#pragma config POSCMOD=HS, FNOSC=PRIPLL, FPBDIV=DIV_8
template
inline void print_elements (const T& coll, const char* optcstr="")
{
typename T::const_iterator pos;
std::cout