You are on page 1of 746

Visual Studio 2005 Smart Device Development

Copyright© 2016 Microsoft Corporation

The content in this document is retired and is no longer updated or supported. Some links might not work. Retired content represents the
latest updated version of this content.
Smart Device Development

Smart Device Development


Visual Studio 2005 offers rich, integrated support for developing software that runs on Windows CE-based smart devices such
as Pocket PCs and Smartphones. You can use Visual C# or Visual Basic to write managed applications that run on the .NET
Compact Framework, or you can write native applications using Visual C++. Whichever language you choose, you will use the
same code editor, designers, and debugger interface as you would use when developing for the PC. Simply select from one of
the Smart Device Project templates available for the language of your choice, and begin coding.
Visual Studio also provides emulators that enable you to run and debug your code on your development computer, and tools
that simplify the process of packaging your application and its resources into CAB files for deployment to end-user devices.
For the most up-to-date information on smart device projects, visit the Mobile Developer Center.
In This Section
Getting Started with Smart Device Projects
Provides overview information on issues specific to device application development, including what's new for Visual Studio
2005, how Visual Studio for Devices relates to other Windows Mobile SDKs and tools, and how to set up your PC to do
software development for devices.
Design Considerations for Smart Device Development
Provides information on choosing a project type, selecting a development language, and customizing skins for emulators.
Connecting Smart Devices to Development Computers
Describes connection methods and options.
Programming for Devices Using the .NET Compact Framework
Explains common procedures when developing smart device software using Visual C# or Visual Basic and the .NET Compact
Framework.
Programming for Devices Using Visual C++
Explains common procedures when using Visual C++ to develop native device applications.
Debugging Device Projects
Explains differences from desktop debugging, and provides instructions for debugging solutions comprised of both native
and managed code.
Packaging Device Solutions for Deployment
Provides instructions for packaging the device applications you develop and transferring them onto one or more target
devices.
Security in Device Projects
Describes how to sign your files with security certificates and provision devices.
Samples and Walkthroughs (Smart Device Projects)
Provides complete projects to illustrate the syntax, structure, and techniques used to solve device programming challenges.
Reference (Devices)
Includes reference topics for ATL and MFC for devices, user interface reference for device projects, error messages, and more.
Related Sections
.NET Compact Framework
Describes how to program device applications. The .NET Compact Framework brings the power of the .NET Framework to
devices. Compares the .NET Compact Framework with the .NET Framework, describes key components, illustrates common
programming tasks, and lists supported classes.
Introducing Visual Studio
Describes what's new in Visual Studio.
Integrated Development Environment for Visual Studio
Provides information on designing, developing, debugging, testing, and managing applications created with Visual Studio.
Smart Device Development

Getting Started with Smart Device Projects


Visual Studio 2005 includes the tools and frameworks you need to develop applications for Pocket PC, Smartphone, and other
Windows CE .NET-based platforms. If you don't have a smart device, you can create and test your smart device applications
using emulation technology without leaving the Visual Studio integrated development environment.
Visual Studio 2005 supports Visual Basic .NET, Visual C#, and Visual C++ languages for smart device application development.
In This Section
What's New in Smart Device Projects
Describes new features for Visual Studio 2005 for smart device projects.
Application Development Overview (Devices)
Discusses solutions based on Windows CE, design issues for small devices, porting existing solutions, choosing a
programming language, comparisons with desktop development, and terminology issues.
Device Capabilities and Required Development Tools
Describes the various versions of smart devices and the tools required to develop for each.
Hardware and Software Requirements for Smart Device Projects
Lists the requirements for building device applications, connecting to devices, and running applications on the device during
the development phase.
Remote Tools for Device Projects
Describes special tools available for smart device projects.
How to: Optimize Help for Smart Device Development
Describes how best to use Help for device projects, including the use of filters.
How to: Launch the Device Emulator in Visual Studio
Describes opening the Device Emulator as a substitute for a physical device.
Updating Projects Created with Previous Tools
Describes how to port projects developed with earlier versions and tools.
How Do I in Smart Device Development
Provides links to help on common smart device issues.
See Also
Other Resources
Smart Device Development
Mobile Developer Center
Smart Device Programmability
Smart Device Development

What's New in Smart Device Projects


This topic has been updated for Visual Studio 2005 SP1.
The following new or expanded features are available in Visual Studio 2005.
What's new in SP1
This section has been updated for Visual Studio 2005 SP1.
eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard
The eMbedded Visual C++ project upgrade wizard has been improved.
List of Desktop MFC Classes Supported for Devices
Fifteen MFC classes were added to device MFC libraries. The following classes were in eMbedded Visual C++ but were
missing in Visual Studio 2005.
CBitmapButton Class
CDialogBar Class
CEditView Class
CFindReplaceDialog Class
CHttpConnection Class
CHttpFile Class
CInternetConnection Class
CInternetException Class
CInternetFile Class
CInternetSession Class
COleSafeArray Class
CReBar Class
CReBarCtrl Class
CRecentFileList Class
CSplitterWnd Class
Prepare for SQL Server Compact Edition
Microsoft SQL Server 2005 Compact Edition replaces SQL Server 2005 Mobile Edition. You will see this change in dialog
boxes in the Visual Studio IDE.
Data Access Overview (Managed Device Projects)
Create SQL Server Compact Edition databases, alter schemas, and perform other database management tasks, all from the
Visual Studio IDE. Use business objects, SQL Server databases, SQL Server Compact Edition databases, or Web services as
datasources.
Windows CE 6.0 releases November 1, 2006
Support for Windows CE 6.0 application development.
What's new in Visual Studio 2005
What's New in Developing Visual C++ Device Applications
Develop smart device applications using Microsoft Foundation Classes, Active Template Library (ATL), and Windows CE
native APIs. Migrate your eMbedded Visual C++ 4.0 projects.
What's New in Managed Device Projects
New features for managed development include integrated Smartphone support, new controls, anchoring and docking, and
more.
How to: Launch the Device Emulator in Visual Studio
You can run, test, and debug a run-time image using this totally new Device Emulator, built from the ground up to run code
compiled for ARM processors.
Data Access Overview (Managed Device Projects)
Create SQL Mobile databases, alter schemas, and perform other database management tasks, all from the Visual Studio IDE.
Use business objects, SQL Server databases, SQL Mobile databases, or Web services as datasources.
Packaging Device Solutions Overview
Package your application for deployment using a smart device CAB project along with the File System Editor and Registry
Editor.
Switching Platforms in Device Projects
Use single source to target more than one platform, such as Pocket PC and Smartphone.
Remote Tools for Device Projects
Remotely perform programming and debugging tasks on a Windows CE-based device.
Security Overview (Devices)
Sign your files with appropriate certificates and provision devices.
Connection Method Selection
Connect your development computer to a device over USB, Ethernet, 802.11b/g, Bluetooth, serial port, or infrared.
Mobile Developer Center Web Site
Access a central location for smart device project information, including how to get started, code samples, frequently asked
questions, training opportunities, and other resources.
Related Sections
What's New in Visual Studio 2005
What's New in the .NET Compact Framework 2.0
What's New (SQL Server Books Online)
Smart Device Development

Application Development Overview (Devices)


Visual Studio supports two approaches for developing applications for devices.
You can develop mobile Web applications that run on a Web server and are rendered in different formats on a wide
range of browser-equipped mobile devices.
You can develop Windows CE- and Windows Mobile-based rich-client applications that run on the device itself. This latter
approach is what we mean by application development for smart devices.
Smart Device Solutions and Windows CE
To better understand the relationship between Windows CE, Pocket PC, Smartphone, and Windows Mobile™ software, see the
article Mobile Developer Center Editor's Note from the Microsoft Mobile Developer Center.
Version Compatibility
To identify which versions of tools and technologies work together in developing device applications, see
Introduction to Development Tools for Windows Mobile-based Pocket PCs and Smartphones. In Visual Studio 2005 managed
projects, all platforms target version 2.0 of the .NET Compact Framework unless otherwise noted. For example, in the New
Project dialog box, smart device templates are marked with "(1.0)" if they target version 1.0 of the .NET Compact Framework.
Design Guidelines
How you design your device application determines how easily, quickly, and efficiently a user can complete tasks. By
optimizing your application to leverage the capabilities of different devices, you can provide the best user experience by
creating a more usable, consistent, responsive, and accessible application. For detailed design guidelines about specific
interface features, see the software development kit (SDK) for your device.
Device Emulator
The Device Emulator is designed specifically for Visual Studio 2005 device projects. It runs applications compiled for the ARM
instruction set and runs as a user-mode process. Visual Studio now provides a Direct Memory Access (DMA) transport to
communicate with the emulator. Surpassing the traditional TCP/IP transport, the DMA transport is faster, does not rely on
network connectivity or other external factors, and provides deterministic connection and disconnection.
Visual Studio 2005 includes emulator images for Pocket PC 2003 SE, Pocket PC 2003 SE Square, Pocket PC 2003 SE Square
VGA, Pocket PC 2003 VGA, Smartphone 2003 SE, and Smartphone 2003 SE QVGA.
Click Help on the emulator menu bar to view the collection of Help topics supporting the emulator.
To open the emulator, click Tools, click Connect to Device, select the emulator you want to open, and then click Connect.
Note
The Device Emulators support Direct3D and DirectPlay libraries. However, the emulators do not support any form of hardw
are acceleration. Performance of Direct3D and DirectPlay applications running on the emulator will not accurately reflect the
performance of applications running on actual hardware. Furthermore, actual hardware may or may not support hardware a
cceleration. You are strongly encouraged to test Direct3D and DirectPlay applications on actual shipping devices.

Security
The remote connection aspect of device applications introduces additional security issues. For more information, see
Security in Device Projects, Security in the .NET Compact Framework, and Security in Native and .NET Framework Code.
Porting Existing Solutions
See the following for tips on porting and migrating:
Creating and Developing Managed Device Projects
eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard

Device vs. Desktop


You use the same Visual Studio environment that you use when you develop applications for the desktop, but some
differences become apparent when you target devices. For example:
The Visual Studio environment provides additional tools for connecting to and debugging on a device.
Besides choosing a project type and template when you create a project, you must select a device on which to run and
debug the application. The device can be either a physical device connected to the development computer, a networked
device, or a device emulator running on the development computer.
The number and members of classes differ from what is available for developing desktop applications. In managed
projects using the .NET Compact Framework, fewer classes are available for devices, and the complement of classes
typically differs among platforms. The same is true for native projects, where only a subset of Windows APIs, MFC
classes, or ATL components is available. You can determine which classes are available by viewing the documentation, by
using IntelliSense, or by using the Visual Studio Object Browser while your project is active.
As with desktop applications, you can access native code by using platform invoke. The .NET Compact Framework
provides limited support for COM interop. It does not support creating COM objects in managed code or interoperating
with ActiveX controls.
Some language items can differ; for example, not all Visual Basic keywords used for desktop development are supported.
Some code snippets provided in Visual Studio documentation for desktop projects may generate build errors in device
projects.
There are design considerations, such as the form factor of the device, power usage, memory constraints, and other
details, that are not factors for desktop development.

Additional Resources
For more information, visit the Mobile Developer Center.
See Also
Other Resources
Getting Started with Smart Device Projects
Smart Device Development

Device Capabilities and Required Development Tools


This topic has been updated for Visual Studio 2005 SP1.
Visual Studio 2005 supports application development for devices running Windows Mobile Version 5.0, Windows Mobile 2003
and 2003 Second Edition, and Windows CE-based hardware running Windows CE 5.0.
However, many legacy devices exist. This situation can lead to confusion as to what is required by way of development tools,
.NET Compact Framework version, and underlying Windows CE operating system.
Tools Comparison Charts
The following tables provide a snapshot of the variations in smart device hardware, hardware features, and development tools.
These listings can change over time. You can obtain the most up-to-date and complete information by reviewing the technical
article Introduction to Development Tools for Windows Mobile-based Devices in the MSDN Library.
Overview of IDE Capabilities
This table provides an overview of the capabilities of the different IDEs. Column heading abbreviations are as follows:
eVT3C = eMbedded Visual C++ 3.0
eVT3V = eMbedded Visual Basic 3.0
eVC4 = eMbedded Visual C++ 4.0 and service pack 4.0
VS2003 = Visual Studio .NET 2003
VS2005 = Visual Studio 2005
eVT3C eVT3V eVC4 VS2003 VS2005
Code type Native Code X X X

Interpreted Code X

Managed Code X X

Server-side Code X X

Device SDKs Pocket PC 2000 and Pocket PC 2002 X X X

Smartphone 2002 X

Windows Mobile 2003 X X X

Windows Mobile 2003 Second Edition X X X

Windows Mobile 5.0 X


.NET Compact Framework Tools and OS Support
This table provides an overview of which tool versions and which Windows Mobile software versions support .NET Compact
Framework versions 1.0 and 2.0.
Version 1.0 Version 2.0
Tool Visual Studio .NET 2003 X

Visual Studio 2005 X X

Windows Mobile software version Windows Mobile 5.0 In-ROM (1.0 SP3) User installable
Windows Mobile 2003 Second Edition In-ROM (1.0 SP2) User installable (Pocket PC only)

Windows Mobile 2003 In-ROM (1.0 SP1) User installable (Pocket PC only)
Smartphone 2002

Pocket PC 2002 User installable

Pocket PC 2000 User installable


Database Technology Support
The following table has been updated for Visual Studio 2005 SP1.
This table provides an overview of which database technologies are supported by various versions of Windows Mobile.
SQL Server 2005 Compact Edition or SQL Serv SQL CE 2.0 EDB CED ADOCE
er 2005 Mobile Edition B
Windows Mobile 5.0 User Installable User Installable (Pock In-R In-R Unsupported Us
et PC Only) OM OM* er Install

Windows Mobile 2003 S User Installable (Pocket PC Only) User Installable (Pock N/A In-R In-ROM
econd Edition et PC Only) OM

Windows Mobile 2003 User Installable (Pocket PC Only) User Installable (Pock N/A In-R In-ROM
et PC Only) OM

Smartphone 2002 N/A N/A N/A In-R N/A


OM

Pocket PC 2002 N/A User Installable (Pock N/A In-R In-ROM


et PC Only) OM

Pocket PC 2000 N/A User Installable (Pock N/A In-R In-ROM (most d
et PC Only) OM evices)

* In Windows Mobile 5.0, CEDB is In-ROM but deprecated. Developers should use EDB instead.
Notes
Check with the device manufacturer regarding upgrading a device to a later version of Windows CE or Windows Mobile.
Microsoft does not supply upgrades for specific devices to end users.
Visual Studio 2005 Express Editions do not include support for Smart Device projects.
The eMbedded Visual Basic tools are no longer supported. The eMbedded Visual Basic run time is no longer in device
ROM.
eMbedded Visual C++ 4.0 and eMbedded Visual Basic 4.0 can be downloaded from the Mobile Developer Center.
Version 1.0 of .NET Compact Framework, if not already present in ROM, can be installed in RAM on Pocket PC 2000,
2002, 2003, and 2003 SE devices. Version 2.0, if not already present in ROM, can be installed in RAM or persistent store
on Pocket PC 2003, Windows CE 5.0, and Windows Mobile 5.0.
The current version of the Compact Framework is 2.0, available as a RAM install from the Mobile Developer Center.
See Also
Concepts
Updating Projects Created with Previous Tools
Other Resources
Getting Started with Smart Device Projects
Smart Device Development

Hardware and Software Requirements for Smart Device


Projects
The following paragraphs specify requirements for the development computer, the target device, and the connection between
the two.
Development Computer
Selecting Smart Device Programmability (selected by default) when you installed Visual Studio 2005 adds approximately 900
MB of hard disk space usage. If you are not developing Smart Device applications, you can recover this space by uninstalling
Smart Device Programmability. You can do this from the Add or Remove Programs tab in Control Panel by selecting your
Visual Studio installation, clicking Change/Remove, and following the steps.
You need a minimum of 64 MB of additional RAM when you use an emulator in your device projects.
Device
The target device must support the platform you are developing against. Visual Studio 2005 provides support for the Pocket
PC 2003, Smartphone 2003, and Windows CE 5.0 and later platforms.
Approximately 2 MB of RAM are required on the device for the .NET Compact Framework if the Framework has not been
installed in ROM.
Connection
Visual Studio 2005 requires the following:
Hardware
Unless your physical device has wireless connectivity with the development computer enabled, you need a serial or USB cable,
as provided by the device manufacturer, to connect a device to the development computer. Before you can use this connection,
you must set up the development computer and device according to the instructions provided by the device manufacturer.
Using an emulator as your device requires no additional hardware.
Software
Microsoft ActiveSync version 4.0 or later.
See Also
Concepts
Installation and Setup Essentials
Other Resources
Getting Started with Smart Device Projects
Visual Studio Editions
Smart Device Development

Remote Tools for Device Projects


The remote tools listed below were available in embedded Visual C++ 4.0 and are shipped with Visual Studio 2005 to help you
develop and debug device applications.
To launch these standalone tools, click Start on the Windows desktop, point to All Programs, point to Microsoft Visual
Studio 2005, click Visual Studio Remote Tools, and then select one of the remote tools from the menu.
To Use
View and manage the file system on a target device (including exporting and importing) Remote File Viewer

Display information about heap identifiers and flags for each process running on a target device Remote Heap Walker

Display information about each process running on a target device Remote Process Viewer

Display and manage the registry for a target device Remote Registry Editor

Display messages received by windows associated with applications running on a target device Remote Spy

Capture a screen image in bitmap (.bmp) file format from a target device Remote Zoom-in

See Also
Other Resources
Getting Started with Smart Device Projects
Smart Device Development

How to: Optimize Help for Smart Device Development


If you selected Minimum or Custom when you installed the MSDN Library for Visual Studio, you might not have all the Visual
Studio 2005 Help files that are available for smart device developers. Specifically, the Minimum setup does not include the
Mobile and Embedded Development section of the library.
The Mobile and Embedded Development section includes such material as Pocket PC and Smartphone SDK documentation,
Windows CE information, and so on. Topics in that section are often referenced by topics in the Smart Device Development
section of Visual Studio, which is always installed and focuses on using the Visual Studio environment to develop smart device
applications. The following procedures show you how to determine what Help you have installed, how to add Mobile and
Embedded Development Help, and how to filter Help.
To verify whether the Mobile and Embedded Development Help section is installed
Click Pocket PC Developer's Guide.
If the topic is displayed, the Mobile and Embedded Development section is installed.
If the topic is not found, you can add the Mobile and Embedded Development section by following the steps below.
To include Mobile and Embedded Development topics
1. In Windows Control Panel, click Add or Remove Programs.
2. Select MSDN Library for Visual Studio 2005, and then click Change.
3. On the Welcome page of the Setup Wizard, click Next.
4. On the Program Maintenance page, click Modify.
5. On the Custom Setup page, select Mobile and Embedded Development.
6. On the shortcut menu available from the drop-down button, select This feature, and all subfeatures, will be installed
on local hard drive.
7. Click Next.
8. On the Ready to Modify the Program page, click Install.
Filtering Help Topics
Visual Studio provides a Smart Device Development filter for the table of contents and index. When you apply this filter, the
visible topics are reduced to include only documentation considered basic for smart device developers. Most importantly,
applying this filter is an excellent way to display only the smart device subsets of run-time reference topics, including the .NET
Compact Framework and the MFC and ATL libraries.
If you apply a language filter (for example, Visual C#), smart device development topics are excluded from the viewable topics.
For this reason it is better to use either the Smart Device Development filter or no filter at all. Note also that a language filter is
assigned by default if you have logged on to Visual Studio using a language development setting, such as Visual C#
Development Settings.
To set the Smart Device Development filter
1. On the Visual Studio Help menu, click Contents or Index.
2. In the Filtered by box, select Smart Device Development.
To change your development setting
1. On the Visual Studio Tools menu, click Import and Export Settings.
2. On the Welcome page of the wizard, click Reset all settings, and then click Next.
If you are not sure of your options, press F1 to open the Help topic for the wizard.
3. On the Save Current Settings page, select whether to save your current settings, and then click Next.
4. On the Choose a Default Collection of Settings page, select General Development Settings, and then click Finish.
See Also
Tasks
How to: Use the Class Library for the .NET Compact Framework
Concepts
Help Filters for Visual Studio
Other Resources
Getting Started with Smart Device Projects
Smart Device Development

How to: Launch the Device Emulator in Visual Studio


The Device Emulator can serve as a substitute for a physical device during much of the development cycle of a smart device
project. The Device Emulator supports many options, such as specifying RAM size, but not all SDKs support all options. Check
your SDK documentation for details.
For more information, launch the Device Emulator and click Help.
To launch the Device Emulator using the Connect to Device dialog box
1. On the Visual Studio Tools menu, click Connect to Device.
2. In the Connect to Device dialog box, select an emulator from the Devices box, and then click Connect.
To launch the Device Emulator using the Device Emulator Manager
1. On the Visual Studio Tools menu, click Device Emulator Manager.
2. In the Device Emulator Manager window, right-click the emulator you want to launch.
3. On the shortcut menu, click Connect.
See Also
Other Resources
Getting Started with Smart Device Projects
Smart Device Development

Updating Projects Created with Previous Tools


Microsoft Visual Studio 2005 provides powerful development tools for the smart device developer. Programmers using C#
and Visual Basic can now take advantage of the improved tools offered by Visual Studio 2005, and it is now possible to create
a C++ project for a Pocket PC, Smartphone or Windows CE device using the same development environment as is used to
create desktop applications.
The improvements to the Visual Studio 2005 development environment, include:
C# source code refactoring tools. For more information, see Refactoring.
Improved debugging. For more information, see Debugging Device Projects.
Code snippets for C# and Visual Basic. For more information, see Creating and Using IntelliSense Code Snippets.
Improved deployment tools. For more information, see Packaging Device Solutions Overview.
Improved smart device emulators. For more information, see How to: Launch the Device Emulator in Visual Studio.
Migrating Projects from eMbedded Visual C++ to Visual Studio 2005
You can migrate eMbedded Visual C++ projects using a migration wizard. For more information, see
eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard.
Migrating Projects from eMbedded Visual Basic to Visual Studio 2005
Projects created in eMbedded Visual Basic (eVB) are not automatically converted to Visual Studio 2005 projects. Instead, you
must add the existing source and resource files to a new Visual Basic Smart Device project created in Visual Studio 2005.
Note
Windows Mobile 2003 devices do not contain the eMbedded Visual Basic runtimes in ROM, and although the runtimes may
be downloaded to the device as a RAM install, this configuration is not supported.

For more information on using Visual Studio 2005 to convert an eVB project, see the following topics:
Migrating eVB File Controls to Visual Basic .NET
Migrating eVB Forms to Visual Basic .NET
Migrating Managed Projects from Visual Studio .NET 2003 to Visual Studio 2005
Visual C# and Visual Basic smart device projects developed in Visual Studio .NET 2003 can be imported into Visual Studio
2005. The Visual Studio Conversion Wizard makes any required changes to the projects.
Updating Projects from 2002 Devices to 2003 Devices
For more information about updating projects to Windows Mobile 2003 from Windows Mobile 2000, see
Windows Mobile Platform Migration FAQ for Developers.
See Also
Concepts
Device Capabilities and Required Development Tools
Other Resources
Getting Started with Smart Device Projects
Migrating to the eVC 4.0 Environment
Smart Device Development

How Do I in Smart Device Development


This topic has been updated for Visual Studio 2005 SP1.
Visual Studio 2005 offers rich, integrated support for developing software that runs on Windows CE- and Windows Mobile-
based smart devices such as Pocket PCs and Smartphones. You can use Visual C# or Visual Basic to write managed
applications that run on the .NET Compact Framework, or you can write native applications using Visual C++. Whichever
language you choose, you use the same code editor, designers, and debugger interface as you would when you develop for the
PC. Simply select from one of the Smart Device Project templates available for the language of your choice, and begin coding.
Visual Studio also provides emulators, so that you can run and debug your code on your development computer without the
need for a physical device.
Getting Started (How Do I in Smart Devices)
Windows Forms applications… Launch Device Emulator… Which tools support which versions… Select a development
language… Use Help filters… more…
Device Connections (How Do I in Smart Devices)
Virtual PC sessions… DMA… Bluetooth… No ActiveSync… Troubleshooting… more…
Visual Basic and Visual C# (How Do I in Smart Devices)
Create projects… Share source… Change platforms… Code snippets… Change default target… more…
Visual C++ (How Do I in Smart Devices)
Create C++ device project… Migrate eMbedded Visual C++… Add SQL Server Mobile Edition or SQL Server Compact
Edition… Develop multiplatform solutions… Create MFC ActiveX host… more…
Debugging (How Do I in Smart Devices)
Attach to processes… Debug mixed solutions… Change device registry… more…
Data (How Do I in Smart Devices)
Create and manage databases… Add data sources to projects… Build queries… Process master-detail relationships… Produce
ResultSets or DataSets… more…
Packaging (How Do I in Smart Devices)
Create cab project… Create shortcuts… Edit device registry… more…
Security (How Do I in Smart Device Development)
Import certificates… Query for security model… Sign files… Provision devices… more…
See Also
Other Resources
Smart Device Development
Smart Device Development

Getting Started (How Do I in Smart Devices)


This page links to Help on common issues for getting started with smart device application development.
What's New in Smart Device Projects
Describes new or enhanced features for device application development in Visual Studio 2005.
Device Capabilities and Required Development Tools
Describes the various versions and releases of smart devices and the tools needed to support each.
Remote Tools for Device Projects
Lists special tools used for device application development and provides links to detailed Help topics for each.
How to: Optimize Help for Smart Device Development
Describes how best to use Help for device projects, including the use of filters.
How to: Launch the Device Emulator in Visual Studio
Describes how to open this regularly used tool that emulates a physical device.
Updating Projects Created with Previous Tools
Describes how to port projects developed with earlier versions and tools.
Selecting a Development Language
Compares Visual Basic, Visual C#, and Visual C++ as development languages for device projects.
Walkthrough: Creating Windows Forms Applications for a Device
Provides step-by-step instructions for developing a Windows Forms application and running it on the Device Emulator.
See Also
Concepts
How Do I in Smart Device Development
Getting Started with Visual Studio
Other Resources
Integrated Development Environment for Visual Studio
Smart Device Development

Device Connections (How Do I in Smart Devices)


This page links to help on common device connection tasks.
How to: Connect to the Device Emulator From a Virtual PC Session
Describes the technique for connecting in the absence of TCP/IP.
How to: Access the Smartphone Emulator File System
Describes how to access the file system of the Smartphone emulator, which does not have its own file viewer.
How to: Connect Using Bluetooth
Describes how to connect using Bluetooth.
How to: Connect Using IR
Describes how to connect using Infrared.
How to: Connect to Windows CE Device Without ActiveSync
Describes the steps you take to connect to a device when ActiveSync services are not available.
How to: Access Development Computer Files from the Emulator
Describes how to use a shared folder to access development computer files from the emulator.
How to: Set Connection Options (Devices)
Describes where to find the common dialog boxes for setting connection options.
See Also
Tasks
Connectivity Troubleshooting (Devices)
Concepts
How Do I in Smart Device Development
Connection Method Selection
Smart Device Development

Visual Basic and Visual C# (How Do I in Smart Devices)


This page links to help on common development tasks with the .NET Compact Framework.
How to: Create Device Applications Using Visual Basic or Visual C#
Describes how to create device applications, and how the process differs from creating desktop applications.
How to: Share Source Code Across Platforms (Devices)
Describes using compiler constants to share the same source code across different platforms.
How to: Change Platforms in Device Projects
Describes how to change back and forth between platforms in the same project.
How to: Upgrade Projects to Later .NET Compact Framework Versions
Describes how to upgrade the platform of an existing project if a later version of the platform is installed.
Managing Code Snippets in Device Projects
Describes using snippets that pertain exclusively to device projects.
How to: Verify Platform Support for Code in Device Projects
Describes how to ensure that your code is supported by the target platform.
How to: Handle HardwareButton Events (Devices)
Describes how to override the application keys on a Pocket PC.
How to: Change the Orientation and Resolution of Forms (Devices)
Describes how to change orientation and resolution if the defaults are incorrect or lacking.
How to: Change the Default Device (Managed Projects)
Describes how to change the target device during project development.
How to: Optimize Help for Smart Device Development
Describes how to use the Smart Device Help filter to show only those .NET Framework elements supported for device
application development.
See Also
Reference
Data (How Do I in Smart Devices)
Concepts
How Do I in Smart Device Development
.NET Compact Framework How-To Topics
Other Resources
Programming for Devices Using the .NET Compact Framework
.NET Compact Framework
Data in Managed Device Projects
Smart Device Development

Visual C++ (How Do I in Smart Devices)


This page links to Help on common smart device C++ tasks.
In General
Device Support for Desktop Projects
Provides a list of relevant topics that help you target multiple platforms, including the desktop.
Resource Editing in Native Device Projects
Explains the similarities and differences between Resource editors for devices versus desktop.
How to: Add a Database to a Native Device Project
Explains how to develop C++ smart device applications that include a SQL Server Mobile Edition or SQL Server Compact
Edition database.
How to: Specify the Remote Path for Primary Project Output
Explains how to set the remote path.
How to: Change the Default Device (Native Projects)
Explains how to change the default target in a C++ device project.
Creating/Migrating
How to: Create a New Visual C++ Device Project
Describes creating C++ applications for devices versus applications that run on the desktop.
How to: Create a Multiplatform Device project (Visual C++)
Describes how to target multiple devices from the same C++ development project.
Known Issues With Porting From eVC
Describes how to migrate eMbedded Visual C++ 4.0 projects to Visual Studio.
MFC
Walkthrough: Creating a Multiplatform MFC Application for Smart Devices
Focuses on targeting multiple platforms.
Walkthrough: Creating an MFC Multiplatform ActiveX Control for Smart Devices
Focuses on creating an ActiveX control using MFC for devices.
How to: Find Help for MFC Classes and Methods Supported for Devices
Describes how to use the Smart Device Help filter to show only those MFC elements supported for device projects.
ATL
Walkthrough: Creating an ATL Multiplatform ActiveX Control for Smart Devices
Focuses on creating an ActiveX control using ATL for devices.
How to: Find Help for ATL Classes and Methods Supported for Devices
Describes how to use the Smart Device Help filter to show only those ATL elements supported for device projects.
See Also
Concepts
How Do I in Smart Device Development
Other Resources
Visual C++
Smart Device Development

Debugging (How Do I in Smart Devices)


This page links to help on smart device debugging tasks and their differences from similar tasks for desktop projects.
Differences Between Device And Desktop Debuggers
Lists features not supported or supported in a limited way, and describes additions to cordbg.exe for device debugging.
How to: Attach to Managed Device Processes
Describes how to attach to a process that is already running without the debugger.
How to: Change Device Registry Settings
Describes how to use the Remote Registry Editor to edit registry settings on the device.
Walkthrough: Debugging a Solution That Includes Both Managed and Native Code
Describes how to debug these mixed solutions.
See Also
Concepts
How Do I in Smart Device Development
Other Resources
Debugging in Visual Studio
Smart Device Development

Data (How Do I in Smart Devices)


This topic has been updated for Visual Studio 2005 SP1.
This page links to Help on common smart device data-handling tasks.
In General
How to: Generate SqlCeResultSet Code (Devices)
Describes how to generate ResultSets instead of DataSets.
How to: Change the Design-Time Connection String (Devices)
Describes changing the string that Visual Studio uses to connect to a SQL Server Mobile Edition or SQL Server Compact
Edition database at design time.
How to: Change the Run-Time Connection String (Devices)
Describes changing the string that the application uses to connect to a SQL Server Mobile Edition or SQL Server Compact
Edition database at run time.
How to: Add Navigation Buttons (Devices)
Describes an alternative to the DataNavigator class, which is not supported in the .NET Compact Framework.
How to: Persist Data Changes to the Database (Devices)
Describes how to apply changes in the DataSet back to the database.
Adding Data Sources
How to: Create a Database (Devices)
Describes how to use the Visual Studio environment to create a SQL Server Mobile Edition or SQL Server Compact Edition
database, inside or outside a project.
How to: Add a Database to a Device Project
Describes adding a SQL Server Mobile Edition or SQL Server Compact Edition database, available in Server Explorer, as a
data source for a Visual Basic or Visual C# project.
How to: Add a SQL Server Database as a Data Source (Devices)
Describes how to add a SQL Server database as a data source for a Visual Basic or Visual C# project.
How to: Add a Business Object as a Data Source (Devices)
Describes how to add a business object as a data source for a Visual Basic or Visual C# project.
How to: Add a Web Service as a Data Source (Devices)
Describes how to add a Web service as a data source for a Visual Basic or Visual C# project.
Managing Data Sources
How to: Manage Tables in a Database (Devices)
Describes how to add and remove tables, and how to edit an existing table schema.
How to: Manage Columns in a Database (Devices)
Describes how to add and remove columns and to edit their properties.
How to: Manage Indexes in a Database (Devices)
Describes how to add and remove indexes, and how to change their sort-order property.
How to: Manage Passwords for Databases (Devices)
Describes how to set a password for a new SQL Server Mobile Edition or SQL Server Compact Edition database and how to
change a password for an existing database.
How to: Shrink and Repair a Database (Devices)
Describes how to shrink and repair SQL Server Mobile Edition or SQL Server Compact Edition databases.
Building Queries
How to: Create Parameterized Queries (Devices)
Describes how to create parameterized queries.
Walkthrough: A Parameterized Query Application
Provides step-by-step instructions for an end-to-end project that includes building a parameterized query.
Processing Master-Detail Relationships
How to: Create Master-Detail Applications (Devices)
Describes how to implement a master-detail relationship.
Walkthrough: A Database Master-Detail Application
Provides step-by-step instructions for an end-to-end project that includes creating and running a master-detail application.
Viewing and Editing Data
How to: Preview Data in a Database (Devices)
Describes several options for viewing data in a database.
How to: Generate Summary and Edit Views for Data Applications (Devices)
Describes how to use data forms to view and edit single rows of data in a datagrid.
See Also
Concepts
How Do I in Smart Device Development
Other Resources
Data in Managed Device Projects
Overview of SQL Server 2005 Mobile Edition
Accessing Data (Visual Studio)
Smart Device Development

Packaging (How Do I in Smart Devices)


This page links to help on packaging and setup tasks for device projects.
Walkthrough: Packaging a Smart Device Solution for Deployment
Provides step-by-step instructions for packaging an application and its resources.
See Also
Concepts
How Do I in Smart Device Development
IDE Features Supporting Device Application Packaging
Packaging Device Solutions Overview
Smart Device Development

Security (How Do I in Smart Device Development)


This page links to help on common smart device security tasks.
In General
How to: Import and Apply Certificates in Device Projects
Describes the effective use of the Select Certificate dialog box for signing device projects.
How to: Launch Signtool.exe as a Post-Build Event (Devices)
Describes how to sign a project when post-build events have changed the original binaries.
How to: Query a Device For Its Security Model
Describes how to determine what certificates are already installed in the device certificate store.
Signing
How to: Sign a Visual Basic or Visual C# Application (Devices)
Lists the steps for signing an application written against the .NET Compact Framework.
How to: Sign a Visual Basic or Visual C# Assembly (Devices)
Lists the steps for signing project assemblies.
How to: Sign the Project Output in a Visual C++ Project (Devices)
Lists the steps for signing Visual C++ project output.
How to: Sign a CAB File (Devices)
Lists the steps for signing a device CAB project.
Provisioning
How to: Provision a Device in a Visual Basic or Visual C# Project
List the steps for adding digital certificates to the device store in managed projects.
How to: Provision a Device in a Visual C++ Project
List the steps for adding digital certificates to the device store in native projects.
How to: Provision a Device with a Security Model
Describes using RapiConfig.exe to provision a device with a security model.
See Also
Concepts
How Do I in Smart Device Development
Other Resources
Security in Native and .NET Framework Code
Smart Device Development

Design Considerations for Smart Device Development


Visual Studio 2005 provides three different programming languages and many different project types for smart device
development. This section contains a summary of these project types, along with some guidance on selecting the more
appropriate language for your project.
In This Section
Choosing a Smart Device Project Type
Provides an overview of the many different smart device projects available within Visual Studio 2005, and the different
hardware platforms they support.
Selecting a Development Language
Provides guidance on choosing the best development language for your project.
Customizing Skins (Devices)
Describes skins in smart device projects and how you can customize them.
See Also
Other Resources
Smart Device Development
Smart Device Programmability
Mobile Developer Center
Smart Device Development

Choosing a Smart Device Project Type


Visual Studio 2005 provides the following project templates for creating new Smart Device projects. Templates marked with "
(1.0)" indicate projects based on version 1.0 of the .NET Compact Framework. Remaining templates refer to projects based on
version 2.0.
Visual C# and Visual Basic
Template Name Supported Devices Comments
Device Application Pocket PC 2003, Windows CE A project for creating a .NET Compact Framework 2.0 Windows Forms a
5.0 pplication.

Control Library Pocket PC 2003, Windows CE A project for creating .NET Compact Framework 2.0 controls.
5.0

Class Library Pocket PC 2003, Windows CE A project for creating a .NET Compact Framework 2.0 class library (DLL).
5.0

Console Application Pocket PC 2003, Windows CE A project for creating a .NET Compact Framework 2.0 non-graphical app
5.0 lication.

Empty Project Pocket PC 2003, Windows CE An empty project for creating a .NET Compact Framework 2.0 applicatio
5.0 n.

Device Application (1. Pocket PC 2003, Smartphone A project for creating a .NET Compact Framework 1.0 Windows Forms a
0) 2003 pplication.

Class Library (1.0) Pocket PC 2003, Smartphone A project for creating a .NET Compact Framework 1.0 class library (DLL).
2003

Console Application ( Pocket PC 2003, Smartphone A project for creating a .NET Compact Framework 1.0 non-graphical app
1.0) 2003 lication.

Empty Project (1.0) Pocket PC 2003, Smartphone An empty project for creating a .NET Compact Framework 1.0 applicatio
2003 n.

Visual C++
Template Name Supported Devices Comments
ATL Smart Device Projec Pocket PC 2003, Smartphone 2003, A project for creating an application using the Active Template L
t Windows CE 5.0 ibrary.

MFC Smart Device Proje Pocket PC 2003, Smartphone 2003, A project for creating an application using the Microsoft Founda
ct Windows CE 5.0 tion Class Library.

MFC Smart Device Activ Pocket PC 2003, Smartphone 2003, A project for creating an ActiveX control using the Microsoft Fo
eX Control Windows CE 5.0 undation Class Library.

MFC Smart Device DLL Pocket PC 2003, Smartphone 2003, A project for creating a dynamic-link library using the Microsoft
Windows CE 5.0 Foundation Class Library.

Win32 Project Pocket PC 2003, Smartphone 2003, A project for creating a Win32 application.
Windows CE 5.0

Other Project Types


Template Name Supported Devices Comments
Smart Device CAB Pr Pocket PC 2003, Smartphone 2003, Window A project for creating a CAB file to deploy smart device ap
oject s CE 5.0 plications.

See Also
Concepts
Selecting a Development Language
Smart Device Development

Selecting a Development Language


When developing an application, control or library for deployment on a Smart Device, there are three programming languages
to choose from: Visual C#, Visual Basic, and Visual C++.
Visual C#
C# is a modern, object-orientated language. Its garbage collection features and support for the .NET Compact Framework
classes make it an ideal language for developing reliable and secure mobile applications. Visual C# for Smart Devices includes
a large number of controls for quickly creating a graphical user interface (GUI), and the Compact Framework classes support
features such as GDI+, XML, and Web Services. Visual C# can also call native Windows CE functions for situations not
supported by the .NET Compact Framework.
For more information about developing with Visual C# and accessing native Windows CE functions, see:
Getting Started with Visual Studio .NET and the Microsoft .NET Compact Framework
C# Reference
An Introduction to P/Invoke and Marshaling on the Microsoft .NET Compact Framework
Creating a P/Invoke Library
Advanced P/Invoke on the Microsoft .NET Compact Framework
Visual Basic
Visual Basic for Smart Devices is a full implementation of Visual Basic, and is considerably more powerful than the previous
development tool, eMbedded Visual Basic. Visual Basic greatly simplifies the task of porting a desktop application to a mobile
device, or quickly creating a rich-client application. As with Visual C#, Visual Basic makes use of the .NET Compact Framework.
Developers already familiar with Visual Basic will be able to port existing applications or create new ones very quickly. As with
C#, Visual Basic can access native Windows CE functions.
For more information on developing in Visual Basic, see:
Getting Started with Visual Studio .NET and the Microsoft .NET Compact Framework
Visual Basic Reference
Visual C++
Visual C++ is the preferred development language for Smart Devices when performance is critical, or when developing
system-level applications, device drivers or Today or Home screen plug-ins. Visual C++ does not support the .NET Compact
Framework, but instead provides a subset of the Win32 API set. It is possible for applications written in managed C# or Visual
Basic code to access C++ code contained in DLLs by means of Interop.
For more information on developing in Visual C++, see:
C/C++ Languages
See Also
Other Resources
Getting Started with Smart Device Projects
Smart Device Development

Customizing Skins (Devices)


A skin is a graphic that surrounds the rectangular form, the viewport, of an application in the Device Emulator or Visual Studio
Designer. When you use a skin during application development, you can better visualize how your application looks on a real
device. You can use the same skins in Visual Studio designers and the Device Emulator.
Besides providing visual enhancement, skins can provide functionality, such as the processing of mouse events for hardware
buttons and softkeys.
Note
If the skin files installed with Visual Studio become corrupt, you can reinstall them by repairing your Visual Studio 2005 insta
llation. For more information, see How to: Register Visual Studio.

In This Section
Skin Technology (Devices)
Describes the XML Skin Definition File and graphic file requirements for skins.
How to: Create Skin Files (Devices)
Describes the steps for creating a simple skin.
How to: Change Visual Characteristics of Skins (Devices)
Describes modifications you can make to the Skin Definition File to affect the title bar of the emulator, the location and
dimension of the viewport, and whether or not the skin appears in a frame, or transparency.
How to: Process Mouse Events (Devices)
Describes using color mapping to specify areas of the skin, also known as hotspots, that can respond to mouse events.
How to: Expose Tooltips (Devices)
Describes how to provide ToolTips for skin hotspots.
How to: Use Skins with the Device Emulator
Describes options available in the Device Emulator user interface, including the choice of a skin, how to save the skin with an
OS image, and how to show or hide ToolTips.
How to: Use Skins with Visual Studio 2005 (Devices)
Describes options available in the Visual Studio user interface, including setting defaults, specifying resolution, enabling
rotation, and other properties.
Skin Definition File Details (Devices)
Describes and gives sample values for the individual elements, both required and optional, that appear in a Skin Definition
File.
Skin Definition File Example (Devices)
Presents a complete Skin Definition File.
See Also
Other Resources
Design Considerations for Smart Device Development
Mobile Developer Center
Smart Device Development

Skin Technology (Devices)


A skin consists of up to three bitmap (BMP) or Portable Network Graphics (PNG) files and a single Skin Definition File that
contains Extensible Markup Language (XML). The Skin Definition File and the associated BMP or PNG files must be in the same
directory.
The XML file describes how the skin works and where to find the BMP or PNG files. The XML file also defines button
actions based on the color code shown in the mapping file. For more information, see
Skin Definition File Example (Devices).
One BMP or PNG file, referred to as a normal art file, shows the default appearance of the emulator skin. The normal art
file is the only file required for a skin.
A second, optional, BMP or PNG file, referred to as a down art file, shows the appearance of the skin with all buttons
pressed.
A third, optional, BMP or PNG file, referred to as a mapping file, shows a color code for each button on the skin. The color code
for each button is represented in the mapping file as a single-color area that completely covers the button. Users of the skin do
not see the colors that you use as codes in the mapping file.
See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

How to: Create Skin Files (Devices)


You can create new skins or customize existing skins using the same techniques. OEMs use high-performance graphic tools to
design and develop the graphic files required for skins. Nevertheless, you can achieve satisfactory results using simpler tools—
even Microsoft Paint. You can write the Skin Definition File (an XML file) using as simple a tool as Microsoft Notepad.
To customize an existing skin, save the existing skin files under new names and edit them. When you want to use new skins,
ensure that all the files for a skin, that is, the Skin Definition File and the graphic files that accompany it, share the same
directory.
The following steps describe how to create a new skin. For more information, see Skin Technology (Devices).
To create a new skin
1. Create a bitmap (BMP) or Portable Network Graphics (PNG) file that shows the default appearance of the skin.
2. Create a BMP or PNG file that shows the appearance of the skin with all buttons pressed.
3. Create a BMP or PNG file that shows the area of each button filled with a single unique color.
These button colors represent hotspots and are used in handling mouse events. If you want the appearance of each
button to change independently of the other buttons on the skin, use a different color to fill the area of each button. For
more information, see How to: Process Mouse Events (Devices).
Note
For best visibility, do not use white or black to fill these areas.

4. Create a Skin Definition File.


For more information, see Skin Definition File Details (Devices) and Skin Definition File Example (Devices).
5. Save the three BMP or PNG files and the XML file to a single directory.
See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

How to: Change Visual Characteristics of Skins (Devices)


You can change a number of the visual characteristics of the skin.
Note
The term viewport describes the window area within the skin where the user interface of an application appears.

Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To change the wording in the title bar of the Device Emulator


In the Skin Definition File, reword the titleBar element. For example:

titlebar = "My Device"

To change the location of the viewport within the skin


In the Skin Definition File, change the value assigned the x and y axes.
For example, the default Pocket PC 2003 Second Edition schema lists displayPosX="51" and displayPosY="47". When
you increase the displayPosX value, you move the viewport to the right. When you increase the displayPoxY value, you
move the viewport downward.
To change the height and width of the viewport
In the Skin Definition File, change the value assigned to the displayWidth and displayHeight elements.
For example, the default Pocket PC 2003 Second Edition schema lists displayWidth="240" and displayHeight="320".
When you increase the value of displayWidth, the horizontal dimension of the viewport increases to the right. When you
increase the value of displayHeight, the vertical dimension of the viewport increases downward.

To change the color depth of the viewport


In the Skin Definition File, change the value assigned to the displayDepth element.
For example, the default Pocket PC 2003 Second Edition schema lists displayDepth="16".
Note
Color depth, also called bit depth, represents the number of bits available to define a color for each pixel. Smart device
skins typically have a color depth of 16.

To implement background transparency


Set the lower left pixel of the Up or Normal graphic file to the transparent color. Skins that Microsoft currently ships for
Smartphone and Pocket PC use the color value FEFFFF for this purpose.
Note
Use this technique to make skins frameless. In other words, the Device Emulator and the graphic in the Visual Studio de
signer will be bounded by the visual elements of the skin, and not appear in a rectangle whose background color is pro
bably not the same as that of the window in which the skin appears.
See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

How to: Process Mouse Events (Devices)


Besides using skins to provide a visual replica of a real device, you can also use them to process mouse events, making the
emulation of real devices even more realistic.
By assigning a unique color (mappingColor) to each button area in the Skin Definition File, you can specify what happens when
you hover, click, or press and hold the cursor over any button on the skin. The color is not visible in the user interface. It serves
only to provide a unique indicator for event handling in the Device Emulator and Visual Studio designers.
For example, if you use your graphic tool to view the file PocketPC_2003_Mask.PNG, installed by default at \Program
Files\Microsoft Visual Studio 8\SmartDevices\Skins\PocketPC_2003\PocketPC_2003\1033, you see that each button appears
with a distinct color.
To process an onClick event
1. In a button tag in the Skin Definition File, assign a color value to mappingColor.
The following example is from the Pocket PC 2003 Skin Definition File:

<button
toolTip="Soft Key 1"
onClick="DOWN:0x5b 0x70 UP:0x5b"
mappingColor="0xF26C4F"
/>

2. Assign keystrokes to the onClick event.


For more information, see the following steps to associate a button with a keystroke.
If you click the button that has the color 0xF26C4F, the onClick event specified in this button section will be handled. The
keystrokes specified in the Skin Definition File are passed to the engine.
To process an onPressAndHold event
1. In a button tag in the Skin Definition File, assign a color value to mappingColor.
The following example is from the Pocket PC 2003 Skin Definition File:

<button
toolTip="Power"
onPressAndHold="0x75"
mappingColor="0xED145B"
/>

2. Assign a keystroke to the onPressAndHold event.


For more information, see the following steps to associate a button with a keystroke.
If you click any button that has the color 0xED145B, the onPressAndHold event specified in this button section is handled.

To associate a button with a keystroke


Use either the keyboard scan code, as in the previous examples or a set of predefined constants, such as Key_Down.
For more information, see Emulator Skin XML Schema in the MSDN Online Library.
See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

How to: Expose Tooltips (Devices)


Each button tag in the Skin Definition File can include a line for ToolTips. Hovering over a hotspot on the skin pops up a
ToolTip, if one has been assigned, that shows information about the feature represented by the hotspot. The hotspot is typically
a button, for example, Soft Key 1. The ToolTip shows the name of the button as specified in the ToolTip element in the Skin
Definition File.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To expose ToolTips on the skin


1. In a button tag in the Skin Definition File, assign a color value to mappingColor.
The following example is from the Pocket PC 2003 Skin Definition File:

<button
toolTip="Soft Key 1"
onClick="DOWN:0x5b 0x70 UP:0x5b"
mappingColor="0xF26C4F"
/>

2. Assign a text string for toolTip.


If you hover over the button that has the color 0xF26C4F, a ToolTip with the text Soft Key 1 is displayed.
See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

How to: Use Skins with the Device Emulator


The Microsoft Device Emulator provides a dialog box for selecting a Skin Definition File, and also provides skin options if you
choose to launch the emulator from the command line.
The graphical interface for selecting a Skin Definition File for the emulator is available from the Display tab in the Emulator
Properties dialog box.
Some options are available only when you launch the Device Emulator from the command line. For more information, click
Help in the Device Emulator.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To open the Device Emulator


1. On the Visual Studio Tools menu, click Connect to Device.
2. In the Connect to Device dialog box, select an emulator, and then click Connect.
To open the Emulator Properties dialog box from the Device Emulator
On the Device Emulator File menu, click Configure, and then click the Display tab.
To open the Emulator Properties dialog box from Visual Studio 2005
1. On the Visual Studio Tools menu, click Options.
2. Expand the Device Tools node, and then click Devices.
3. In the Devices box, select an emulator, and then click Properties.
4. In the <EmulatorName> Emulator Properties dialog box, click Emulator Options, and then click the Display tab.
To apply a skin to the Device Emulator
Use the Skin box on the Display tab in the Emulator Properties dialog box.
-or-
Use the /skin switch when you launch the emulator from the command line.
-or-
Apply a skin that you previously saved with an emulator OS image by launching from the command line with the /s
switch.
To save a skin file with an emulator OS image
On the File menu of the Device Emulator, click Save State and Exit.
A saved-state file, including the skin, is generated and saved. For more information, look for Saved-State Files in the
emulator's Help system.
To show or hide ToolTips
On the Display tab of the Emulator Properties dialog box, select or clear Enable tooltips.
Note
Showing ToolTips is available only when ToolTips have been specified in the Skin Definition File.
See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

How to: Use Skins with Visual Studio 2005 (Devices)


Visual Studio 2005, except Express editions, offers a number of user interface elements to help you manage skins in the
designers. These features are typically found in the Form Factors Options and Form Factor Properties dialog boxes.
Note
As a convenience, you can use the Visual Studio environment to access skin properties for the emulator as well as for the Vis
ual Studio designers, without having to open the Device Emulator. For more information, see the section"To access skin prop
erties for the Device Emulator."

Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To open the Form Factors Options dialog box


1. On the Visual Studio Tools menu, click Options.
2. Expand Device Tools, and then click Form Factors.
To open the Form Factor Properties dialog box
In the Form Factors Options dialog box, select a Form factor, and then click Properties.
To select a skin for the designer
1. In the Form Factor Properties dialog box, use the Skin box to select the XML file that represents the Skin Definition File
you want to use in the designer.
A graphic representation of the skin appears in the panel to the left of the Skin box.
2. Click OK to return to the Form Factors Options dialog box.
3. Click Save As to store this new arrangement under a new name.
The newly named Form factor includes the customized skin.
Note
If you have a project open, you need to close the form and reopen it for the change to take effect.

To set a particular skin as the default skin


In the Form Factors Options dialog box, use the Default form factor box to select the form factor you want to set as
the default.
The default you select becomes the default form factor for new projects.
Note
You can set this default value only when you have a project open.

To enable rotation support


In the Form Factor Properties dialog box, select Enable rotation support.

To set horizontal and vertical resolution


In the Form Factor Properties dialog box, enter values for pixels per inch for both horizontal and vertical resolution.
To hide or show the skin
In the Form Factor Properties dialog box, clear or select Show skin.
If you select Show skin, the skin determines height, width, and color depth, so these properties appear dimmed and are
unavailable for change.
To set the height and width of the viewport
In the Form Factor Properties dialog box, use the Screen width and Screen height boxes to enter values for the
number of pixels.
If you select Show skin, the skin sets these properties, so they appear dimmed and are unavailable for change.
To set the color depth
In the Form Factor Properties dialog box, use the Color depth box to select the number of bits per pixel.
If you have selected Show skin, the skin sets this property, so it appears dimmed and is unavailable for change.
To hide ToolTips
Remove the ToolTip elements from the Skin Definition File.
Note
Visual Studio provides no user interface option for hiding ToolTips in the designer if the Skin Definition File has already
defined them. Distinguish this ToolTip behavior from that of skins applied to the Device Emulator, where ToolTips can b
e enabled or disabled. For more information, see How to: Use Skins with the Device Emulator.

To access skin properties for the Device Emulator


1. On the Visual Studio Tools menu, click Options.
2. Expand the Device Tools node, and then click Devices.
3. In the Devices box, select an emulator, and then click Properties.
4. In the <EmulatorName> Emulator Properties dialog box, click Emulator Options, and then select the Display tab.
This is the same dialog box that appears when you click Configure on the Device Emulator File menu. For more
information, see How to: Use Skins with the Device Emulator.
See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

Skin Definition File Details (Devices)


The following table describes sample elements and values for a Skin Definition File for devices. For more information, see
Skin Definition File Example (Devices).
Elements
XML Tags and Ele Description
ments
<skin> tag Encapsulates the schema for an emulator skin. You can use only one <skin> tag in each XML file.

<view> tag Contains the schema for an emulator skin. You can use only one <view> tag per <skin> tag.

titleBar ="My Emu Specifies the title of the window for the emulator.
lator skin" title ba
r element

displayPosX="10" a Specifies the position at which to locate the window containing the display for the emulator within the wi
nd displayPosY="14 ndow for the emulator skin. To make the display not visible, select coordinates that are off-screen.
9" elements

displayWidth="272 Specifies the width and height of the display for the emulator. For width, choose an integer between 80 a
" and displayHeigh nd 1024 that is divisible by 8. For height, choose an integer between 64 and 768.
t="224" elements

displayDepth="8" e Specifies the color depth of the display for the emulator. For color depth, choose 8, 16 or 32.
lement

normalImage="up.b Specifies the normal art file for the emulator skin, which is required. The normal art file specifies the size
mp" element of the window for the emulator, and the appearance of the emulator skin.

mappingImage="map Specifies the mapping file for the emulator skin. The mapping file is an optional file that defines the regio
.bmp" element ns occupied by the buttons in the emulator skin.

downImage="down.b Specifies the down art file for the emulator skin. The down art file is an optional file that specifies the app
mp" element earance of the buttons on the emulator skin when the buttons are pressed.

<button> tag Contains the description of a button on the emulator skin.

mappingColor="0x0 Specifies the RGB color in the mapping file to use for the button. All pixels having this color in the mappi
0FF00" element ng image represent the area in the emulator skin that you can click for this button. This area behaves as a
mask through which the down art file is displayed when you press the button.

toolTip="This is Optional. Specifies the text to appear when you move the pointer over the button.
my ToolTip." eleme
nt

onClick=" DOWN:Ke Optional. Specifies keyboard key presses to be passed to the engine when you press a button. Use hexad
y_LeftShift
ecimal or integer values corresponding to a raw keyboard scan code.
Key_Z
0x00000015
UP: Key_LeftShift
Key_A"
<button Specifies keyboard events to repeat while a button on the emulator skin is being pressed. If KeyEvent is s
toolTip="Soft Key pecified, the designer generates code for the button. If Comment is specified, it is added to the generated c
1" ode as a comment. A ToolTip is used as a comment by default.
onPressAndHold="0 This feature supports all key codes except for the SHUTDOWN key code.
x3B"
mappingColor="0xF
26C4F"
KeyEvent="F1"
Comment="Not hand
led when menu
is present."

See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

Skin Definition File Example (Devices)


The following code is the Skin Definition File, PocketPC_2003_Skin.xml, for the Pocket PC 2003 skin in portrait format. Visual
Studio 2005, except Express editions, installs this and other skin files by default at \Program Files\Microsoft Visual Studio
8\SmartDevices\Skins.
You can use the same skin files for the Device Emulator and for the Visual Studio designers. For more information, see
Skin Definition File Details (Devices).
Code
<?xml version="1.0" encoding="UTF-8" ?>
<skin>
<view
titleBar ="Pocket PC 2003 Second Edition"
displayPosX="51"
displayPosY="47"
displayWidth="240"
displayHeight="320"
displayDepth="16"
mappingImage="PocketPC_2003_Mask.png"
normalImage="PocketPC_2003_Up.png"
downImage= "PocketPC_2003_Down.png">
<button
toolTip="Power"
onPressAndHold="0x75"
mappingColor="0xED145B"
/>
<button
toolTip="Record"
onPressAndHold="0x44"
mappingColor="0xF5989D"
/>
<button
toolTip="Rocker Up"
onPressAndHold="0x48"
mappingColor="0x0072BC"
KeyEvent="Up"
/>
<button
toolTip="Rocker Down"
onPressAndHold="0x50"
mappingColor="0x605CA8"
KeyEvent="Down"
/>
<button
toolTip="Soft Key 1"
onClick="DOWN:0x5b 0x70 UP:0x5b"
mappingColor="0xF26C4F"
/>
<button
toolTip="Soft Key 2"
onClick="DOWN:0x5b 0x71 UP:0x5b"
mappingColor="0xF68E56"
/>
<button
toolTip="Soft Key 3"
onClick="DOWN:0x5b 0x72 UP:0x5b"
mappingColor="0xFBAF5D"
/>
<button
toolTip="Soft Key 4"
onClick="DOWN:0x5b 0x73 UP:0x5b"
mappingColor="0xF7941D"
/>
<button
toolTip="Up"
onPressAndHold="0x48"
mappingColor="0x39B54A"
KeyEvent="Up"
/>
<button
toolTip="Down"
onPressAndHold="0x50"
mappingColor="0x009900"
KeyEvent="Down"
/>
<button
toolTip="Left"
onPressAndHold="0x4B"
mappingColor="0x66CC66"
KeyEvent="Left"
/>
<button
toolTip="Right"
onPressAndHold="0x4D"
mappingColor="0x00CC00"
KeyEvent="Right"
/>
<button
toolTip="Enter"
onClick="0x1C"
mappingColor="0x006600"
KeyEvent="Return"
/>
</view>
</skin>

See Also
Other Resources
Customizing Skins (Devices)
Smart Device Development

Connecting Smart Devices to Development Computers


The topics in this section discuss establishing a secure and reliable connection between the development computer the and
target device (whether the device is real or the emulator).
In This Section
Connection Method Selection
Describes various connection methods.
How to: Set Connection Options (Devices)
Describes how to change default connection settings.
How to: Connect to Windows CE Device Without ActiveSync
Describes the steps for connecting when ActiveSync is not available to support the connection.
How to: Connect Using Bluetooth
Describes the steps for making a Bluetooth connection.
How to: Connect Using IR
Describes the steps for making an IR connection.
How to: Connect to the Device Emulator From a Virtual PC Session
Shows how to connect the development computer to an emulator running in a VPC session.
How to: Access the Smartphone Emulator File System
Describes the steps to access the file system of the Smartphone emulator, which has no File Explorer.
How to: Access Development Computer Files from the Emulator
Describes how to use shared folders to move files between the emulator and the development computer.
Connectivity Troubleshooting (Devices)
Describes issues that interfere with proper connections, and how to resolve them.
See Also
Other Resources
Smart Device Development
Mobile Developer Center
Smart Device Development

Connection Method Selection


During development, it is essential to have a fast and reliable connection between the Smart Device and the development
computer. Although the Smart Device emulators can be used in almost all stages of development, testing your application on a
real-world piece of hardware is a vital part of the development cycle.
Many connection options are available, as summarized later in this article. The most common configurations are:
Connecting to the Device Emulator using the DMA transport. This transport eliminates network-related connection
issues, and typically ships as the default transport. Unless you have some serious reason for using another transport,
always use the DMA transport for the Device Emulator.
Connecting to a physical device using ActiveSync 4.x and a USB port.
You can access these and other options from the Visual Studio Tools menu. For more information, see
How to: Set Connection Options (Devices).
ActiveSync 4.x
ActiveSync 4.x provides a secure connection between the development computer and a device using cable, cradle, Bluetooth, or
infrared connections. It also provides the vehicle by which required connection and security files are automatically downloaded
to the device. When you cradle a device, ActiveSync turns off all other network cards, so you know your device is
communicating only with the development computer. ActiveSync is the standard connection mechanism while you develop
your device application.
If ActiveSync support is not available for your device, see How to: Connect to Windows CE Device Without ActiveSync.
Connection Options
Pocket PCs, Smartphones, and other Windows CE-based hardware offer many ways of linking a device and a computer. In this
section, the various connection options and their advantages and disadvantages are discussed.
Depending on the hardware device involved, one or more of the following connection methods can be employed.
USB Connection
The simplest form of connection, all Pocket PC and Smartphone devices support a USB connection. Although not as fast as
an Ethernet or Wireless 802.11b/g connection, the simplicity of the USB connection makes it an attractive option. Many
devices will also be powered by means of the USB port, which is an added convenience.
Wired Ethernet network
Pocket PC and Smartphone devices do not by default support Ethernet connections without additional hardware. However,
the extra speed of this connection standard makes it the preferred way to perform debugging and other data-intensive
operations.
Wireless 802.11b/g network
Wireless network cards are available for Pocket PCs, and several models now come with wireless networking as an integral
feature. Wireless networking is as fast as a wired Ethernet network connection.
Bluetooth
Many Pocket PC and Smartphone devices feature Bluetooth wireless networking. Once paired, the Smart Device can connect
over ActiveSync as long as it is within range of the desktop computer. Bluetooth is not as fast as 802.11b/g wireless, and is
not recommended for debugging.
Serial connection
If no USB or wired or wireless networking options are available, a serial port makes an acceptable, if slow, way of connecting
a Smart Device to a development computer.
Infrared connection
Infrared connections require no additional wiring, and both Pocket PC and Smartphone devices come with IrDA ports as
standard. However, infrared connections require line-of-sight to operate reliably, and even then performance is not
acceptable for debugging. However, IrDA can be useful as a last resort technique to copy files to devices.
See Also
Tasks
Connectivity Troubleshooting (Devices)
Other Resources
Connecting Smart Devices to Development Computers
Smart Device Development

How to: Set Connection Options (Devices)


Visual Studio 2005 offers many options for connecting the development computer to a device. Use the Device Properties
dialog box to manage these connections.
Visual Studio ships with emulator connections defaulted to the DMA transport and physical devices defaulted to TCP/IP.
To set connection options
1. On the Visual Studio Tools menu, click Options.
2. Expand Device Tools, click Devices, select a device or emulator, and then click Properties.
Use the associated dialog boxes to select and configure your connections.
See Also
Reference
Device Properties Dialog Box
Concepts
Connection Method Selection
Other Resources
Connecting Smart Devices to Development Computers
Smart Device Development

How to: Connect to Windows CE Device Without ActiveSync


When ActiveSync is not available, Visual Studio 2005 does not automatically copy required connectivity files to the device. Use
the following steps to install these files on the device, modify the Visual Studio connection configuration, and establish device
security.
The first two steps, preparing the device and Visual Studio, need to be done only once. The last set of steps, setting security and
establishing the connection, must be repeated any time you want to connect from a new instance of Visual Studio.
To prepare the device for connecting
1. Using whatever connection with the device you have, copy the following files to the \Windows\ folder on the device.
These files are located on the development computer by default at \Program Files\Common Files\Microsoft
Shared\CoreCon\1.0\Target\wce400\<CPU>.
Clientshutdown.exe
ConmanClient2.exe
CMaccept.exe
eDbgTL.dll
TcpConnectionA.dll
2. From the command prompt on the device, run conmanclient2.exe.
3. Determine the IP address of the device.
To prepare Visual Studio for connecting
1. On the Visual Studio Tools menu, click Options, then click Device Tools, and then click Devices.
2. Select Windows CE Device, and then click Properties.
3. To the right of the Transport box, click Configure.
4. In the Configure TCP/IP Transport dialog box, select Use specific IP address, and then type the device IP address.
5. Close the dialog boxes.
A message box might appear prompting you to reset your device. If so, a soft reset is sufficient.
To set security and establish the connection
1. At the command prompt on the device, run cMaccept.exe.
2. Within three minutes, connect to the device.
If you establish your first connection within three minutes, you can continue deploying and debugging indefinitely as
long as you are using the same Visual Studio instance. If you need to connect from another instance of Visual Studio, you
need to perform these security steps again.
Security Note
You can eliminate the cMaccept step by disabling security on the device. To do so, use the Remote Registry Editor to set
HLKM\System\CoreConOverrideSecurity = 1 DWORD value. Disabling security exposes your device to malicious attack
and is not recommended unless you have provided appropriate safeguards.

See Also
Concepts
Remote Tools for Device Projects
Other Resources
Connecting Smart Devices to Development Computers
Smart Device Development

How to: Connect Using Bluetooth


The following steps describe how to connect a device to your development computer using Bluetooth. To complete the
process, you must have ActiveSync 4.0 or later installed.
To connect using Bluetooth
1. On the development computer, ensure that the Bluetooth antenna is correctly inserted and installed.
2. In the Bluetooth properties dialog box on the development computer, change the discoverability to ON.
3. On the device, tap the Bluetooth icon, and then tap Turn Bluetooth ON.
4. Tap Bluetooth Manager.
5. On the Bluetooth window menu, click New to launch a search for Bluetooth-enabled devices.
6. Select the development computer that you want to connect to using ActiveSync.
7. When prompted, type a temporary passkey, and then quickly type the same passkey on the development computer.
You now have a Bluetooth connection with your device. To set up ActiveSync, you create a virtual COM port for this
Bluetooth connection. Use the steps that follow.
To set up ActiveSync
1. On the desktop computer, go into the Bluetooth configuration and add an incoming COM port for your Bluetooth
connection.
2. In ActiveSync, open the Connection Settings dialog box, and then select Allow connections to one of the following.
3. Select the COM port of the Bluetooth device, and then click OK.
4. On the device, launch ActiveSync.
5. On the ActiveSync menu, tap Connect via Bluetooth.
You should now have an ActiveSync connection.
See Also
Other Resources
Connecting Smart Devices to Development Computers
Smart Device Development

How to: Connect Using IR


The following steps describe how to connect a device to your development computer using Infrared Port (IR). To complete the
process, you must have ActiveSync 4.0 or later installed.
To set up the development computer
1. On the development computer, open Microsoft ActiveSync.
2. On the ActiveSync File menu, click Connection Settings.
3. Select Allow connections to one of the following.
4. Select Infrared Port (IR), and then click OK.

To set up the device


1. Ensure that the device IR port is pointing to the development computer IR port, and is within good range.
2. On the device, open ActiveSync.
3. On the ActiveSync Tools menu, tap Connect via IR.
The connection is established.

See Also
Tasks
Connectivity Troubleshooting (Devices)
Other Resources
Connecting Smart Devices to Development Computers
Smart Device Development

How to: Connect to the Device Emulator From a Virtual PC


Session
You cannot use TCP/IP to connect to the device emulator during a Virtual PC (VPC) session because VPC does not support the
Virtual Network Switch driver. The emulator needs this driver for a TCP/IP connection. Instead, use the steps that follow.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To connect to the emulator during a Virtual PC session


1. Install Microsoft ActiveSync 4.x in the Virtual PC image.
2. On the ActiveSync File menu, click Connection Settings.
3. In the Connection Settings dialog box, change the connection transport to DMA.
4. Launch the emulator.
5. On the Visual Studio Tools menu, click Device Emulator Manager.
6. In the Available Emulators box, right-click the desired emulator, and then click Cradle on the shortcut menu.
7. Follow the instructions in the ActiveSync wizard to establish a partnership.
See Also
Tasks
How to: Launch the Device Emulator in Visual Studio
Other Resources
Getting Started with Smart Device Projects
Connecting Smart Devices to Development Computers
Smart Device Development

How to: Access the Smartphone Emulator File System


The Smartphone emulator has no File Explorer. Use the following technique to access the Smartphone file system. To complete
the process, you must have ActiveSync 4.0 or later installed.
Before attempting to use ActiveSync with an emulator, make sure no device is connected to your desktop computer and that
USB connections are disabled in ActiveSync.
Note
If you close the Device Emulator Manager or close the emulator after completing the following steps, the ActiveSync connecti
on also closes.

To access the Smartphone emulator file system


1. On the Visual Studio Tools menu, click Device Emulator Manager.
2. In the Available Emulators box, select the emulator whose file system you want to access.
3. On the Device Emulator Manager Actions menu, click Connect.
An icon appears beside the selected emulator indicating that a connection has been made.
4. Right-click the selected emulator, and then click Cradle.
The icon changes to show the emulator is cradled.
5. Open ActiveSync.
6. On the ActiveSync File menu, click Connection Settings.
7. Select the Allow connections to one of the following check box.
8. Select DMA from the list of ports, and then click OK.
ActiveSync now initiates a partnership with the emulator. Follow the instructions provided by the New Partnership
Wizard.
Note
If a partnership is not initiated automatically, click Connect in the Connection Settings dialog box, and then follow th
e prompts in the Get Connected Wizard.

9. After you have completed the ActiveSync partnership steps, click Explore on the ActiveSync toolbar to access the
Smartphone emulator file system.
Note
Whenever you want to use an emulator connected with Visual Studio using ActiveSync, use the Device, not Emulator, ta
rget of the corresponding platform.

See Also
Other Resources
Connecting Smart Devices to Development Computers
Smart Device Development

How to: Access Development Computer Files from the


Emulator
The following steps demonstrate how to use folder sharing to access files on the development computer from the device
emulator.
Note
Smartphone emulators typically do not have file viewers, so the Remote File Viewer is used in the Smartphone testing steps t
hat follow. For more information, see Remote File Viewer.

To set up a shared folder


1. On the development computer, create a folder to be shared between the development computer and the device
emulator.
2. On the Device Emulator File menu, click Configure.
3. In the Shared folder box of the General tab, type or navigate to the shared folder on the development computer.
4. Click OK.
To test your shared folder on the Pocket PC emulator
1. In the Pocket PC emulator, open File Explorer.
2. Tap and select My Device.
The Storage Card entry is the shared folder.

To test your shared folder on the Smartphone emulator


1. On the Windows Start menu, point to All Programs, then point to Microsoft Visual Studio 2005, then point to Visual
Studio Remote Tools, and then click Remote File Viewer.
2. In Select a Windows CE Device, select the Smartphone emulator, and then click OK to open the Windows CE Remote
File Viewer window.
The Storage Card entry is the shared folder.
See Also
Other Resources
Connecting Smart Devices to Development Computers
Smart Device Development

Connectivity Troubleshooting (Devices)


Most connectivity difficulties between the development computer and a device result from either security or network issues.
The following paragraphs help you identify and resolve some of the more common connection issues and provide steps to
establish reliable and secure connections.
Connecting to the Device Emulator
Use the DMA transport that Visual Studio 2005 provides for connecting to the Device Emulator. This transport eliminates
virtually all connection issues between the development computer and the emulator.
Important
Use the TCP/IP transport only if you have some serious specific reason. To resolve issues arising from use of TCP/IP with the
emulator, review the steps that follow. For more information, see the Mobile Developer Center.

Failed to Open Virtual Switch Driver


If you are trying to connect the Device Emulator to a network using the emulated NE2000 or CS8900 card, you need a Virtual
Switch Driver. You can download a driver from the Mobile Developer Center.
An error opening the driver can arise for several reasons, including:
Lack of driver.
The network card on the development computer does not have the driver installed.
There were problems during the installation of the driver.
The driver is in a disabled state.
The development computer does not have a network card.
Use the following steps to diagnose the precise cause.
To diagnose the precise cause of the failure
1. Look on the Network tab of the Emulator Properties dialog box.
If the NE2000 and/or the CS8900 cards are enabled, verify that the network cards they are bound to are present and
connected. To open the Emulator Properties dialog box, click Configure on the emulator File menu.
2. Look at the network properties of the adapter to verify that the item Virtual Machine Network Services is present,
enabled, and of the correct version, which is 2.6.465.224 or later.
3. If these steps fail to fix the problem, reinstall the driver.
Deployment to Emulator Error
If your development computer has a wireless network connection and you are using the TCP Transport, you might need
additional steps, such as installing the Microsoft Loopback Adapter. For more information, see the Mobile Developer Center.
Note
Unless you have some serious specific reason to use the TCP Transport, use the DMA transport to avoid network issues.

Cannot Debug After Switching Transports


You can change the transport for the emulator, but the emulator does not bind to the new transport until you soft-reset the
device.
Note
The DMA transport is the preferred transport for the Device Emulator. Use the TCP/IP transport only if you have serious speci
fic reasons for doing so.
To switch transports
1. On the Visual Studio Tools menu, click Options, then click Device Tools, and then click Devices.
2. Select an emulator, and then click Properties.
3. In the Transport box, select a different transport.
If you are switching to TCP/IP, click Configure to set additional options.
4. Click OK to close the dialog boxes.
Cannot Connect to Emulator While Running in Virtual PC Session
You can avoid this connection issue by using the DMA transport for the emulator. For more information, see
How to: Connect to the Device Emulator From a Virtual PC Session.
Repairing the Device Emulator Installation
Errors indicating a failure to connect to the Device Emulator are typically not installation errors. However, you can use the
following steps to repair the Device Emulator installation. To do this, you need your original installation media. Repairing your
Visual Studio 2005 installation does not repair Device Emulator installation.
To repair the Device Emulator installation
1. Navigate to wcu\ARM on your original Visual Studio 2005 installation media.
The location of this folder, under Disk 1, Disk 2, and so on, varies with your edition of Visual Studio.
2. Double click vs_emulator.exe to open the Device Emulator Setup Wizard, and then follow the instructions.
Additional Tips
The Device Emulator independent Help system provides additional tips. For more information, click the Device Emulator Help
menu and look for "Troubleshooting Connection Issues" on the Content or Index tabs.
Connecting to Physical Devices
Lack of Proper Certificates on Device
Some devices, including Smartphone 2003 and later, require proper certificates to be installed on the device for security
reasons. Certificates for day-to-day development work are included in Visual Studio 2005, along with a tool to install them.
To install the required certificates
1. Connect to the device using whatever connection mechanism you have available.
2. Copy SDKCERTS.cab from the development computer to the device.
SDKCERTS.cab is located by default under \Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SDKTools.
3. On the device, explode sdkcerts.cab to install the certificates.
Lack of Prepping Windows CE 5.0 Device
Windows CE 5.0 devices that do not have ActiveSync support require preparation steps before a connection can be established
with a Visual Studio instance. For more information, see How to: Connect to Windows CE Device Without ActiveSync.
Unexpected behavior during deployment
If the development computer is connected to a device through ActiveSync and you then try to make a TCP/IP connection with,
for example, a Windows CE device, —and a connection error occurs, then the development computer connects with the
ActiveSync-connected device, and does not warn that the TCP/IP connection failed.
Wireless Connections
Although Visual Studio 2005 supports the use of wireless technology to connect to devices, wireless technology introduces
additional factors that can adversely affect a successful and maintainable connection. These factors include misalignment of IR
ports, obstruction or degradation of signal in RF connections, and so on.
See Also
Other Resources
Connecting Smart Devices to Development Computers
Smart Device Development

Programming for Devices Using the .NET Compact Framework


This section provides information on developing smart device applications using the Visual Basic or C# language and the
.NET Compact Framework.
In This Section
What's New in Managed Device Projects
Lists important changes since Visual Basic .NET 2003.
Differences from Desktop in .NET Compact Framework Development
Describes differences from developing desktop applications.
Variations in .NET Compact Framework Versions
Describes the several releases of the .NET Compact Framework, including service packs.
Differences Between Pocket PC 2003 and Smartphone 2003 Controls
Presents a table showing which controls are supported for Pocket PC 2003 development and which are supported for
Smartphone 2003 development.
Controls and Components in Managed Device Projects
Describes additional controls and components available for device development.
Custom and User Controls in Device Projects
Describes the functionality available for device projects.
COM Interoperability for Devices
Describes how to create COM Interop assemblies in a managed device project.
Creating and Developing Managed Device Projects
Provides step-by-step instructions for common device development tasks.
Data in Managed Device Projects
Describes how to manage data for devices in Visual Studio 2005.
Walkthrough: Creating a Simple Application
Provides step-by-step instructions on creating a simple Visual Basic or Visual C# device project.
See Also
Tasks
Walkthrough: Creating Windows Forms Applications for a Device
Other Resources
.NET Compact Framework
Smart Device Development
.NET Compact Framework
Frequently Asked Questions
Mobile Developer Center
Smart Device Development

What's New in Managed Device Projects


The list below describes enhancements for managed device application development added since Visual Studio .NET 2003.
Note
Although you can use Visual Studio 2005 to program against both version 1.0 and version 2.0 of the .NET Compact Framewo
rk, the features below marked with an asterisk (*) are not supported in version 1.0.

New Features
The following features are available in Visual Studio 2005.
Feature Details
*Anchoring controls on Windows forms How to: Anchor Controls on Windows Forms

CAB file generation using Visual Studio Setup and Deployment project Packaging Device Solutions Overview
s. This process eliminates the need to manually customize the .inf file.

Filter unsupported properties/methods/events. Feature includes filtered IntelliSense, a build verificatio


n step, and ability to convert unsupported controls.

Color Editor Colors as they appear on the device.


Define Color Dialog Box (Devices)

Custom Controls Fully supported. Use


Designing and Viewing Classes and Types to add custo
*User Controls m designer attributes.

*Docking controls on Windows Forms How to: Dock Controls on Windows Forms

*Data design support Data in Managed Device Projects

Font Editor Fonts as supported by the current


platform.Font Editor Dialog Box (Devices)

Form factor support, including orientation and resolution. Form Factor Properties Dialog Box (Devices)
*Autoscale

Form skin with code creation Form Factor Properties Dialog Box (Devices)

*New Controls and Components in Toolbox WebBrowser, Notification, DocumentList,


DateTimePicker, MonthCalendar, LinkLabel, Splitter,
BindingSource

Platform-specific WYSIWYG Improved designers provide accurate appearance for e


ach platform.

Targets version 1.0 of the .NET Compact Framework Smartphone 2003 and Pocket PC 2003 support

Change platforms using the same source code How to: Share Source Code Across Platforms (Devices)

See Also
Other Resources
What's New in the .NET Compact Framework 2.0
What's New in the Development Environment
Programming for Devices Using the .NET Compact Framework
Smart Device Development

Differences from Desktop in .NET Compact Framework


Development
Before you start a device project, it is important to understand the major differences between desktop development using the
.NET Framework and device development using the.NET Compact Framework.
Programming Elements in Visual Basic
When you program against the .NET Compact Framework using Visual Basic, you do not have the same list of programming
elements, such as functions and keywords, that you have when you program against the full .NET Framework. These
differences are summarized in Visual Basic Language Reference for Devices and noted in the individual topics for those
elements in the Visual Basic Reference.
Development with My
Visual Studio 2005 includes support for My.Resources, My.Forms, and My.WebServices. It does not include support for
My.Application, My.Computer, My.User, or My.Settings. For more information, see My Reference.
File Input and Output
Visual Basic offers two options for file input/output (I/O):
The standard .NET Framework System.IO namespace. All languages in the common language runtime (CLR) support
these libraries.
A set of Visual Basic-specific libraries that provides a development experience similar to that of previous versions of
Visual Basic.
Device projects support only the .NET Framework System.IO namespace. File I/O with the FileSystem namespace is not
supported because:
Several commonly used features of the FileSystem namespace do not exist on devices. For instance, there is no concept
of a current directory or a current drive on devices. Therefore, you cannot use the ChDir and ChDrive functions.
Supporting only the .NET Framework System.IO namespace reduces the size of the Visual Basic helper libraries. This
frees up valuable space on the device.
Implicit Late Binding
In Visual Basic, an object is late-bound when it is assigned to a variable declared to be of type Object Data Type. Objects of this
type are bound at run time. You can assign to them and retrieve values from them. But you cannot specify the methods or
properties of an object variable using the dot convention. The following code causes a compiler error because it attempts to
get the property of an object:
dim a as object = "automobile"
dim i as integer = a.horsepower

COM Interop
Desktop application developers use COM interoperability to draw on existing COM objects while they transition to the .NET
Framework at their own pace. Device projects support only certain scenarios for COM interop. For more information, see
COM Interoperability for Devices.
Debugging
Attaching to running processes differs somewhat from the desktop. For more information, see
How to: Attach to Managed Device Processes.
See Also
Reference
Visual Basic Language Reference for Devices
System.IO Namespace
Deciding Which Technologies and Tools To Use
My Reference
Concepts
Early and Late Binding
Me, My, MyBase, and MyClass in Visual Basic
COM Interoperability for Devices
Other Resources
File Access with Visual Basic
.NET Framework Programming in Visual Studio
Smart Device Development

Variations in .NET Compact Framework Versions


When developing applications for Smart Devices, it is important to take into account the possible variations in the installed
version of the Compact Framework.
.NET Compact Framework version 1.0
The initial release of the Compact Framework.
.NET Compact Framework version 1.0 SP1
Bug fixes from version 1.0.
Support for Smartphone.
.NET Compact Framework version 1.0 SP2
Bug fixes from version 1.0 SP1.
Performance improvements.
Support for devices with landscape display modes.
Support for Autoscroll, automatically supporting dialogs in landscape mode.

.NET Compact Framework version 1.0 SP3


Bug fixes from version 1.0 SP2.
.NET Compact Framework version 2.0
Smart Devices that have been upgraded to version 2.0 of the .NET Compact Frameworks will have the following features:
Performance improvements.
Support for Generic classes.
Support for COM interop.
Improved support for controls.
Support for Direct3D and DirectDraw for Mobile Devices.
See Also
Other Resources
Programming for Devices Using the .NET Compact Framework
What's New in the .NET Compact Framework 2.0
.NET Compact Framework FAQ - .NET Compact Framework 2.0
Smart Device Development

Differences Between Pocket PC 2003 and Smartphone 2003


Controls
The following table summarizes the difference in control support between Windows Mobile Pocket PC 2003 and Windows
Mobile Smartphone 2003. Some controls do not make sense in the context of the Smartphone, which, for example, has no
touchscreen.
Control Pocket PC 2003 Smartphone 2003
Label Yes Yes

LinkLabel Yes No

Button Yes No

TextBox Yes Yes

MainMenu Yes Yes

CheckBox Yes Yes

RadioButton Yes No

PictureBox Yes Yes

Panel Yes Yes

DataGrid Yes No

BindingSource Yes No

ListBox Yes No

ComboBox Yes Yes

ListView Yes Yes

TreeView Yes Yes

TabControl Yes No

DateTimePicker Yes No

MonthCalendar Yes No

HScrollBar Yes Yes

VScrollBar Yes Yes

Timer Yes Yes

Splitter Yes No
DomainUpDown Yes No

NumericUpDown Yes No

TrackBar Yes No

ProgressBar Yes Yes

ImageList Yes Yes

ContextMenu Yes No

ToolBar Yes No

StatusBar Yes No

OpenFileDialog Yes No

SaveFileDialog Yes No

WebBrowser Yes No

InputPanel Yes No

Notification Yes No

DocumentList Yes No

You can share source code across platforms. For more information, see How to: Share Source Code Across Platforms (Devices).
See Also
Tasks
How to: Upgrade Projects to Later .NET Compact Framework Versions
Other Resources
Programming for Devices Using the .NET Compact Framework
Smart Device Development

Controls and Components in Managed Device Projects


Managed device projects have their own set of controls and components, and their own tab in the Visual Studio Toolbox. When
a device project is active, this Devices tab is available for drag-and-drop operations just as in projects for the desktop.
For more information, see Windows Forms Controls in the .NET Compact Framework
See Also
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

Custom and User Controls in Device Projects


The .NET Compact Framework provides healthy support for creating and customizing controls for Windows Forms projects.
User Controls
You can create and add user controls to your managed device projects in the same way you would for desktop projects. For
more information, see How to: Author Composite Controls.
Custom Controls
The .NET Compact Framework provides a number of ways to customize controls. For more information, see
Custom Control Development.
See Also
Tasks
Walkthrough: Authoring User Controls for Devices
Walkthrough: Adding a Simple Attribute to a User Control
Other Resources
Developing Windows Forms Controls at Design Time
Designing and Viewing Classes and Types
Programming for Devices Using the .NET Compact Framework
Smart Device Development

COM Interoperability for Devices


The .NET Compact Framework supports Runtime Callable Wrappers (also called "Interop Assemblies") for COM objects. This
feature includes the marshaling of complex types. COM Interop for devices is based on the desktop implementation. As such,
components must be registered on the desktop.
Supported Scenarios
The following scenarios are supported for device projects in Visual Studio 2005:
You can add an existing COM component as a reference to a managed project. This action creates an interop assembly
and automatically adds the assembly as a reference. You can then use the interop assembly just as you could any
managed assembly, and the properties, methods, and events of the object are available for Intellisense and in the Object
Browser. Legal file types to add are DLL, EXE, and TLB.
You can create a native project to generate a COM component, and then create a managed project in the same solution
to consume the COM component. The process is the same as for the desktop:
Set the native project to generate TLB output.
Compile the native project to generate a DLL.
In the managed project, add a reference to the DLL. This action generates the interop assembly.
Unsupported Scenarios
The following scenarios are not supported in Visual Studio 2005:
Referencing an existing ActiveX COM component from within a managed project
COM objects with non-system child components
COM objects referenced as business objects from within the DataSource Wizard.

See Also
Tasks
Walkthrough: Hello World: A COM Interop Example for Smart Devices
Walkthrough: Debugging a Solution That Includes Both Managed and Native Code
Concepts
Introduction to COM Interop
Runtime Callable Wrapper
Marshaling Selected Interfaces
Other Resources
COM Interoperability in .NET Framework Applications
Programming for Devices Using the .NET Compact Framework
Interoperability in the .NET Compact Framework
Smart Device Development

Creating and Developing Managed Device Projects


Developing managed device projects is very similar to developing managed desktop projects. A central difference is that the
.NET Compact Framework is a subset of the full .NET Framework, and accordingly, some areas are not supported. For more
information, see .NET Compact Framework.
In This Section
How to: Create Device Applications Using Visual Basic or Visual C#
How to: Display the Device Toolbar in Visual Basic Projects
How to: Show Configuration Manager in Visual Basic Projects (Devices)
How to: Share Source Code Across Platforms (Devices)
How to: Change Platforms in Device Projects
How to: Upgrade Projects to Later .NET Compact Framework Versions
How to: Verify Platform Support for Code in Device Projects
How to: Handle HardwareButton Events (Devices)
How to: Change the Orientation and Resolution of Forms (Devices)
How to: Change the Default Device (Managed Projects)
How to: Play a Wave File Using Platform Invoke (Devices)
Managing Code Snippets in Device Projects
See Also
Other Resources
Programming for Devices Using the .NET Compact Framework
.NET Framework Programming in Visual Studio
Smart Device Development

How to: Create Device Applications Using Visual Basic or Visual


C#
Creating Visual Basic and Visual C# managed projects for devices follows the same general process as creating projects for the
desktop, except that you must select a target platform (for example, Pocket PC 2003) and .NET Compact Framework version
(for example, v2.0) on which the project is designed to run.
An enhanced New Project dialog box in Visual Studio 2005 replaces the Smart Device Application Wizard of Visual Studio
.NET 2003. In Visual Studio 2005, you make all choices regarding project types and templates from the New Project dialog
box.
Note
Options available in dialog boxes and menu commands differ depending on your active settings, also known as your profile.
The following procedure was written using Visual Basic Development Settings and Visual C# Development Settings. To view
or change your settings, choose Import and Export Settings on the Tools menu.

To create a device project


1. (Visual Basic) On the File menu in Visual Studio 2005, click New Project.
—or—
(Visual C#) On the File menu in Visual Studio 2005, point to New, and then click Project.
2. Under Project Types in the New Project dialog box, expand Visual Basic Projects or Visual C# Projects, expand
Smart Device, and then click the platform you want, such as, Pocket PC 2003.
If the language you want does not at first appear, expand Other Languages. This display is governed by your
Development Settings. To view or change your settings, click Import and Export Settings on the Tools menu.
3. Under Templates, click whichever template is appropriate for what you want to do, for example, Pocket PC 2003 Class
Library.
Note
A template that has (1.0) appended to its name is designed for version 1.0 of the .NET Compact Framework. Other tem
plates are designed for version 2.0.

4. In the Name box, type a name for the project.


If a Location box is displayed, verify where you want to store your project files, and then click OK.
To add a project to an existing solution
On the File menu, point to Add, and then click New Project or Existing Project.
The New Project command opens the New Project dialog box so that you can create a new project. The Existing
Project command opens the Add Existing Project dialog box so that you can select an already existing project for
inclusion into the current solution.
To port existing projects
The steps for porting projects created in a previous version of Visual Studio are described in the general Visual Studio
documentation for managing projects. For more information, see Projects and Backward Compatibility and
Working With Multiple Versions of the .NET Framework.
See Also
Tasks
Walkthrough: Creating Windows Forms Applications for a Device
Reference
Deciding Which Technologies and Tools To Use
Other Resources
What's New in the .NET Compact Framework 2.0
Managing Solutions, Projects, and Files
Creating and Developing Managed Device Projects
Smart Device Development

How to: Display the Device Toolbar in Visual Basic Projects


If you set your Development Settings to Visual Basic Development Settings, the Device toolbar does not appear by default.
To display the Device toolbar
On the Visual Studio View menu, point to Toolbars, and then click Device.
See Also
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

How to: Show Configuration Manager in Visual Basic Projects


(Devices)
If you have selected Visual Basic Development Settings, Configuration Manager does not appear by default. You use
Configuration Manager when, for example, you want to switch from a Debug to a Release configuration. The following steps
show how to display Configuration Manager.
To display Configuration Manager in a Visual Basic device project
1. On the Visual Studio Tools menu, click Options, expand Projects and Solutions, and then click General.
2. Click Show advanced build configurations.
See Also
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

How to: Share Source Code Across Platforms (Devices)


You can share source code across platforms by using compiler constants to differentiate those sections of code that depend on
the target. Allowable constants are PocketPC, Smartphone, and WindowsCE. The platforms must target the same version of the
.NET Compact Framework.
The following steps provide a simple example of the technique. You create a Visual Basic Pocket PC application, add compiler
directives, run the application, close it, and change to a Smartphone application. Then you run the Smartphone application to
see that the title bar text is changed.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To create and run the Pocket PC version


1. On the Visual Studio File menu, point to New, and then click Project.
2. In the Project types pane, expand Visual Basic, expand Smart Device, and then click Pocket PC 2003.
3. In the Templates pane, click Device Application (1.0), and then click OK.
The appended (1.0) indicates that this is a .NET Compact Framework version 1.0 project.
4. In the designer, right-click the form, and then on the shortcut menu, click Properties.
5. Clear the Text property value of the form—that is, make it blank.
6. In Solution Explorer, right-click Form1.vb, and then on the shortcut menu, click View Code.
7. Expand the Windows Form Designer generate code region.
8. After InitializeComponent() in Public Sub New(), insert the following code:

#If PocketPC Then


Me.Text = "PPC2003"
#Else
Me.Text = "Smartphone"
#Endif

9. On the Debug menu, click Start Debugging.


10. In the Deploy <Projectname> dialog box, click Pocket PC 2003 SE Emulator, and then click Deploy.
The Pocket PC application runs in the emulator with PPC2003 in the title bar of the form.
To create and run the Smartphone version
1. Close the emulator without saving state.
If a message appears indicating that the connection has been lost, click OK.
2. On the Project menu, click Change Target Platform.
3. In the Change to box in the Change Target Platform dialog box, select Smartphone2003, and then click OK.
4. In the message box advising that the project will be closed and re-opened, click Yes.
Note that the Target Device box on the toolbar now displays Smartphone 2003 SE Emulator.
5. On the Debug menu, click Start Debugging.
6. In the Deploy <Projectname> dialog box, click Smartphone 2003 SE Emulator, and then click Deploy.
The Smartphone application runs in the emulator with Smartphone in the title bar of the form.
See Also
Tasks
How to: Change Platforms in Device Projects
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

How to: Change Platforms in Device Projects


You can switch back and forth between platforms in the same project. For example, if you are targeting a Pocket PC platform,
you can switch to target a Windows CE platform, as long as the new platform targets the same version of the .NET Compact
Framework as the original target.
To change target platforms in a device project
1. On the Project menu, click Change Target Platform.
2. In the Change to box, select a different platform, and then click OK.
The only platforms available are those that target the same version of the .NET Compact Framework as the active project.
See Also
Reference
Change Target Platform Dialog Box (Devices)
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

How to: Upgrade Projects to Later .NET Compact Framework


Versions
This procedure upgrades the .NET Compact Framework version of an existing project if a later version of the .NET Compact
Framework is installed on the development computer.
To upgrade a project to a later version of the .NET Compact Framework
1. On the Project menu, click Upgrade Project.
Note
If the Upgrade Project command does not appear on the menu, then no later version of the platform is installed on th
e development computer, and the upgrade process is unavailable for the current project.

2. Follow the instructions on the prompt that appears.


See Also
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

How to: Verify Platform Support for Code in Device Projects


Visual Studio always validates that your code is supported by the target platform and generates warnings if it is not.
You can stop unsupported code from deploying by stipulating that all warnings should be treated as errors, so that the build
fails.
For example, the following Visual Basic code, even though it compiles, would generate a warning or error in a Smartphone
application because Smartphone does not support buttons.
Dim btn as System.Windows.Forms.Button
btn = new System.Windows.Forms.Button()

btn.Caption = "MyButton"

To treat all warnings as errors in Visual Basic


1. In Solution Explorer, right-click <Projectname>, and then on the shortcut menu, click Properties.
2. On the Compile tab, select Treat all warnings as errors.
To treat all warnings as errors in Visual C#
1. In Solution Explorer, right-click <Projectname>, and then on the shortcut menu, click Properties.
2. On the Build tab, select All in the Treat warnings as errors section.
See Also
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

How to: Handle HardwareButton Events (Devices)


Use a HardwareButton control to override the application keys on a Pocket PC.
To assign a HardwareButton component to a specific application key
1. From the Device Components tab of the Toolbox, drag a HardwareButton component onto a Windows Form or into
the Component tray in the designer.
2. In the Component tray, right-click the HardwareButton control, and then on the shortcut menu, click Properties.
3. Set the AssociatedControl property to the form, for example, Form1.
4. Set the HardwareKey property to the key you want to override, for example, ApplicationKey1.
5. Click the button, for example, Soft Key 1, on the designer's skin.
The Code Editor opens at the Form_KeyDown event handler.
6. Insert the following code:

if ((int) e.KeyCode == (int) Microsoft.WindowsCE.Forms.HardwareKeys.ApplicationKey1)


{
//TODO
}

You would typically use the //TODO section to launch an application.

See Also
Tasks
How to: Use the HardwareButton Component
Reference
HardwareButton
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

How to: Change the Orientation and Resolution of Forms


(Devices)
Default orientation (rotation) properties are already set for platforms installed with Visual Studio. Use the following steps if you
need to change the properties or if you have installed an SDK in which these properties are incorrect or lacking.
To change orientation
1. On the Tools menu, click Options, click Device Tools, and then click Form Factors.
2. Select the form factor — for example, Pocket PC 2003 Portrait — for the form in your project, and then click
Properties.
3. Select Show skin in Windows Forms Designer and Enable rotation support.
4. Click OK to close the Form Factor Properties dialog box, and click OK again to close the Options dialog box.
Note
If the designer was open when you changed options, close and re-open it for the changes to take effect.

5. In the designer, right-click the form or the skin, and then select Rotate Left or Rotate Right to rotate the skin.
Whether the form rotates when the device rotates depends on the current platform and on form property settings, as
follows:
Smartphone: The form always rotates when the device rotates.
Pocket PC: The form rotates by default when the device rotates. To prevent the form from rotating with the device,
set the WindowState property of the form to Normal and the FormBorderStyle property to None.
Windows CE: The form does not rotate by default when the device rotates. To make the form rotate with the device,
set the WindowState property to Maximized.
To change resolution
1. On the Tools menu, click Options, click Device Tools, and then click Form Factors.
2. Select the form factor — for example, Pocket PC 2003 Portrait — for the form in your project, and then click
Properties.
3. In the Form Factor Properties dialog box, set the vertical and horizontal resolution.
4. Click OK to close the Form Factor Properties dialog box, and then click OK again to close the Options dialog box.
Note
If the designer was open when you changed options, close and re-open it for the changes to take effect.

See Also
Reference
Form Factor Properties Dialog Box (Devices)
Form Factors, Device Tools, Options Dialog Box
Smart Device Development

How to: Change the Default Device (Managed Projects)


Use the following steps to change the default target device in managed projects.
To select a new default target device for a managed project
1. In Solution Explorer, right-click <Project name>.
2. On the shortcut menu, click Properties, and then select the Devices pane.
3. Use the drop-down list in the Target device box to select a new default target.

See Also
Tasks
How to: Change the Default Device (Native Projects)
Reference
Deploy Dialog Box (Devices)
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

How to: Play a Wave File Using Platform Invoke (Devices)


The following code example illustrates how to use Platform Invoke (PInvoke) to play a wave sound file on a mobile device.
Example
This example code plays a sound file using PlaySound on the mobile device. This code uses System.Runtime.InteropServices to
invoke the PlaySound method of the Compact FrameWork's CoreDll.DLL.

using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;

namespace MobileSoundPInvoke
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu1;

public Form1()
{
InitializeComponent();
PlaySound(".\\sound.wav");
}

#region Windows Form Designer generated code


private void InitializeComponent()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.Menu = this.mainMenu1;

this.Text = "Form1";
}

#endregion
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
static void Main()
{
Application.Run(new Form1());
}
private enum Flags
{
SND_SYNC = 0x0000,
SND_ASYNC = 0x0001,
SND_NODEFAULT = 0x0002,
SND_MEMORY = 0x0004,
SND_LOOP = 0x0008,
SND_NOSTOP = 0x0010,
SND_NOWAIT = 0x00002000,
SND_ALIAS = 0x00010000,
SND_ALIAS_ID = 0x00110000,
SND_FILENAME = 0x00020000,
SND_RESOURCE = 0x00040004
}

[DllImport("CoreDll.DLL", EntryPoint = "PlaySound", SetLastError = true)]


private extern static int MobilePlaySound(string szSound, IntPtr hMod, int flags);

public void PlaySound(string fileName)


{
MobilePlaySound(fileName, IntPtr.Zero, (int)(Flags.SND_ASYNC | Flags.SND_FILENA
ME));
}

}
}

Compiling the Code


Create a new C# Smartphone Application project in Visual Studio and call it MobileSoundPInvoke.
Copy the code from the previous example, and paste it over the Form1.cs file of your MobileSoundPInvoke project in a
console application.
Robust Programming
Make sure the appropriate parameters are passed to the C MobilePlaySound (string szSound, IntPtr hMod, int
flags) function, including the path and file name for the .wav file.

Security
For more information on security, see .NET Framework Security.
See Also
Tasks
Platform Invoke Technology Sample
Other Resources
Smart Device Samples
Smart Device Walkthroughs
Using Explicit PInvoke in C++ (DllImport Attribute)
Creating a P/Invoke Library
http://pinvoke.net/
Smart Device Development

Managing Code Snippets in Device Projects


Visual Basic includes a code library of IntelliSense Code Snippets that you can insert with a few mouse clicks into your
application. Each snippet performs a complete programming task. You can also create your own snippets, add them to the
library, and then use them when you need them.
Visual Studio has added snippets that pertain exclusively to device projects. The shortcuts for these snippets all begin with the
characters sd. For more information, see Visual Basic IntelliSense Code Snippets.
See Also
Other Resources
Creating and Developing Managed Device Projects
Smart Device Development

Data in Managed Device Projects


This topic has been updated for Visual Studio 2005 SP1.
Visual Studio 2005 provides new database management tools for device solutions, including the ability to create new
databases, modify their schemas, and handle other management tasks such as setting passwords and compressing the
database.
The following section has been updated for Visual Studio 2005 SP1.
In This Section
Data Access Overview (Managed Device Projects)
Describes the features available in Visual Studio for handling data applications in device projects.
Resultsets vs. Datasets (Devices)
Describes the difference between these two techniques, and why you would use one or the other.
Generating Typed ResultSets
Describes in more detail the features offered by ResultSets.
Managing Data Sources in Device Projects
Lists steps for common tasks, such as creating a SQL Server Mobile or SQL Server Compact Edition database, modifying
table schemas, managing passwords, and so on.
See Also
Tasks
Walkthrough: A Database Master-Detail Application
Concepts
Connecting to Data in Visual Studio Overview
Other Resources
Creating Client Data Applications
Data Walkthroughs
Programming for Devices Using the .NET Compact Framework
SQL Server Mobile Edition Books Online Home Page
Programming for Devices Using the .NET Compact Framework
Smart Device Development

Data Access Overview (Managed Device Projects)


This topic has been updated for Visual Studio 2005 SP1.
The Visual Studio environment for developing device projects that manipulate data is similar to the environment for
developing desktop data applications. Managed data applications for devices rely on ADO.NET namespaces supported by the
.NET Compact Framework. This combination lends itself to applications where the data store on the device is typically
disconnected from data on a server, and is only periodically synchronized.
Data for Devices: What's New in Visual Studio 2005
The following section has been updated for Visual Studio 2005 SP1.
You can create SQL Server Mobile or Microsoft SQL Server 2005 Compact Edition databases, assign passwords, alter
schemas, and perform other fundamental database management tasks using the Visual Studio IDE.
You can use Typed Datasets, ResultSets, business objects, SQL Server databases, SQL Mobile databases, SQL Server
Compact Edition databases, or Web services as data sources.
You can drag and drop these data sources from the Data Sources window onto a Windows Form to generate data-bound
controls of your choice.
Note
The Data Source Configuration Wizard is not available for projects that target version 1.0 of the .NET Compact Fram
ework.

SQL Server Mobile Edition and SQL Server Compact Edition Architectures
The following section has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
SQL Server Mobile and SQL Server Compact Edition represent the best local data engine for devices that are only occasionally
connected. You can program using the .NET Compact Framework for managed applications or Microsoft Visual C++ for
Devices for native applications. For more information, see SQL Server Mobile Architecture.
Typical Uses of SQL Server Mobile Edition and SQL Server Compact Edition
The following section has been updated for Visual Studio 2005 SP1.
SQL Server Mobile and SQL Server Compact Edition offer a solution for occasionally connected data access scenarios on
mobile devices. Mobile enterprise scenarios are frequently required to work with data when connectivity is not available. SQL
Server Mobile and SQL Server Compact Edition address these scenarios by providing rich relational stores that can be
synchronized to SQL Server when a connection is available. For more information, see Typical Uses of SQL Server Mobile.
Note
You can use SQL Server Mobile and SQL Server Compact Edition as data stores for Tablet PC applications as well as for devic
e applications. You can also run them on laptops and desktops provided either Visual Studio 2005 or SQL Server 2005 is inst
alled. For more information, see Building a SQL Server Mobile Application for Tablet PCs.

Features of SQL Server Mobile and SQL Server Compact Edition


The following section has been updated for Visual Studio 2005 SP1.
SQL Server Mobile and SQL Server Compact Edition provide a wealth of features, either as part of a .NET Compact Framework
application or as an independent installation on a smart device. Data can be manipulated offline and synchronized later to a
server. For more information, see SQL Server Mobile Features.
Designing and Managing SQL Server Databases
To develop effective data applications for devices, you need an understanding of good database design and of the SQL Server
database engine. You should master how to maintain databases, how to make them secure, how to access and modify the data
in them, how to efficiently query them, and how to maximize their performance. For more information, see
Working with Databases (SQL Server Mobile) and Enhancing Performance.
Connections With a Server
The following section has been updated for Visual Studio 2005 SP1.
SQL Server Mobile and SQL Server Compact Edition support merge replication, Remote Data Access, and security planning
and implementation at the server. For more information, see Managing Connectivity (SQL Server Mobile).
Implementing Common Tasks Programmatically
For steps to implement common tasks programmatically, see How To (SQL Server Mobile).
Local security
The SQL Server Mobile and SQL Server Compact Edition Database engines provide password protection and encryption for
securing local databases on devices. They also provide connectivity security options. For more information, see
Securing Databases (SQL Server Mobile).
See Also
Tasks
Walkthrough: A Database Master-Detail Application
How to: Install Sample Databases
Concepts
What's New in Data
Securing Connection Strings
Connecting to Data in Visual Studio Overview
Other Resources
SQL Server Mobile Edition Books Online Home Page
Creating Client Data Applications
Data Walkthroughs
Programming for Devices Using the .NET Compact Framework
Data in Managed Device Projects
Accessing Data (Visual Studio)
Smart Device Development

Resultsets vs. Datasets (Devices)


Visual Studio 2005 generates both datasets and resultsets when you use the DataSource Wizard to create a new data source.
Resultset code is more performant and significantly less verbose than dataset code. On the other hand, datasets are richer in
the sense that they can hold multiple tables and maintain information about relationships between them. The programming
model is significantly different between the two technologies.
You can choose to generate either or both of these structures to suit your purposes. This feature is provided for advanced
developers. For more information, see How to: Generate SqlCeResultSet Code (Devices).
See Also
Tasks
How to: Generate SqlCeResultSet Code (Devices)
Concepts
Recommendations for Data Access Strategies
Other Resources
SQL Server Compact Edition Portal
Data in Managed Device Projects
Smart Device Development

Generating Typed ResultSets


This topic has been updated for Visual Studio 2005 SP1.
When the CustomTool property on an XSD schema file is set to MSResultSetGenerator, typed ResultSet datasource objects
are generated instead of the usual typed DataSet datasource objects. ResultSets are fast database cursors that support UI
databinding, backward and forward scrolling through the data, and the updating of data in the database. As an always-
connected model, ResultSets keep a live connection to the database.
The following section has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
Typed ResultSet Features
Generated typed ResultSet objects provide type-safe access to the database table much like typed DataSets. Thus the
generated code ensures that the data passed between the application and database correctly matches the database schema at
compile time. Typed ResultSet-generated code extends the SQL Server Mobile Edition or SQL Server Compact Edition
ResultSet base class to provide the properties and methods specific to the targeted database table.
The following paragraphs summarize the features of the code generated for a typed ResultSet.
Constructors The generated typed ResultSet contains two constructors. The default constructor is used for both design-
time and basic run-time scenarios. The design time of Visual Studio requires the default constructor to make a
connection to the database that resides on the local development machine. Thus, the generated code contains a
connection string to the local SQL Server Mobile Edition or SQL Server Compact Edition database file. The default
constructor switches for run time to the local database file from the same directory as the executing application. This is a
basic run-time scenario.
Connection strings When the run-time scenario is more complex, such as when the SQL Server Mobile Edition or SQL
Server Compact Edition database file resides in a device location other than the executing directory, or the connection
string is varied in some other way, such as a password, then the overloaded constructor can be used. The overloaded
constructor takes two arguments: a custom connection string and a custom ResultSetOptions flag.
Connection property The connection property is the live SqlCeConnection object used by the typed ResultSet in
order to access the database data. The connection property is public and enables access to manage the state of the
connection for the typed ResultSet. For example, the connection may be required to be closed for some transactions.
Typed safe access to table columns The generated code creates a property accessor for each column in the datatable.
The property type is determined by mapping the underlying database type into a .NET Framework type. For example,
nvarchar is mapped into a .NET Framework string. The generated property supports both Get and Set accessors,
allowing you to pull and push data using .NET Framework strings instead of the nvarchar of the underlying database.
Each column also has an IsxxxDBNull and SetxxxDBNull method, where xxx is the column name, to facilitate getting
and setting DBNull into the database.
AddxxxRecord method (where xxx is the table name) This method enables new rows to be added to the database
table. AddxxxRecord method has one parameter for each column in the data table, except for auto-incremented
columns, which have their values assigned by the database engine. Each parameter is again declared as a .NET
Framework type, enabling easy use with the application and abstracting out the underlying database type. Update is not
required to be called after calling this method. Once called, the new row is committed to the database.
DeletexxxRecord method (where xxx is the table name) This method deletes the current row from the database.
Unlike DataSets, this transition is not cached, and once called, the row is deleted from the database. Update is not
required to be called after calling this method.
Bind method The bind method takes one parameter, a BindingSource, which is data-bound to one or more UI controls
on the form. This method then databinds the BindingSource to the instance of the typed ResultSet, completing the
databinding chain and enabling the controls to display the data directly in the database.
Note
The design-time scenario requires a hard-coded connection string to the SQL Server Mobile Edition or SQL Server Co
mpact Edition database. This connection string can get out of date when, for example, a project is shared from one deve
loper to another. As a result, the DataSource window or the Windows Forms Designer or both may fail to open the pr
oject. You can regenerate the typed ResultSet code to remedy this situation. In Solution Explorer, right-click the XSD s
chema file, and then click Run CustomTool.

See Also
Reference
SqlCeResultSet
Concepts
Resultsets vs. Datasets (Devices)
Other Resources
Data in Managed Device Projects
Smart Device Development

Managing Data Sources in Device Projects


The following sections describe how to implement common data tasks in device projects.
Note
The Data Source Configuration Wizard is not available for projects that target version 1.0 of the .NET Compact Framewor
k.

In This Section
How to: Create a Database (Devices)
How to: Change the Design-Time Connection String (Devices)
How to: Change the Run-Time Connection String (Devices)
How to: Manage Passwords for Databases (Devices)
How to: Shrink and Repair a Database (Devices)
How to: Add a Database to a Device Project
How to: Manage Tables in a Database (Devices)
How to: Manage Columns in a Database (Devices)
How to: Manage Indexes in a Database (Devices)
How to: Preview Data in a Database (Devices)
How to: Create Parameterized Queries (Devices)
How to: Create Master-Detail Applications (Devices)
How to: Add Navigation Buttons (Devices)
How to: Persist Data Changes to the Database (Devices)
How to: Generate SqlCeResultSet Code (Devices)
How to: Add a Business Object as a Data Source (Devices)
How to: Add a Web Service as a Data Source (Devices)
How to: Add a SQL Server Database as a Data Source (Devices)
How to: Generate Summary and Edit Views for Data Applications (Devices)
See Also
Concepts
Connecting to Data in Visual Studio Overview
Other Resources
SQL Server Mobile Edition Books Online Home Page
Data in Managed Device Projects
Smart Device Development

Using SQL Server Mobile Edition and SQL Server Compact


Edition Databases
This topic is new for Visual Studio 2005 SP1.
Visual Studio 2005 includes SQL Server Mobile edition which developers of Smart Devices could use when creating database
applications. Visual Studio 2005 Service Pack 1 enables developers to use Microsoft SQL Server 2005 Compact Edition, a new
version that also includes features for desktop developers. For smart device developers, SQL Server Compact Edition and SQL
Server Mobile Edition provide the same set of features.
However, in order to take advantage of the rich design time data features in Visual Studio Service Pack 1 you must write your
data application using SQL Server Compact Edition 3.1 and .NET Compact Framework 2.0. You must install both Visual Studio
SP1 and SQL Server Compact Edition Tools for Visual Studio 2005 SP1. For more information see,
How to: Install Sample Databases
The following table links to information that enables you to use the Visual Studio integrated development environment (IDE) to
effectively interact with databases.
Common Database Tasks
How to: Create a Database (Devices) How to: Generate Summary and Edit Views for Data Applications (Devices)

How to: Create Master-Detail Applications (Devices) How to: Manage Columns in a Database (Devices)

How to: Create Parameterized Queries (Devices) How to: Manage Passwords for Databases (Devices)

How to: Generate SqlCeResultSet Code (Devices) How to: Preview Data in a Database (Devices)

How to: Shrink and Repair a Database (Devices) How to: Add a Database to a Device Project

How to: Manage Tables in a Database (Devices) How to: Manage Indexes in a Database (Devices)

How to: Add Navigation Buttons (Devices) How to: Persist Data Changes to the Database (Devices)

See Also
Concepts
SQL Server Compact Edition with the .NET Compact Framework
Smart Device Development

How to: Create a Database (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following procedures have been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
You can create a SQL Server Mobile or SQL Server Compact Edition database whether you have a project open or not. If the
database is to become part of a project, consider creating it within the project as a data source for the project. Even if you
create the database outside a project, you can add it to a project later. For more information, see
How to: Add a Database to a Device Project.
Note
Two or more processes cannot simultaneously access the same SQL Server Mobile or SQL Server Compact Edition database
over a network share because the second process will cause a file-sharing violation error. However, a process can open multi
ple connections to the database. For example, the process can run an Insert query on one connection and a Select query on a
nother connection simultaneously. Use DB_MODE_SHARE_EXCLUSIVE file mode when opening a database file over a networ
k share. For more information, see How to: Set the File Mode When Opening a Database with OLE DB (Programmatically).

To create the database outside a project


1. On the View menu, click Server Explorer.
2. Right-click Data Connections, and then click Add Connection to open the Add Connection dialog box.
3. Click Change to open the Change Data Source dialog box.
4. In the Data source box, select Microsoft SQL Server Mobile Edition, and then click OK.
or
In the Data source box, select Microsoft SQL Server Compact Edition, and then click OK.
5. Select Microsoft SQL Server Mobile Edition or Microsoft SQL Server Compact Edition, and then click OK.
6. Continue with "To continue the process and configure the connection" below.

To create the database inside a project


1. With a project open, click Add New Data Source on the Data menu.
The Data Source Configuration Wizard opens.
2. On the Choose a Data Source Type page, select Database, and then click Next.
3. On the Choose Your Data Connection page, click New Connection to open the Add Connection dialog box.
4. Click Change to open the Change Data Source dialog box.
5. Select Microsoft SQL Server Mobile Edition or Microsoft SQL Server Compact Edition, and then click OK.
6. Continue with "To continue the process and configure the connection" below.
To continue the process and configure the connection
1. In the Add Connection dialog box, select My Computer.
2. Click Create.
3. In the Create New SQL Server 2005 Mobile Edition Database dialog box, type a fully qualified path for the new
database (for example, c:\MyDB).
or
In the Create New SQL Server 2005 Compact Edition Database dialog box, type a fully qualified path for the new
database (for example, c:\MyDB).
4. In the New Password and Confirm Password boxes, type a password (for example, MyPassword) as the password for
the new database, and then click OK.
Security Note
For projects that will be used in real-world applications, choose a strong password.

5. Click OK to return to the Add Connection dialog box.


6. In the Add Connection dialog box, click Test Connection to ensure that the connection has been made.
A message appears indicating that the test connection succeeded.
7. Click OK to return to the Add Connection dialog box, and then click OK to close it.
Complete the following steps only if you are creating a database and a dataset inside your project:
8. On the Choose Your Data Connection page, select Yes, include sensitive data in the connection string.
Security Note
For projects that will be used in real-world applications, you should choose to exclude sensitive data from the connecti
on string. At the very least, you should ensure that the sensitive data is encrypted.

9. Click Next.
The Local database file message box appears, inquiring whether you want to include your data file in your current
project.
Click Yes.
10. On the Choose Your Database Objects page, select the tables or other objects you want to include in your project.
11. Click Finish.
You can now view the new database as a dataset in the Data Sources window by clicking Show Data Sources on the
Data menu. To add tables, columns, constraints, and so on to the database, see
Managing Data Sources in Device Projects.

See Also
Tasks
How to: Install Sample Databases
Other Resources
Create Database Dialog (SQL Server Mobile)
Managing Data Sources in Device Projects
Smart Device Development

How to: Create Master-Detail Applications (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
The following steps assume you have a SQL Server Mobile or SQL Server Compact Edition database with table relationships
available in the Data Sources window. For more information, see How to: Create a Database (Devices).
When dragging detail tables, consider dragging only those columns that serve your purpose, rather than the entire grid. You
can make this choice by clicking the arrow at the right of the table name.
The following procedures assume that you have a device project open and a data source configured.
To create a master-detail application
1. Drag the master table from the Data Sources window onto the form in the designer.
2. In the Data Sources window, expand the master table to expose the detail table.
3. Drag the detail table that you find under the master table node onto the form.
Note
This is the detail table as it appears within the master table, not the detail table that is at the same tree level as the mast
er table.

The designer automatically detects the master-detail relationship from the foreign key constraints. For more information,
see Walkthrough: A Database Master-Detail Application.
4. Adjust the controls on the form to suit your application.
See Also
Tasks
Walkthrough: A Database Master-Detail Application
How to: Install Sample Databases
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Create Parameterized Queries (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following procedures have been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
The following steps assume you have a SQL Server Mobile or SQL Server Compact Edition database available in the Data
Sources window. For more information, see How to: Create a Database (Devices) or
How to: Add a Database to a Device Project.
When you want users to be able to enter different values for a parameter, use a question mark ("?") as the parameter when you
design your query. If you create your query using the smart tag on the Windows Forms designer, as shown in the following set
of steps, a user interface is automatically generated in the Windows Form. If you create your query from the TableAdapter in
the Dataset Designer, as shown in the last set of steps, no user interface is automatically generated.
To set up for specifying a parameter using the Windows Forms designer
1. Drag a table in Datagrid or Details format from the Data Sources window onto the form in the designer.
You can select the format by clicking the arrow at the right of the table name.
2. Click the smart tag on the dragged component, and then on the shortcut menu, click Add Query.
If you are not using a mouse, the keyboard shortcut to open the Tasks dialog box is Shift+Alt+F10.
3. In the Search Criteria Builder dialog box, select New query name.
Use the default name or create a name of your choice.
4. You can now specify your parameters by changing the SQL statement in the Query Text box or by clicking Query
Builder.
To specify a parameter using the Query Text box
1. Add a WHERE clause to the end of the SELECT statement.
2. Click OK to close the Search Criteria Builder dialog box.
A query-bound button is displayed on the form in the designer.
To specify a parameter using Query Builder
1. In the Query Builder dialog box, either:
Add a WHERE clause in the SQL Statement pane.
-or-
Enter your parameter under Filter in the appropriate Column listing.
This approach writes the WHERE clause for you in the SQL Statement pane.
2. Click OK to close the Query Builder dialog box.
3. Click OK to close the Search Criteria Builder dialog box.
A query-bound button is displayed on the form in the designer.
To specify a parameter using the Dataset Designer
1. In Solution Explorer, right-click the .xsd file, and then click Open.
2. In the Dataset Designer, right-click the TableAdapter, point to Add, and then on the shortcut menu, click Query.
3. In the TableAdapter Query Configuration Wizard, select Use SQL Statements, and then click Next.
4. On the Choose a Query Type page, select Select which returns a single value, and then click Next.
5. On the Specify a SQL SELECT statement page, click Query Builder.
If you want, you can add the WHERE clause here.
6. Use Query Builder as described earlier in this topic.
Note
No user interface elements are automatically generated when you create your queries using the TableAdapter Query
Configuration Wizard.

See Also
Tasks
How to: Add a Parameterized Query to a Form in a Windows Application
Walkthrough: A Parameterized Query Application
How to: Install Sample Databases
Reference
Search Criteria Builder Dialog Box
Concepts
Query and View Designer Tools
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Generate SqlCeResultSet Code (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following section has been updated for Visual Studio 2005 SP1.
The following steps assume you have a SQL Server Mobile or Microsoft SQL Server 2005 Compact Edition database available
in the Data Sources window. For more information, see How to: Create a Database (Devices) or
How to: Add a Database to a Device Project.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
In a device project, Visual Studio by default generates code for a dataset only. You can change this default value to generate a
resultset instead, or to generate both. For more information on the differences between the two types, see
Resultsets vs. Datasets (Devices).
The ResultSet and ResultSet/DataSet options are supported only for .xsd files created against SQL Server Mobile or SQL Server
Compact Edition connections. The dataset option is supported for all connections, and is the code generated by default.
Note
If you want to convert an existing dataset application to a resultset application, set the Custom Tool property to MSDataSet
ResultSetGenerator. This setting generates both types of data access classes. You can then migrate your code from one to t
he other without build errors. After you have migrated the code, set the Custom Tool property to MSResultSetGenerator.
Rebuild to confirm that all dataset usage has been removed from the code.

To generate code for Resultsets only


1. In Solution Explorer, right-click the database .xsd file, and then click Properties on the shortcut menu.
2. Set the Custom Tool value to MSResultSetGenerator.
3. Rebuild the solution.
To generate code for Datasets only
1. In Solution Explorer, right-click the database .xsd file, and then click Properties on the shortcut menu.
2. Set the Custom Tool value to MSDataSetGenerator.
This value is the default value.
3. Rebuild the solution.
To generate code for both Resultsets and Datasets
1. In Solution Explorer, right-click the database .xsd file, and then click Properties on the shortcut menu.
2. Set the Custom Tool value to MSDataSetResultSetGenerator.
3. Rebuild the solution.
See Also
Tasks
How to: Install Sample Databases
Concepts
Resultsets vs. Datasets (Devices)
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Generate Summary and Edit Views for Data


Applications (Devices)
This topic has been updated for Visual Studio 2005 SP1.
Use data forms to view and edit single rows of data in a datagrid.
The data form user interface consists of two dialog boxes: the View dialog box displays a summary view of a selected datagrid
row, and the Edit dialog box enables editing of the row.
You open the View dialog box in a running application by double-clicking a row in the datagrid on the Device Emulator
or tapping a row on a device.
You open the Edit dialog box by clicking (tapping) New when the datagrid is displayed—this action creates a new row in
the datagrid—or by clicking (tapping) Edit when the View dialog box is displayed.
Data forms are designed as templates for customization. You should add suitable code for validating and committing changes
to the database as part of this customization.
The changes made by using the data forms are not persisted in the database. For more information about how to persist those
changes, see How to: Persist Data Changes to the Database (Devices).
Note
This feature is supported only for data sources created against SQL Server Mobile, SQL Server Compact Edition, and Server
Database Datasets. It is not supported for Result Sets, Business Objects, or Web services.

The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
The following steps assume you have a SQL Server Mobile or SQL Server Compact Edition database available in the Data
Sources window. For more information, see How to: Create a Database (Devices). This topic also describes how to add an
existing SQL Server database as a data source to your project.
To generate the data forms
1. Drag a table in Datagrid format from the Data Sources window onto the form in the designer.
You can select the format by clicking the arrow at the right of the table name.
2. Click the smart tag on the dragged component, and then on the shortcut menu, select Generate Data Forms. (If you are
not using a mouse, the keyboard shortcut to open the Tasks dialog box is Shift+Alt+F10.)
Note
The dialog boxes are briefly displayed as they are generated in the designer. To verify that the dialog boxes are now par
t of the project, look for them in Solution Explorer.

To modify data in a running application


1. Launch the data application.
The datagrid is displayed, populated with data.
2. Double-click a row of data.
A summary view of that row appears in the View dialog box. This view consists of a label and data for each column that
has contents. That is, the View dialog box hides any column whose value is DBNULL.
3. On the main menu, click Edit to open the Edit dialog box.
Use the Edit dialog box, which displays all columns, to modify the data, and then click OK.
The revised data is displayed in the datagrid.
To create a new row in the datagrid in a running application
1. With a datagrid open, on the main menu, click New.
The Edit dialog box appears. Use this dialog box to add a new row of data.
2. Click OK.
The new row is added to the datagrid.
See Also
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Manage Columns in a Database (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following steps assume you have a SQL Mobile or Microsoft SQL Server 2005 Compact Edition database available in the
Server Explorer window. For more information, see How to: Create a Database (Devices).
The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
To add a column
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection to display its tables.
3. Right-click the table to which you want to add a column, and then click Edit Table Schema on the shortcut menu.
4. In the Edit Table window, add the column and its properties, and then click OK.
To edit column properties
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection to display its tables.
3. Right-click the table that contains the column whose properties you want to edit, and then click Edit Table Schema on
the shortcut menu.
4. Make your edits, and then click OK.
Note
You cannot make an edit that would violate referential integrity (for example, trying to change the Primary Key proper
ty to No when that column is referenced by another constraint).

To remove a column from a table


1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection to display its tables.
3. Right-click the table from which you want to remove the column, and then click Edit Table Schema on the shortcut
menu.
4. In the Edit Table window, select the column you want to delete, click Delete, and then click OK.
Note
You cannot remove a column until all references to the column are deleted.

See Also
Tasks
How to: Install Sample Databases
Other Resources
Column Properties
Managing Data Sources in Device Projects
Smart Device Development

How to: Manage Passwords for Databases (Devices)


This topic has been updated for Visual Studio 2005 SP1.
You can set a password when you create a database, and you can change the password in an existing database.
Security Note
Including a password in a connection string represents a security risk. For more information, see
Securing Databases (SQL Server Mobile).

The following sample steps assume you have a Pocket PC Windows Forms application open.
The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
To set a password when creating a database
1. On the Data menu, click Add New Data Source.
2. On the Choose a Data Source Type page, click Database, and then click Next.
3. On the Choose Your Data Connection page, click New Connection to open the Add Connection dialog box.
4. Click Change, click Microsoft SQL Server Mobile Edition, and then click OK.
or
Click Change, click Microsoft SQL Server Compact Edition, and then click OK.
5. In the Add Connection dialog box, click My Computer.
6. Click Create.
7. In the Create New SQL Server 2005 Mobile Edition Database dialog box, type a fully-qualified path for the new
database (for example, c:\MyDatabase.sdf).
or
In the Create New Microsoft SQL Server Compact Edition Database dialog box, type a fully-qualified path for the
new database (for example, c:\MyDatabase.sdf).
8. In the New Password and Confirm Password boxes, type a password for the new database, and then click OK.
To change a password in an existing database
1. On the View menu, click Server Explorer.
2. In Server Explorer, right-click the data source for which you want to change the password.
3. On the shortcut menu, click Database Properties.
4. In the Database Properties dialog box, click Set password.
5. Type the old and new passwords as prompted, and then click OK.
See Also
Tasks
How to: Create a Database (Devices)
Other Resources
Securing Databases (SQL Server Mobile)
Managing Data Sources in Device Projects
Smart Device Development

How to: Preview Data in a Database (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following procedures have been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
The following steps assume you have a SQL Server Mobile or SQL Server Compact Edition database available in the Server
Explorer window. For more information, see How to: Create a Database (Devices).
You can preview data outside a project using Server Explorer, or from within a project using the Data Sources window,
where you can also parameterize the query that produces the view. For more information, see
How to: Create Parameterized Queries (Devices).
To view data using Server Explorer
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection to expose the table listing.
3. Right-click the table whose data you want to view, and then on the shortcut menu, click Open.
To view data using the Data Sources window in a project
1. On the Data menu, click Show Data Sources.
2. In the Data Sources window, right-click the data source whose data you want to view (for example, a table).
3. On the shortcut menu, click Preview Data.
4. In the Data Preview dialog box, click Preview.
To view data using the smart tag on the datagrid control
1. In the designer, click the smart tag on the datagrid control.
2. On the DataGrid Tasks shortcut menu, click Preview Data.
3. In the Preview Data dialog box, select the object to preview, and then click Preview.
The data appears in the Results box. The number of columns and rows in the grid is also displayed at the bottom of the
Preview Data dialog box.
See Also
Tasks
How to: Install Sample Databases
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Add a Database to a Device Project


This topic has been updated for Visual Studio 2005 SP1.
The following steps assume you have a SQL Server Mobile Edition or SQL Server Compact Edition database available in the
Server Explorer window. For more information, see How to: Create a Database (Devices).
The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
To add a SQL Server Mobile Edition or SQL Server Compact Edition database as a data source
1. With a Smart Device project open, click Add New Data Source on the Data menu.
2. On the Choose a Data Source Type page, select Database, and then click Next.
3. On the Choose Your Data Connection page, select the data connection string that contains the name of your database,
and then click Next.
This connection should be displayed in the dropdown box if your database is already available in Server Explorer. If your
database connection does not appear in the list, click New Connection to open the Add Connection dialog box, click
Browse to open the Select Database File dialog box, navigate to your database, and then click Open. Then click OK to
close the Add Connection dialog box.
4. On the Choose Your Data Connection page, click Next.
The Local database file message box appears, inquiring whether you want to include your data file in your current
project.
Click Yes.
5. On the Choose Your Database Objects page, select the objects you want to use as data sources in your project.
6. Click Finish.
Objects you have selected from your SQL Server Mobile or SQL Server Compact Edition database are displayed as data
sources for your project in the Data Sources window. To open the window, click Show Data Sources on the Data
menu.
See Also
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Shrink and Repair a Database (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following steps assume you have a SQL Server Mobile Edition or SQL Server Compact Edition database available in the
Server Explorer window. For more information, see How to: Create a Database (Devices).
The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
To shrink and repair a database
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, right-click the data connection you want to shrink and repair, and then on the shortcut
menu, click Database Properties.
3. In the Select a page pane, click Shrink & Repair.
4. Choose among the options on the Shrink & Repair page.
The bottom of the page displays an explanation for the option you select.
5. Click OK to launch the selected shrink and repair option, or click Cancel to leave the database in its current condition.
See Also
Other Resources
Shrink & Repair
Managing Data Sources in Device Projects
Smart Device Development

How to: Manage Tables in a Database (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following steps assume you have a SQL Server Mobile Edition or SQL Server Compact Edition database available in the
Server Explorer window. For more information, see How to: Create a Database (Devices).
The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
To add a table
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection to which you want to add a table.
3. Right-click Tables, and then click Create Table.
4. In the New Table dialog box, type a table name in the Name box.
5. For the first column, enter values for Column Name, Data Type, Length, Allow Nulls, Unique, and Primary Key.
Continue for additional columns.
6. Click OK.
The new table is displayed in the list of tables for the data connection.
To edit an existing table schema
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection where the table schema to be edited is found.
3. Right-click the table to be edited, and then on the shortcut menu, click Edit Table Schema.
4. In the Edit Table <Tablename> dialog box, make the changes, and then click OK.
To remove a table
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection from which you want to drop a table.
3. Under Tables, right-click the table you want to delete, and then on the shortcut menu, click Drop Table.
4. In the Delete Objects dialog box, click Remove, and then click OK.
Note
You cannot remove a table until all references to the table are deleted.

See Also
Other Resources
New Table
Edit Table (SQL Server Mobile)
Table Properties
Managing Data Sources in Device Projects
Smart Device Development

How to: Manage Indexes in a Database (Devices)


This topic has been updated for Visual Studio 2005 SP1.
The following steps assume you have a SQL Server Mobile Edition or SQL Server Compact Edition database available in the
Server Explorer window. For more information, see How to: Create a Database (Devices).
The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
To create an index for a SQL Server Mobile Edition or SQL Server Compact Edition database
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data source in which you want to create a new index.
3. Expand the table for which you want the new index, and then right-click the Indexes folder.
4. On the shortcut menu, click Create Index.
5. In the New Index dialog box, type a name for the index, and then click Add.
6. In the Select Columns from <Table> dialog box, select the columns to be added to the index key, and then click OK.
7. Click OK to close the New Index dialog box.
To edit index properties in sort-order only
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection and table that contain the index whose properties you want
to edit.
3. Right-click the index, and then click Index Properties on the shortcut menu.
4. You can change the sort order in this dialog box.
You cannot change other index properties except by replacing the existing index with a new one.
To drop an index from a SQL Server Mobile Edition or SQL Server Compact Edition database
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, expand the data connection from which you want to drop an index.
3. Expand the table that has the index, expand Indexes, and then right-click the index to be dropped.
4. On the shortcut menu, click Drop Index.
5. In the Delete Objects dialog box, click Remove, and then click OK.
See Also
Other Resources
New Index
Index Properties (SQL Server Mobile)
Managing Data Sources in Device Projects
Smart Device Development

How to: Add Navigation Buttons (Devices)


Use these procedures to provide navigation buttons for viewing different rows in the data source. This technique works around
the lack of .NET Compact Framework support for the DataNavigator class of the .NET Framework.
The steps below, written in C# and relying on the Customers table of the Northwind database, assume you have a dataset or
resultset in the Data Sources window. For more information, see How to: Add a Database to a Device Project. In a real project,
you would include bounds checking, which is not shown in the code samples here.
To set up for adding navigation buttons
1. Drag and drop a table from the Data Sources window onto a Windows Form.
2. Drag and drop a button onto the form.
3. Set the Text property of the button appropriately (for example, "Next").
4. Double-click the button on the form to open the code editor at the button click event handler.
5. Use the following code examples to code First, Next, Previous, and Last button event handlers.
To code a First button
Type this.customersBindingSource.MoveFirst();

To code a Next button


Type this.customersBindingSource.MoveNext();

To code a Previous button


Type this.customersBindingSource.MovePrevious();

To code a Last button


Type this.customersBindingSource.MoveLast();

See Also
Tasks
How to: Generate SqlCeResultSet Code (Devices)
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Persist Data Changes to the Database (Devices)


Use these procedures to persist changes made to data in device projects.
The steps below, written in C# and relying on the Customers table of the Northwind database, assume you have a dataset (not
any other sort of data source) in the Data Sources window. For more information, see
How to: Add a Database to a Device Project.
To persist data changes to the database
1. Drag a table from the Data Sources window onto a Windows Form.
2. Drag a button onto the form.
3. Change the Text property of the button to Save.
4. Double-click the button on the form to open the code editor at the button click event handler.
5. Type the following code:

this.customersBindingSource.EndEdit();
this.customersTableAdapter.Update(this.northwindDataSet.
Customers);

See Also
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Change the Design-Time Connection String (Devices)


This topic has been updated for Visual Studio 2005 SP1.
A design-time connection string is created by default when you create a SQL Server Mobile Edition or SQL Server Compact
Edition data source for your project. Visual Studio uses this string to connect to the database at design-time to retrieve schema
information. During the course of project development, you might want to change this string.
Security Note
Including a password in a connection string represents a security risk. For more information, see
Securing Databases (SQL Server Mobile).

Note
Distinguish this string from the run-time connection string. For more information, see
Connection String Property, File Properties Dialog Box (Devices).

The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
To change the design-time connection string
1. In Solution Explorer, double-click the .xsd file to open the DataSet Designer.
2. Right-click the TableAdapter, and then click Properties on the shortcut menu.
3. Expand the Connection property.
4. Type a new value for ConnectionString.
See Also
Tasks
How to: Edit a Connection String
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Change the Run-Time Connection String (Devices)


When you add a data source to a project, a connection string is generated in the .xsd file. This string is considered a design-
time connection string, suitable for connecting Visual Studio to the data source at design time. This same connection string
serves as the default run-time connection string.
If you need a different connection string when the application runs on a device, you can specify the run-time string using the
following steps. For more information, see Connection String Property, File Properties Dialog Box (Devices).
Security Note
Including a password in a connection string represents a security risk. For more information, see
Securing Databases (SQL Server Mobile).

To change the run-time connection string


1. In Solution Explorer, select the .xsd file.
2. On the View menu, click Properties Window.
3. Type a run-time connection string for the Connection String property.
See Also
Tasks
How to: Change the Design-Time Connection String (Devices)
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Add a Business Object as a Data Source (Devices)


You can add a business object as a data source in your smart device projects. For more information, see Visual Database Tools.
To create a new data source from an object
1. On the Data menu, click Add New Data Source.
2. On the Choose a Data Source Type page, select Object.
3. On the Select an Object you wish to bind to page, select an object already in your application.
Note
You might need to build the project that contains your object before the object appears in the wizard. You can also add
a reference to an object not currently in your application by clicking Add Reference and locating the desired assembly
in the Add Reference Dialog Box. The assembly is added to the tree view.

4. Expand the assembly that contains the object you want to bind to, and then select the object in the tree view.
5. Click Finish.
The data source is added to the Data Sources window.

To add a data source to your form


1. On the Data menu, click Show Data Sources to open the Data Sources window.
2. Select items in the Data Sources window, and drag them onto a Windows Form to create controls bound to the
properties in your object. For more information, see Displaying Data Overview.
See Also
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Add a Web Service as a Data Source (Devices)


You can add a Web service as a data source in your smart device projects.
To connect your application to a Web service
1. On the Data menu, click Add New Data Source.
2. On the Choose a Data Source Type page, select Web Service, and then click Next.
3. Add a reference to the desired Web service using the Add Web Reference Dialog Box.
4. Click Finish.
The data source is added to the Data Sources window.
To add a data source to your form
Select items in the Data Sources window and drag them onto a Windows Form to create bound controls. For more
information, see Displaying Data Overview.
See Also
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

How to: Add a SQL Server Database as a Data Source (Devices)


You can use SQL Server databases as data sources in your managed device projects.
To add a SQL Server data connection to Server Explorer
1. On the View menu, click Server Explorer.
2. In the Server Explorer window, right-click Data Connections, and then click Add Connection on the shortcut menu.
3. In the Add Connection dialog box, click Change.
4. In the Change Data Source dialog box, select Microsoft SQL Server, and then click OK to reopen the Add Connection
dialog box.
5. In the Server name box, specify the name of the server where the data source is located.
6. Log on to the server.
If the server uses SQL Server Authentication, you need to provide a user name and password.
7. In the Select or enter a database name box, select or type the name of the database, and then click OK.
The new data connection is displayed in Server Explorer.
To use a SQL Server data connection as a data source in a project
1. Prerequisite: You must have a .NET Compact Framework smart device project already open in the Visual Studio IDE.
2. On the Data menu, click Add New Data Source to open the Data Source Configuration Wizard.
3. On the Choose a Data Source Type page, select Database, and then click Next.
4. On the Choose Your Data Connection page, click New Connection.
5. In the Add Connection dialog box, click Change.
6. In the Change Data Source dialog box, select Microsoft SQL Server, and then click OK to reopen the Add Connection
dialog box.
7. In the Server name box, type or select the name of the server where the data source is located.
8. Log on to the server.
If the server uses SQL Server Authentication, you need to provide a user name and password.
9. In the Select or enter a database name box, select or type the name of the database, and then click OK.
10. In the Choose Your Data Connection page, choose to exclude sensitive data from the connection string, and then click
Next.
Security Note
Including sensitive data in the connection string poses a security risk.

11. On the Choose Your Database Objects page, select the objects you want to use as data sources, and then click Finish.
The data connection now appears as a data source in the Data Sources window.
See Also
Other Resources
Managing Data Sources in Device Projects
Smart Device Development

Walkthrough: Creating a Simple Application


This walkthrough demonstrates how to use Visual Studio 2005 to create a simple Smart Device Project, using either Visual C#
or Visual Basic. The walkthrough also demonstrates how to run the application on your PC in the emulator, or on an actual
device connected to your PC.
Note
To install a finished application permanently on an actual device, you must first package it into a CAB file. For more informati
on, see Walkthrough: Packaging a Smart Device Solution for Deployment.

Note
Options available in dialog boxes and menu commands differ depending on your development settings. This Walkthrough w
as written using Visual Basic Development Settings and Visual C# Development Settings. To view or change your settings, ch
oose Import and Export Settings on the Tools menu, click Reset IDE Settings, select the setting you want, and then click
Reset Settings.

This walkthrough consists of four main tasks:


Choosing a target device.
Creating a device project.
Adding a button and event handler to the form.
Running the application on the target device.
Choosing a Target Device
You can perform this walkthrough targeting either an emulator or a physical device. You can even switch back and forth during
the walkthrough. To ensure that you are prompted to select a device each time you deploy your solution, complete the
following procedure.
To prompt for device choices at deployment time
1. On the Tools menu, click Options, click Device Tools, and then click General. If Device Tools is not visible, select
Show all settings at the bottom of the Options dialog box.
2. Select the Show device choices before deploying a device project check box.
Creating a Device Project
In this section, you build a simple Windows Forms application. The following procedures include creating a Windows Forms
project, adding a control to the form, adding event handling for the control, and finally building and testing the application. The
steps to create a C++ project are not given here. If you are developing in C++, create a basic Hello World application, build a
release version, and skip to the section called "To build, test, and save the application."
To create a device project
1. (Visual Basic) On the File menu in Visual Studio, click New Project.
—or—
(Visual C#) On the File menu in Visual Studio, point to New, and then click Project.
2. Under Project Types in the New Project dialog box, expand Visual Basic or Visual C#, expand Smart Device, and
then click Pocket PC 2003.
If the language you want is not displayed at first, expand Other Languages. This display is governed by your profile
settings.
3. Under Templates, click Device Application.
4. In the Name box, type AppForDeployment.
5. (Visual C# only) In the Location box, verify where you want to store your project files.
6. Click OK.
A representation of a Pocket PC device appears in the Windows Forms Designer.
To add a control to the form
1. From the Toolbox, drag a Button control onto the form.
If the Toolbox is not visible, click Toolbox on the View menu.
If the Device Controls tab is not visible in the Toolbox, right-click the Toolbox and select Show All, or select Reset
Toolbox.
2. Right-click the Button control, and then click Properties.
3. In the Properties window, type Say Hello, and press ENTER to set the Text property.
To add event handling for the Button control
1. Double-click the button on the form.
The Code Editor opens with the insertion point positioned in the event handler.
2. Insert the following Visual Basic code:

MessageBox.Show("Hello, World!")

—or—
Insert the following C# code:

MessageBox.Show("Hello, World!");

To build, test, and save the application


1. On the Debug menu, click Start.
2. In the Deploy dialog box, select Pocket PC 2003 SE Emulator, and then click Deploy.
Progress messages appear in the Output window, on the Status bar, and on the emulator screen.
3. When the application is running on the emulator, tap the Say Hello button to ensure that "Hello, World!" is displayed.
4. On the emulator File menu, click Exit to close the emulator before proceeding to the next section of this walkthrough.
5. In the Device Emulator dialog box, click No in response to the Save State Before Exiting prompt.
6. On the Visual Studio File menu, click Save All.
If the emulator has not shut down entirely, the prompt Do you want to stop debugging? is displayed. Click Yes.
7. In the Save Project dialog box, save the AppForDeployment project to a location of your choice.
See Also
Other Resources
Programming for Devices Using the .NET Compact Framework
Smart Device Development

Programming for Devices Using Visual C++


Visual Studio 2005 provides support for developing device applications with Visual C++.
In This Section
What's New in Developing Visual C++ Device Applications
Provides information about new features in Visual C++ for Devices.
Creating and Porting Visual C++ Device Projects
Explains how to create a new Visual C++ device project and how to port existing Visual C++ desktop projects and eMbedded
Visual C++ 4.0 projects into a Visual C++ device project.
Developing Visual C++ Device Projects
Describes how to use the features of Visual Studio 2005 to develop a device application using Visual C++.
Building and Debugging Visual C++ Device Projects
Explains how to build and debug a Visual C++ device project.
See Also
Other Resources
Smart Device Development
Mobile Developer Center
Smart Device Development

What's New in Developing Visual C++ Device Applications


Visual Studio 2005 includes device development in Visual C++. Previously, developing device projects with Visual C++
required a version of eMbedded Visual C++. The new features detailed in the following sections are improvements over
eMbedded Visual C++.
Integrated Development Environment (IDE)
Target Multiple Operating Systems
The Visual Studio 2005 toolset provides the ability to target Pocket PC 2003, Smartphone 2003, custom Windows CE 5.0-
based SDKs, and future SDK releases.
Project System
The project system now associates platforms with their supported CPU architectures. Previous versions of eMbedded Visual
C++ allowed the selection of a CPU architecture that was not supported by the current active project.
IntelliSense
In Visual Studio 2005, IntelliSense reflects across the Software Development Kit (SDK) header files to provide accurate
information about the targeted platform.
Mixed Mode Solutions
Visual Studio 2005 enables device developers to have both managed, Visual C# or Visual Basic, code and unmanaged, Visual
C++, code in the same solution. It will also enable desktop and device Visual C++ code to be in the same project.
Application Install
Allows developers to package their device applications and create a desktop installer to distribute the applications to devices.
Custom Application and Class Wizards
Visual Studio 2005 makes it easy to write application and class wizards for device projects.
Resource Editor
The Resource Editor includes device-specific resources, such as the State of Input Panel and CAPEdit controls.
Debugging
The Visual Studio 2005 C++ device debugger has the following new features or improvements:
Improved robustness and performance over previous device application debuggers.
The ability to detach and re-attach to processes.
The ability to attach to a process without the executable.
Support for breakpoints in shared DLLs.
Multiple process debugging.
Improved expression evaluation, including more expressive debugger windows.
Compilers
The Visual Studio 2005 C++ device compilers have the following new features or improvements:
Support for /LTCG (Link-time Code Generation).
Increased compiler limits.
/GS switch support for buffer overrun detection.
Support for the __restrict keyword.
Updates to conform to a higher percentage of C++ standards.
Libraries
The Visual C++ libraries for devices have the following new features or improvements:
Microsoft Active Template Library (ATL) for devices and Microsoft Foundation Classes (MFC) for devices have been
updated to the 8.0 code base.
Extensive security, performance, stability and standards compliance work in MFC for devices, ATL for devices, the C run-
time (CRT) library for devices, and the standard C++ library for devices.
Common ATL and MFC functionality has been merged.
Stream support has been added to the standard C++ library for devices.
ATL
The following features have been added to ATL for devices:
ActiveX control hosting.
The ability to consume Web services.
Bitmap support with the CImage class.
New classes for managing arrays, lists and trees.
Enhanced string manipulation and conversion.
Extended Socket support for IPv6.
MFC
The following features have been added to MFC for devices:
Now available for Smartphone.
ActiveX control hosting and creation.

See Also
Other Resources
Programming for Devices Using Visual C++
Smart Device Development

Creating and Porting Visual C++ Device Projects


This topic has been updated for Visual Studio 2005 SP1.
Visual Studio 2005 provides many ways to start a C++ device project. This section includes topics on creating new Visual C++
device projects, and allowing existing projects to target devices in the Visual Studio 2005 environment.
The following table has been updated for Visual Studio 2005 SP1.
In This Section
How to: Create a New Visual C++ Device Project
Describes how to create new ATL, MFC, and native Windows CE application projects.
eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard
Describes how to import a project written in eMbedded Visual C++ 3.0 and 4.0 to Visual Studio 2005 using the upgrade
wizard.
Known Issues With Porting From eVC
Describes what to look for when migrating a project written in eMbedded Visual C++ 3.0 and 4.0 to Visual Studio 2005.
Device Support for Desktop Projects
Describes how to set up a desktop C++ project to target a device.
Target Multiple Platforms in Native Device Projects
Describes two approaches to targeting multiple platforms from a single project.
Resource Editing in Native Device Projects
Describes how closely the Resource editors for devices resemble their desktop counterparts.
Limitations After Creating Native Device Projects
Describes limitations if you add an additional platform after project creation.
How to: Add a Database to a Native Device Project
Describes how to develop a SQL Server Mobile or SQL Server Compact Edition device application using Visual C++.
Related Sections
Programming for Devices Using Visual C++
How to: Create a New Visual C++ Device Project
Known Issues With Porting From eVC
Developing Visual C++ Device Projects
Building and Debugging Visual C++ Device Projects
Smart Device Development

How to: Create a New Visual C++ Device Project


There are a couple of significant differences between creating device projects and creating desktop projects:
A subset of the desktop project templates is supported for devices. You can see these templates when you perform the
following procedure.
In the application wizard of the project you choose to create, you will need to select one or more platforms to target from
the list provided on the Platform page of the wizard. This platform list is generated based on the SDKs that you currently
have installed.
Note
If the compiler issues a warning about defining CE_ALLOW_SINGLE_THREADED_OBJECTS_IN, define_CE_ALLOW_SINGLE_THR
EADED_OBJECTS_IN_MTA, define the flag in stdafx.h. To do so, open stdafx.h header file and add #define _CE_ALLOW_SING
LE_THREADED_OBJECTS_IN_MTA near the top of the file.

To create a Visual C++ device project


1. On the File menu, point to New, and click Project.
2. In the Project Types pane, expand Visual C++, and then click Smart Device.The Templates pane displays all of the
supported project templates for devices.
3. Click the project template that you want to use.
4. In the Name box, type a name for your project, and click OK.
5. Use the application wizard to finish creating your project.
See Also
Tasks
Creating Projects with Application Wizards
Other Resources
Creating and Porting Visual C++ Device Projects
Smart Device Development

eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard


Visual Studio 2005 features an upgrade wizard to migrate eMbedded Visual C++ 3.0 and eMbedded Visual C++ 4.0 projects
to Visual Studio 2005.
The upgrade wizard will:
Create a Visual Studio 2005 solution and project or projects with your source code, headers, and resources migrated
from eMbedded VC++.
Add MFC dll to deploy list for migrated MFC projects.
Migrate project settings, such as compiler switches.
Map any architectures that were supported in eVC but not in Visual Studio 2005 to architectures that are supported in
Visual Studio 2005.

Using the eVC to Visual Studio 2005 Upgrade Wizard


To use the upgrade wizard to migrate an eVC project to Visual Studio 2005
1. On the File menu, click Open, and then click Project/Solution.
2. Navigate to the directory your eVC project is in. If your eVC workspace only has one project, you can select either the
.vcw or the .vcp file If your eVC workspace has more than one project, and you wish to migrate all the projects, select the
.vcw file.
3. Click OK.
Note
The migration wizard performs an in-place migration process; for example, no copies of your source code will be created, onl
y the Visual Studio 2005 project or projects. The Visual Studio 2005 projects created as a result of the migration will include t
he same source files that your original eVC project included.

Mapping Architectures
eMbedded Visual C++ supported some device architectures that are no longer supported in Visual Studio 2005. This is
because the newer platforms that Visual Studio 2005 targets support newer architectures. Fortunately, all the older
architectures can be mapped to the newer device architectures. The upgrade wizard performs this mapping automatically for
you. The table illustrates eMbedded Visual C++ supported device architectures versus Visual Studio 2005 supported device
architectures:
eVC Architecture Compatible Visual Studio 2005 Architecture
ARM ARMv4

ARMv4 ARMv4

ARMv4i ARMv4i

ARMv4T ARMv4i

MIPS MIPSII

Mips16 MIPSII

MipsII MipsII

MipsII_fp MipsII_fp
MipsIV MipsIV

MipsIV_fp MipsIV_fp

SH3 SH4

SH4 SH4

Emulator X86

X86 X86

When the eVC project is upgraded using the wizard, the new project created in Visual Studio 2005 targets all the installed SDKs
that support the architecture in the new project. Migrated architectures inherit their settings from one of the eVC architectures.
The following table illustrates the mapping of eMbedded Visual C++ supported device architectures versus Visual Studio 2005
supported device architectures.
Original Architecture Map to Notes
Not ARM/ARMV4/ARMV4 See table in “Mapping Architectures
I ”

ARM but no ARMV4i ARMV4 and ARMV4i ARMV4i config settings inherit from the ARM config in eVC.

ARMV4 but no ARMV4i ARMV4 and ARMV4i ARMV4i config settings inherit from the ARMV4 config in eVC.

ARM/ARMV4 and ARMV4i ARMV4 and ARMV4i ARMV4i config settings inherit from the ARMV4i config in eVC
.

Embedded Visual C++ version 4.0, by default, sets dialog box style to DS_MODALFRAME for MFC Pocket PC applications. In MFC
8.0 this style is not supported.
Note
If you receive an error message that says "No platforms are available that match this project file's original platforms," you m
ay need to install a compatible version of the SDK with which the original project was configured.

See Also
Reference
Windows Mobile Platform Migration FAQ for Developers
Migrating Microsoft eMbedded Visual C++ Projects to Visual Studio 2005
Step by Step: Migrating an eMbedded Visual C++ Application to Visual Studio 2005
Concepts
Known Issues With Porting From eVC
Smart Device Development

Known Issues With Porting From eVC


A number of C++ tools and resources are available to help you convert your existing Embedded Visual C++ projects to Visual
Studio 2005. For more information, see eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard.
The Active Template Library (ATL), Microsoft Foundation Classes (MFC), and standard C++ libraries have been updated and
changed since eVC. Some classes are not supported anymore. See List of eVC Classes Not Supported from MFC 3.0 to 8.0.
Code that calls these classes needs to be modified to compile in Visual Studio 2005. The following issues commonly arise
when porting from eVC.
Issue Description/Workaround
The CCeSocket::OnReceive() method does not get called in The resolution is detailed at:
MFC for devices newer than CE 3.0. http://support.microsoft.com/default.aspx?scid=kb;en-us;253945
.

The CArchive Class class is not supported. Many eVC projects contain references to CArchive Class class. T
o work around this, you need to remove references to CArchive.

Certain collection classes including CObArray, CMapPtrToPtr, To work around this difference in implementation, change your I
and so on, are implemented in CE 5.0 using templated versio MPLEMENT_SERIAL macro to use CObject instead of CObArray,
ns of CArray<>, CMap<>, and so on. In Embedded Visual C CMapPtrToPtr, and so on.
++ version 4.0 and in desktop C++ libraries, these types are
implemented as regular, non-templated classes. Therefore, c In other words, do not write this:
alling IMPLEMENT_SERIAL on these templated classes cause IMPLEMENT_SERIAL(CYourClass, CObArray, 0)
s a compilation error: Use this instead:
error C2039: 'classCObArray' : is not a member of 'CArray<T IMPLEMENT_SERIAL(CYourClass, CObject, 0)
YPE,ARG_TYPE>'
error C2065: 'classCObArray' : undeclared identifier

Embedded Visual C++ version 4.0, by default, sets dialog style to DS_MODALFRAME for MFC Pocket PC applications. In MFC
8.0, this style is not supported.
Examples
This section outlines some of the more common errors that you may encounter when you migrate your project from
eMbedded Visual C++ to Visual Studio 2005. For more information, see
Migrating Microsoft eMbedded Visual C++ Projects to Visual Studio 2005.
Compile error: Cannot open include file 'wceres.rc'
Right-click the project resource (RC) file, select View Code, and then comment out the following line:

//#include "wceres.rc"

NUM_TOOL_TIP not defined


In your header file, define #define _WIN32_WCE_PSPC for your Pocket PC configurations and _WIN32_WCE_WFSP for your
Smartphone configurations.
Cannot open file OLDNAMES.lib
In Solution Explorer, right-click the project file, and click Properties.
Click Linker. Edit the Ignore Specific Library property by adding OLDNAMES.LIB.
Ambiguous Overload
Standard C++ Library (SCL) and ATL have APIs that also exist in the device SDK. Disambiguate with a namespace, such as
::.
Module Machine type 'THUMB' conflicts with target machine type 'ARM
In Solution Explorer, right-click the project file, and select Properties.
Under Configuration Properties, expand Linker, and then click the Command Line property. Remove the
/MACHINE:THUMB switch from the command line for each Windows Mobile 5.0 configuration in the Property pages.
Resource String not separated properly
You may experience an issue where resource strings from ported applications are not being separated properly. In
Solution Explorer, right-click the project file, and click Properties. Under Configuration Properties, expand
Resources, and then select the Command Line property. Add an -n switch to the resource compiler command line.
BEGIN expected in dialog error
This error is usually followed by File not found errors, such as "file not found: 0x1". Go to the RC file that is indicated by
the error, and edit the code to use a #ifdef statement around the FONT declaration as shown in the following code
example.
Original code:

IDD_COMPTEST DIALOGEX 0, 0, 186, 95


STYLE DS_SETFONT | WS_CHILD
EXSTYLE WS_EX_CONTROLPARENT
FONT 8, "MS Sans Serif", 0, 0, 0x1
BEGIN
END

Modified code:

IDD_COMPTEST DIALOGEX 0, 0, 186, 95


STYLE DS_SETFONT | WS_CHILD
EXSTYLE WS_EX_CONTROLPARENT
#ifdef _WIN32_WCE
FONT 8, "MS Sans Serif"
#else
FONT 8, "MS Sans Serif", 0, 0, 0x1
#endif
BEGIN
END

See Also
Concepts
eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard
Other Resources
Windows Mobile Platform Migration FAQ for Developers
Smart Device Development

Device Support for Desktop Projects


Visual Studio 2005 supports having a project that targets multiple platforms, including desktop as well as smart device
platforms such as Pocket PC and Smartphone devices. You can use the C++ Class Wizards for Device Projects to create a
device project in the same solution as the desktop project. For more information, see C++ Class Wizards for Device Projects.
You can then port the desktop application to your newly created device project using the following resources:
Using Code Wizards with Device Projects
How to: Create a New Visual C++ Device Project
Target Multiple Platforms in Native Device Projects
Resource Editing in Native Device Projects
Building and Debugging Visual C++ Device Projects
Resource Editors for Device Projects
Debugging Device Projects
Packaging Device Solutions for Deployment
Using Resources on Multiple Platforms.
See Also
Reference
Visual Basic Language Reference for Devices
Concepts
.NET Compact Framework Reference for Device Projects
Standard C++ Library Reference for Devices
C Run-Time Library Reference for Devices
Other Resources
ATL Reference for Devices
MFC Reference for Devices
Smart Device Development

Target Multiple Platforms in Native Device Projects


Using Visual Studio 2005 you can create a single device project that targets multiple device platforms, such as Pocket PC 2003
and Smartphone 2003.
There are two ways that you can set your device project to target multiple platforms:
With the application wizards at the time of project creation. This is the easier method. For more information, see
How to: Create a Multiplatform Device Project Using the Wizard.
After you create your project. For more information, see How to: Add a New Platform to a Device Project.
If you select multiple platforms on the Platforms page in the application wizard of your project, a resource file will be
generated and configured for each of your platforms. However, if you add a platform after you create your project, you will
need to manually add a platform and resource file. For more information, see Using Resources on Multiple Platforms.
See Also
Tasks
Creating Projects with Application Wizards
Concepts
MFC for Windows CE Wizards C++
Other Resources
Creating and Porting Visual C++ Device Projects
Smart Device Development

Resource Editing in Native Device Projects


Because of the multiplatform nature of Visual Studio 2005, a separate resource file is generated for each platform you choose
to include, such as Pocket PC and Smartphone. The Resource editors for device projects are almost identical to the Resource
editors for desktop projects. Every editor is supported, and only the Dialog editor has any significant changes. For more
information, see Using the Resource Editors for Device Projects and Resource Editors.
You can target all platforms at project creation time; this makes it easy to customize the UI of your application to suit the device
form factors and allows you to maintain one project for your multiplatform application. The sample project created in
Walkthrough: Creating a Multiplatform MFC Application for Smart Devices has both a Pocket PC resource file and a
Smartphone resource file. Note that the Smartphone resource file has a No Build icon on it because the current active
configuration for the project is Pocket PC 2003 (Armv4). You can change the active configuration to Smartphone 2003
(ArmV4) using the Configuration Manager Settings, Smart Device Project Wizard. This will remove the No Build icon from the
Smartphone 2003 resource file, and the icon will appear on the Pocket PC 2003 (Armv4) resource file instead.
See Also
Other Resources
Creating and Porting Visual C++ Device Projects
Smart Device Development

Limitations After Creating Native Device Projects


This section lists the limitations that apply to native C++ applications for Smart Devices, compared to native applications for
the desktop.
Differences Between Desktop and Device Native Projects
For more information about creating C++ device projects, see C++ Class Wizards for Device Projects.
For filtering Help topics and references, see How to: Optimize Help for Smart Device Development.
For user interface differences between projects, see User Interface Reference for Devices
For developing ATL device projects, see Differences Between ATL for Devices and Standard ATL.
For developing MFC device projects, see Differences Between MFC C++ for Devices and Standard MFC and
Unique MFC for Devices Classes.
For C++ device development, see Standard C++ Library Reference for Devices.
For using resources with device projects, see Using Resources on Multiple Platforms.
For compiler switches, see Compilers for Smart Devices.
For debugging device projects, see Debugging Device Projects
For packaging device projects, see Packaging Device Solutions for Deployment
See Also
Tasks
How to: Find Help for ATL Classes and Methods Supported for Devices
How to: Find Help for MFC Classes and Methods Supported for Devices
Concepts
eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard
Other Resources
Creating and Porting Visual C++ Device Projects
Smart Device Development

How to: Add a Database to a Native Device Project


This topic has been updated for Visual Studio 2005 SP1.
You can develop smart device applications that use SQL Server Mobile Edition or SQL Server Compact Edition by using the
Visual Studio development environment.
For instructions about developing a SQL Server Mobile Edition or SQL Server Compact Edition application using Visual C++
for Devices, see Installing a Development Environment.
When using SQL Server Mobile Edition or SQL Server Compact Edition in your native project, installation CAB file is not
automatically downloaded to the device when you deploy the project. You can add the CAB file to your project.
The following procedure has been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
To add the SQL Server Mobile Edition or SQL Server Compact Edition CAB file to your project
1. Right-click the project, and on the Project shortcut menu, click Add Existing Item.
2. Navigate to the CAB file.
By default, the cab files are located at %Program Files%\Microsoft Visual Studio 8\SmartDevices\SDK\SQL
Server\Mobile\v3.0\wce500\<device processor>\.
-or
3. Copy the CAB file to the smart device.
By default, the cab files are located at %Program Files%\Microsoft Visual Studio 8\SmartDevices\SDK\SQL
Server\Mobile\v3.0\wce500\<device processor>\.
4. Install SQL Server Mobile Edition or SQL Server Compact Edition by running the CAB file on the device.
See Also
Other Resources
Creating and Porting Visual C++ Device Projects
Smart Device Development

Developing Visual C++ Device Projects


This section contains topics that describe the unique aspects of developing a device application.
In This Section
Switching Platforms in Device Projects
Describes how to switch targets using the same project.
C++ Class Wizards for Device Projects
Provides information on how to use C++ wizards for device projects.
Resource Editors for Device Projects
Provides information on the Resource Editors for device projects.
Compilers for Smart Devices
Describes the compilers that target microprocessors used in smart devices.
Code Explanation: Wizard-Generated Code in Visual C++ Device Projects
Describes the code generated by Visual C++ wizards in device projects.
How to: Specify the Remote Path for Primary Project Output
Describes how to specify where on the target device your project will be deployed.
How to: Change the Default Device (Native Projects)
Describes how to change the default target for native projects.
See Also
Reference
Welcome to Windows Mobile
Other Resources
Programming for Devices Using Visual C++
Smart Device Development

Switching Platforms in Device Projects


You can easily switch the target platform. For example target a Pocket PC 2003 platform or a Smartphone platform using the
same project.
To create a project targeting multiple platforms in Visual C++, see:
Target Multiple Platforms in Native Device Projects
Configuration Manager Settings, Smart Device Project Wizard.
For information on setting the target platform in Configuration manager, see:
How to: Create a Multiplatform Device project (Visual C++)
Configuration Manager Settings, Smart Device Project Wizard.
For additional information on working with resources multiple platforms in a Visual C++ project, please see
Using Resources on Multiple Platforms.
See Also
Concepts
eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard
Known Issues With Porting From eVC
Other Resources
Smart Device Development
Smart Device Development

C++ Class Wizards for Device Projects


Visual C++ device projects support a subset of the class wizards that are supported for desktop Visual C++ projects. Some
wizards are not supported for device projects due to differences in the Windows and Windows CE platforms. For more
information, see Adding Functionality with Code Wizards.
In This Section
Using Code Wizards with Device Projects
Describes which C++ class wizards are supported, and how to access them.
Wizard Options in Native Device Projects
Provides links to topics describing the unsupported wizard options on specific C++ class wizards.
Unsupported Options in the Project Properties Dialog Box
Describes behavior that differs from desktop projects in the Project Properties dialog box.
Not all Smart Device Native application wizards give you the choice of both static linking and dynamic linking. The following
table outlines the behavior of the Smart Device Application Wizards with respect to runtimes linking:
Wizard Notes
Win32 Smart Device Project – Windows Applicati Static link. No option to dynamic/static link provided at project creation time
on

Win32 Smart Device Project – Console Applicatio Static link. No option to dynamic/static link provided at project creation time
n

Win32 Smart Device Project – DLL Static link. No option to dynamic/static link provided at project creation time

Win32 Smart Device Project – Static Library Static link. No option to dynamic/static link provided at project creation time

ATL Smart Device Project – DLL Static link. No option to dynamic/static link provided at project creation time

ATL Smart Device Project – EXE Static link. No option to dynamic/static link provided at project creation time

MFC Smart Device Application – SDI Static link. No option to dynamic/static link provided at project creation time

MFC Smart Device Application – SDI w. DocList Static link. No option to dynamic/static link provided at project creation time

MFC Smart Device Application – Dialog based Static link. No option to dynamic/static link provided at project creation time

MFC Smart Device DLL – Regular DLL Static link. No option to dynamic/static link provided at project creation time

MFC Smart Device ActiveX Control Static link. No option to dynamic/static link provided at project creation time

MFC Smart Device DLL – Extension DLL Dynamic link. No option to dynamic/static link provided at project creation t
ime

The above table refers to deployment using the F5 shortcut key. The application installation is as described in this section:
When creating a Smart Device CAB project for your application written in C++, you must manually add any
dependencies such as atl80.dll, mfc80U.dll, and/or msvcrt.dll) to the CAB project if you are dynamically linking to
these DLLs. If you are dynamically linking, and need to redistribute the DLLs in the cab, do not install the DLLs to the
system directory such as \windows on the device. Instead, install the DLLs into the local application directory. If you are
redistributing a suite of applications, all of which dynamically link to the ATL/MFC runtimes, it is recommended to install
all the apps, and the runtime DLLs, in a single application directory and provide shortcuts to the applications which can
be placed in their own folders. This will save size and avoids the danger of the DLLs in the system directory being
replaced later with another install of an application and breaking applications that dynamically link to the DLLs.
Static linking is strongly recommended in order to reduce dependencies on the MFC/ATL DLLs. If you are linking
statically, the DLLs should not be redistributed with your application.
See Also
Other Resources
Developing Visual C++ Device Projects
Smart Device Development

Using Code Wizards with Device Projects


Device projects can utilize many of the same code wizards that C++ desktop projects use. Some are not supported, and some
are supported, but have unsupported options. For more information on the unsupported options of specific code wizards, see
Wizard Options in Native Device Projects.
Supported Code Wizards
Visual C++ device projects support the following wizards:
ATL Simple Object Wizard. For more information on unsupported options on this wizard, see
Wizard Options for Options, ATL Simple Object Wizard.
ATL Control Wizard. For more information on unsupported options on this wizard, see
Wizard Options for Options, ATL Control Wizard, Wizard Options for Interfaces, ATL Control Wizard, and
Unsupported Wizard Options for Stock Properties, ATL Control Wizard.
ATL Dialog Wizard.
Adding ATL Support to Your MFC Project
ATL Property Page Wizard. For more information on unsupported options on this wizard, see
Unsupported Wizard Options for Options, ATL Property Page Wizard.
Generic C++ Class Wizard
MFC Class Wizard. For more information on unsupported options on this wizard, see
Unsupported Wizard Options for MFC Class Wizard.
Accessing Visual C++ Smart Device Code Wizards
The Visual C++ Smart Device Code Wizards are available in the Add Class Dialog Box dialog box. You can access the Add Class
dialog box in the following ways:
On the Project menu, click Add Class.
In Solution Explorer, right-click any folder, click Add, and then click Class.
In the Class View window, right-click the appropriate node, click Add, and then click Class.
To see the wizards that are available for smart device projects, expand the directory structure in the Categories pane of the
Add Class dialog box, and click Smart Device. The available templates appear in the Templates pane.
See Also
Other Resources
C++ Class Wizards for Device Projects
Smart Device Development

Wizard Options in Native Device Projects


Due to the differences between device and desktop projects, some of the C++ Class Wizards contain options that are either not
supported on devices, or behave differently on device projects.
The following topics describe the unsupported wizard options when the current project is targeting a device.
In This Section
Wizard Options for Options, ATL Simple Object Wizard
Describes unsupported wizard options for the Options page of the ATL Simple Object Wizard.
Wizard Options for Options, ATL Control Wizard
Describes unsupported wizard options for the Options page of the ATL Control Wizard.
Wizard Options for Interfaces, ATL Control Wizard
Describes unsupported wizard options for the Interfaces page of the ATL Control Wizard.
Unsupported Wizard Options for Appearance, ATL Control Wizard (Devices)
Describes unsupported wizard options for the Appearance page of the ATL Control Wizard.
Unsupported Wizard Options for Stock Properties, ATL Control Wizard
Describes unsupported wizard options for the Stock Properties page of the ATL Control Wizard.
Unsupported Wizard Options for Options, ATL Property Page Wizard
Describes unsupported wizard options for the Options page of the ATL Property Page Wizard.
Unsupported Wizard Options for MFC Class Wizard
Describes unsupported wizard options for the MFC Class Wizard.
Unsupported Wizard Options for Application Settings, ATL Smart Device Project Wizard
Describes unsupported wizard options for the Application Settings page of the ATL Smart Device Wizard.
See Also
Other Resources
C++ Class Wizards for Device Projects
Smart Device Development

Wizard Options for Options, ATL Simple Object Wizard


Describes the unsupported wizard options for smart devices on the Options page of the ATL Simple Object Wizard. Some of
the elements on this wizard page are either not supported on devices, or behave differently in a device project.
Unsupported and Differently Supported Options
The following table describes the elements that behave differently on device projects.
Section Behavior
Threadi The threading model setting depends on whether or not the target platform supports DCOM. If the target platform do
ng mo es not support DCOM, the threading model used in the generated code is always "Free," regardless of what threading
del model the user selects.
Windows Mobile 2003 software does not support DCOM.
For more information about COM, DCOM and threading models on Windows CE, see
Component Services (COM and DCOM) and COM Threads and Processes in the Windows CE 5.0 documentation.

Interfa The Automation compatible check box is not supported on device projects.
ce

Suppor The IObjectWithSite (IE object support) check box is not supported on device projects.
t

See Also
Other Resources
C++ Class Wizards for Device Projects
Smart Device Development

Wizard Options for Options, ATL Control Wizard


Some of the elements on this wizard page are either not supported on devices, or behave differently in a device project.
Unsupported and Differently Supported Options
The following table describes the elements that behave differently on device projects.
Section Behavior
Thread The threading model setting will depend on whether or not the target platform supports DCOM. If the target platform
ing mo does not support DCOM, the threading model used in the generated code is always "Free," regardless of what threadi
del ng model the user selects.
Windows Mobile 2003 software does not support DCOM.
For more information about COM, DCOM and threading models on Windows CE, see
Component Services (COM and DCOM) and COM Threads and Processes in the Windows CE 5.0 documentation.

Control The DHTML control option is not supported on device projects.


type

Suppor The Licensed check box is not supported on device projects.


t

See Also
Other Resources
C++ Class Wizards for Device Projects
Smart Device Development

Wizard Options for Interfaces, ATL Control Wizard


Describes the unsupported interfaces for smart devices on the Interfaces page of the ATL Control Wizard.
Some of the interfaces that appear on this wizard page are either not supported on devices, or behave differently in a device
project.
Unsupported and Differently Supported Options
The following table describes the interfaces that behave differently on device projects.
Interface Behavior
IDataObjec This interface is not supported in Windows CE.
t

IPersistStor This interface is only supported on platforms that support DCOM.


age
Windows Mobile™2003 software does not support DCOM.
For more information on COM and DCOM on Windows CE, see Component Services (COM and DCOM) in the Wi
ndows CE 5.0 documentation.

See Also
Other Resources
C++ Class Wizards for Device Projects
Smart Device Development

Unsupported Wizard Options for Appearance, ATL Control


Wizard (Devices)
Some elements on this wizard page are not fully supported for device projects.
Differently Supported Options
The following table describes elements that differ in device projects.
Section Difference
Add control based on Only the following are supported for device platforms:
Button
ComboBox
Edit
ListBox
Scrollbar
Static
RichEdit (supported on some but not all Windows CE platforms)

See Also
Other Resources
Wizard Options in Native Device Projects
Smart Device Development

Unsupported Wizard Options for Stock Properties, ATL Control


Wizard
Due to the absence of the GUIDs CLSID_StockPicturePage, CLSID_StockColorPage, and CLSID_StockFontPage, some of the
stock properties on this wizard page are not supported on devices.
Unsupported Properties
The following stock properties are not supported on devices:
BackColor
BorderColor
FillColor
Font
ForeColor
MouseIcon
Picture
See Also
Other Resources
C++ Class Wizards for Device Projects
Smart Device Development

Unsupported Wizard Options for Options, ATL Property Page


Wizard
Some of the elements on this wizard page are either not supported on devices, or behave differently in a device project.
The following table describes the elements that behave differently on device projects.
Section Behavior
Threadi The threading model setting depends on whether or not the target platform supports DCOM. If the target platform do
ng mo es not support DCOM, the threading model used in the generated code is always "Free," regardless of what threading
del model the user selects.
Windows Mobile 2003 software does not support DCOM.
For more information about COM, DCOM and threading models on Windows CE, see
Component Services (COM and DCOM) and COM Threads and Processes in the Windows CE 5.0 documentation.

Interfa The Automation compatible check box is not supported on device projects.
ce

Suppor The IObjectWithSite (IE object support) check box is not supported on device projects.
t

See Also
Other Resources
C++ Class Wizards for Device Projects
Smart Device Development

Unsupported Wizard Options for MFC Class Wizard


Some of the elements on this wizard page are either not supported on devices, or behave differently in a device project.
Unsupported Options
The following elements are not supported on device projects:
Active accessibility
DHTML resource ID
.HTM files
Automation
Generate DocTemplate resources
Document Template Strings
See Also
Other Resources
C++ Class Wizards for Device Projects
Smart Device Development

Unsupported Wizard Options for Application Settings, ATL


Smart Device Project Wizard
Describes the unsupported wizard options for smart devices on the Application Settings page of the ATL Smart Device Project
Wizard.
Some of the elements on this wizard page are either not supported on devices, or behave differently in a device project.
Unsupported Options
The following table describes the elements that behave differently on device projects.
Section Behavior
(None) The Attributed checkbox is not supported on device projects.

ATL Smart Device Project Wizard Does Not Implement Type Library Unregistration
Because Windows Mobile does not implement the COM functionality to remove type libraries from the registry, the ATL Smart
Device Project Wizard generates code that implements the DllUnregisterServer function differently:

// DllUnregisterServer - Removes entries from the system registry


STDAPI DllUnregisterServer(void)
{
HRESULT hr = _AtlModule.DllUnregisterServer(false);
return hr;
}

Passing false to the DllUnregisterServer function tells COM not to unregister the type library. If you change the parameter to
true, all calls to DllUnregisterServer will fail with E_NOTIMPL.
See Also
Other Resources
Wizard Options in Native Device Projects
Smart Device Development

Unsupported Options in the Project Properties Dialog Box


Some of the elements on the Project Properties dialog box are either not supported on devices, or behave differently in a
device project.
Unsupported and Differently Supported Options
The following table describes the elements that behave differently on device projects than on a desktop PC.
Sectio Behavior
n
Project While it is possible to set Use of MFC to Use MFC in a Static Library while also setting Use of ATL to Dynamic Lin
Defaul k to ATL, this scenario is not supported in a device project.
ts

Project Note
Defaul This item applies only to MFC Smart Device Application projects and MFC Smart Device DLL projects.
ts

If you change Use of MFC from Use MFC in a Shared DLL (the default) to Use MFC in a Static Library, you should a
lso remove mfc80ud.dll (Debug) and/or mfc80u.dll (Release) from Additional Files in the General section of the Dep
loyment property page.
Likewise, if you change Use of MFC from Use MFC in a Static Library to Use MFC in a Shared DLL, you should also
add mfc80ud.dll (Debug) and/or mfc80u.dll (Release) to Additional Files in the General section of the Deployme
nt property page.
When adding mfc80u.dll or mfc80ud.dll you must also add atl80.dll and msvcr80.dll or msvcr80d.dll.

See Also
Reference
Property Pages (C++)
Other Resources
Wizard Options in Native Device Projects
Smart Device Development

Resource Editors for Device Projects


Using a resource editor with a device project is similar to using one with a desktop Visual C++ project. This section details
some differences between the desktop and device Resource editors. For more information, see Resource Editors.
Device SDKs can define their own user interface (UI) Model, which can be used to filter the list of controls that appear in the
Dialog editor to only show the controls that are supported for that platform. Visual Studio 2005 ships with a Windows CE UI
model including the Windows Mobile 2003 SDKs.
In This Section
Using the Resource Editors for Device Projects
Provides an overview to using the Resource editors with device projects.
Using Resources on Multiple Platforms
Explains how to use resources in projects that target multiple platforms.
Device Dialog Box Controls
Describes the dialog controls that are supported for device projects.
See Also
Other Resources
Developing Visual C++ Device Projects
Smart Device Development

Using the Resource Editors for Device Projects


The Resource editors for device projects are almost identical to the Resource editors for desktop projects. Every editor is
supported, and only the Dialog editor has any significant changes. For more information, see Resource editors.
Native smart device projects in Visual Studio 2005 support the following Resource types:
Accelerator
Bitmap
Cursor
Dialog
Icon
Menu
Registry
String Table
Toolbar
Version
Dialog Editor
The device Dialog editor differs from the desktop Dialog editor in the following ways:
There are some controls missing from the desktop controls and the controls supported on devices have slightly different
properties than the corresponding desktop control. For more information, see Device Dialog Box Controls.
There are new Dialog templates for popular device form factors.
The behavior and properties of the dialog box controls are derived from a user interface (UI) model that accompanies
each installed software development kit (SDK). This UI model provides the correct set of controls for the currently
targeted platform. If the SDK does not define a UI model, the Dialog editor defaults to the Windows CE UI model.
There are two controls unique to device projects: the State of Input Panel Control, and the CAPEdit Control.
RC2 File(s)
Some of the Application Wizards generate an .RC2 resource file in addition to the standard (.RC) resource file. This .RC2 file is
not intended to be compiled by the Resource Compiler; actually, it contains resources that the Resource Compiler does not
handle. Examples include the HI_RES_AWARE custom resource and Menu Resource Data (RCDATA). The .RC2 file is a great
place to put your other custom resources that you do not want the Resource Compiler editing for you.
For more information about how to create Menu resources for Smartphone, see How to: Create a Soft Ke y Bar. To create a
Smartphone menu, make sure you have an RCDATA section. Typically, this will be found in the .RC2 file. Resource IDs should
have values greater than or equal to 100. The IDs are set in the resource header file (resourcesp.h for Smartphone). Buttons
should have an NOMENU as their index (IDR_MENU RCDATA). The example below illustrates this point:

BEGIN
IDR_MENU,
2,
I_IMAGENONE, IDM_OK, TBSTATE_ENABLED, TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE,
IDS_OK, 0, NOMENU,
I_IMAGENONE, IDM_HELP, TBSTATE_ENABLED, TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE,
IDS_HELP, 0, 0,
END

When working with Resource editors for devices you may get errors for the following reasons:
Because you edit a RESX item that belongs to another project item such as a Form or a user-control.
Because the Windows form designer automatically discards any item that does not link to a control. It also removes all
comments, does not support linked items, and fails to load the form or user-control if one has been added to the RESX
file in the Resource editor.
Because some resource types such as Tiff files are not supported on Windows CE.
Because an error is also generated when the resource file's format is unsupported, the file is empty, or the format is
corrupted.
See Also
Other Resources
Resource Editors for Device Projects
Smart Device Development

Using Resources on Multiple Platforms


Visual Studio 2005 enables you to have one device project target multiple platforms, such as Pocket PC and Smartphone. Due
to the user interface (UI) differences between the platforms, each platform needs its own resource script (.rc) file in the project.
Multiple Resource Files
There are two ways that you can set your device project to target multiple platforms:
With the application wizards at the time of project creation.
After project creation.
If you select multiple platforms on the Platforms page in the application wizard of your project, a resource file will be
generated and configured for each of your platforms. For example, if you select Pocket PC and Smartphone as target platforms,
then the Pocket PC resource file will be excluded from the build for the Smartphone platform, and the Smartphone resource
file will be excluded from the build for the Pocket PC platform.
However, if you add a platform after project creation, you will need to manually add a platform and resource file.
Adding a New Platform

To add a new platform


1. On the Build menu, click Configuration Manager.
2. In the Active Solution Platform box, click <New...>.
3. Select the platform that you want to add to your project, select the platform that you want to copy settings from, and
click OK.
Note
If you copy settings from <Default>, the project properties for that platform will be empty. It is recommended that yo
u copy settings from a similar platform, and then change the project properties as needed. For example, if you are addi
ng Smartphone as a platform, copy settings from the Pocket PC platform.

4. Click Close.
Adding a New Resource File
Now that you have a new platform, you will need to add a resource file for that platform.
To add a resource file for a new platform
1. On the Project menu, click Add New Item.
2. In the Add New Item dialog box, click Resource, and then in the Templates pane, click Resource File (.rc).
3. In the Name box, type a name for your file, and click Add.
A new header (.h) file that corresponds to your new resource script (.rc) file is added to your project.
Excluding Resource Files From Builds
When you build a project for a target platform, you do not want resource files from another platform included. You can exclude
files from builds based on the targeted platform.
To exclude resource files from builds
1. Right-click the resource script (.rc) file, and click Properties.
2. In the Platform box, select the first platform in the list.
3. On the General property page, select Yes in the Excluded From Build box if you do not want this .rc file included when
the project is built for the selected platform.
4. Repeat the previous step for each platform configuration, making sure to only exclude the resource files that do not
belong to the currently selected platform.
5. Repeat steps all of the previous steps (1-4) for each .rc file in the project.
In Solution Explorer, you will notice a red mark on the icon of each file being excluded from the build for the currently
selected platform.
Changing the Project Properties of Your New Platform Configuration
Now that your resource files are set up for your platforms, you need to make sure that the project properties are correct for
your new platform configuration. If you copied settings from a similar platform, you may not have many settings to change,
but if you selected <Default>, you will have to manually add all of your settings. For this example, you can assume that you
added a new Smartphone 2003 (ARMV4) platform to your project, and copied the settings from the Pocket PC 2003
(ARMV4) platform.
To change your project properties
1. On the Project menu, click Properties.
2. Expand the C/C++ node, and click Preprocessor.
3. In the Preprocessor Definitions box, change POCKETPC2003_UI_MODEL to SMARTPHONE2003_UI_MODEL, and
click OK.
Note
If you have added a different platform, or have copied settings from a different platform, you may have to change mor
e settings.

Adding the #ifdef Directive to the Header File


The main header file of your project needs to check for the UI model preprocessor definition that you set in the previous
procedure, and only includes the corresponding resource file.
To add the #ifdef directive to the header file
1. Open ProjectName.h.
2. After the #ifdef for your original platform's UI model, add the following code:

#ifdef SMARTPHONE2003_UI_MODEL
#include "ResourceFileName.h"
#endif

3.
See Also
Other Resources
Resource Editors for Device Projects
Smart Device Development

Device Dialog Box Controls


The Dialog Editor enables you to create or edit dialog box resources for Visual C++ device projects in almost the same way
that you can for Visual C++ desktop projects. This section describes the two device-specific controls as well as the common
desktop controls that are supported in the dialog editor for device projects.
In This Section
Dialog Box Controls Supported on Devices
Describes the common desktop controls that are also supported on devices.
Dialog Box Controls Unique to Devices
Describes the two controls unique to devices.
See Also
Other Resources
Resource Editors for Device Projects
Smart Device Development

Dialog Box Controls Supported on Devices


The Visual Studio 2005 device dialog box editor supports two unique device controls as well as most of the common controls
that are supported for desktop projects.
Supported Controls
The following common controls are supported in the dialog box editor for devices:

Button Vertical Scroll Bar

Check Box Slider Control

Edit Control Progress Control

Combo Box List Control

List Box Tree Control

Group Box Tab Control

Radio Button Date Time Picker

Static Text Month Calendar

Picture Control Custom Control

Horizontal Scroll Bar

To see an up-to-date list of dialog box controls supported on devices, you can create a native Win32 .exe device project,
double-click on the RC file, and then expand the Dialog node and open it.
Controls Unique to Devices
The Visual Studio 2005 dialog box editor also adds two new controls for device development.
Control Description
CAPEdit Control The CAPEdit control is an edit control that capitalizes the first letter in each word in the control.

State of Input Panel Control The State of Input Panel control raises the input panel on platforms that support it.

See Also
Other Resources
Device Dialog Box Controls
Smart Device Development

Dialog Box Controls Unique to Devices


The State of Input Panel and CAPEdit Control are dialog boxes unique to the devices. These dialog boxes are designed to
take advantage of unique characteristics of devices.
In This Section
CAPEdit Control
The CAPEdit control is an edit control that capitalizes the first letter typed in the control.
State of Input Panel Control
The State of Input Panel Control shows the input panel on any dialog box.
See Also
Other Resources
Device Dialog Box Controls
Smart Device Development

CAPEdit Control
The CAPEdit control behaves like an CEdit Class control except that the first letter in the control is automatically capitalized.
This control simplifies the process of entering long strings of characters and is often used in situations where users need to
enter information that should always be capitalized, such as names and locations.
See Also
Reference
CDialog Class
Other Resources
Dialog Box Controls Unique to Devices
Creating an Edit Control
Smart Device Development

State of Input Panel Control


The State of Input Panel control is a non-visual control that displays the Input Panel on platforms that support it, such as the
Pocket PC. If this control is included in a dialog box, the input panel is raised whenever an input control receives focus. When
the control loses focus, the input panel is lowered.
Note
Adding more than one State of Input Panel control in a dialog box causes applications to hang on the device. This issue ma
y be addressed in future releases.

See Also
Concepts
Dialog Box Controls Supported on Devices
Other Resources
Dialog Box Controls Unique to Devices
Smart Device Development

Compilers for Smart Devices


Visual Studio 2005 includes the following compilers that target microprocessors used in smart devices:
32-bit C/C++ compiler used to compile and link 32-bit ARM C, and C++ programs.
32-bit C/C++ compiler used to compile and link 32-bit Renesas SH-4 C, and C++ programs.
A C/C++ compiler used to compile and link MIPS16, MIPS32, MIPS64 C, and C++ programs.
The compilers produce Common Object File Format object files. The compiler programs compile each source file and, unless
otherwise specified, an object file for each compile. The compilers include the options listed at the command line (CL), in the CL
environment variable, and any specified response files. For more information, see the Reference topic
Compilers for Smart Devices.
Visual Studio 2005 Compiler Differences Between Desktop and Devices
Difference Description
Advanced Tab, Compil Device projects in Project Properties, Advanced tab , Compile for Architecture dropdown list, un
e for Architecture drop der C/C++ node, have the following options in the drop down box: Arm4 (/QRarch4), ARM5 (/QRa
down list. rch5), Arm4t (/QRarch4t), ARM5t (/QRarch5t).

Advanced Tab, Interw Device projects in Project Properties, Advanced tab , Interwork ARM & ARM Thumb dropdown l
ork ARM & ARM Thu ist under C/C++ node, have the following options in the drop down box: Yes (/QRInterwork-return
mb dropdown list. ), and NO option. When set to yes, the compiler generates thunking code to interwork ARM 16 and 3
2 bit code.

Advanced Tab, Enable Device projects in Project Properties, Advanced tab , Enable Floating Point Emulation dropdow
Floating Point Emulat n list under C/C++ node, have the following options in the drop down box: Yes, and NO option. Whe
ion dropdown list. n set to Yes, the compiler enables emulation of floating point operations.

PreProcessor Tab, PreP Device projects in Project Properties, PreProcessor tab , PreProcessor Definitions input box, und
rocessor Definitions in er C/C++ node, have a check box to Inherit From Parent or Project Defaults and a Macros button
put box. to add macros.

Optimization Tab, Floa Device projects in Project Properties, Optimization tab , , Floating Point Consistency Definition
ting Point Consistenc s dropdown list, under C/C++ node, have a dropdown list to select Default Consistency or Improv
y Definitions dropdow e Consistency (/Op).
n list.

For additional information see Compiler Options Listed Alphabetically.


Compiler Changes Between Visual Studio 2003 and Visual Studio 2005
Because the device compilers are based on the desktop computer Visual C++ compiler, examining the differences between
versions of the desktop compilers provides a good picture of the changes between the eMbedded Visual C++ device compilers
and the Visual Studio 2005 device compilers. For information about changes between Visual Studio 6.0 and Visual Studio
2003, see Standard Compliance Issues in Visual C++.
The following table summarizes compiler changes between Visual Studio 2003 and Visual Studio 2005.
Issue Description
Pointer-to-mem Code that was written for previous versions of the compiler that used only the method name will now give C
bers now require ompiler Error C3867 or Compiler Warning C4867. This diagnostic is required by the ISO C++ standard. To cr
qualified name, a eate a pointer to a member function, the address-of operator (&) and the fully qualified name of the method
ddress-of operat must be used. Errors may result from not requiring the & operator and the fully qualified name of the metho
or (&), and pare d, or due to missing parentheses in function calls. Using the function's name without an argument list results
nthesis in functio in a function pointer that is convertible to several types. Therefore, the code may produce unexpected behavi
n calls. or at run time.
A class must be Previous Visual C++ compilers enabled a friend declaration to a class that was not accessible in the scope of
accessible to a fr the class that contained the declaration. In Visual C++ 2005, these circumstances will cause the compiler to g
iend declaration. enerate Compiler Error C2248. To resolve this error, change the accessibility of the class that is specified in th
e friend declaration. This change was made to comply with the ISO C++ standard.

Explicit specializa Code that depends on an explicit template specialization for a copy constructor or copy assignment operator
tion is not allowe will now generate Compiler Error C2299. The ISO C++ standard prohibits this usage. This change was made
d as a copy const for conformance reasons, to improve code portability.
ructor and copy
assignment oper
ator.

An unspecialized Using an unspecialized template class name in the base class list for a class definition will result in Compiler
class template ca Error C3203. It is invalid to use an unspecialized template class name as a template parameter in a base class
nnot be used as list. You must explicitly add the template type parameters to the template class name when using it as a tem
a template argu plate parameter in a base class list. This change was made for conformance reasons and to improve code por
ment in a base cl tability.
ass list.

A using declarati Code that has a using declaration to a nested type will now generate Compiler Error C2885. To resolve this e
on of nested typ rror, you need to fully qualify references to nested types, put the type in a namespace, or create a typedef. Th
e is no longer all is change was made for conformance reasons, to improve code portability.
owed.

/YX compiler op The /YX compiler option generated automatic precompiled headers support. It was used by default from the
tion is removed. development environment. If you remove the /YX compiler option from your build configurations, it can res
ult in faster builds. In addition to performance issues, the /YX compiler option introduces the possibility of u
nexpected run time behavior. It is preferable to use /Yc, Create Precompiled Header File, and /Yu, Use Pr
ecompiled Header File, which give you more control over how precompiled headers are used.

/Oa and /Ow co The /Oa and /Ow compiler options have been removed and will be ignored. Use the noalias or restrict dec
mpiler options a lspec modifiers to specify how the compiler does aliasing.
re removed.

/Op compiler op The /Op compiler option has been removed. You can use /fp:precise instead.
tion is removed.

/ML and /MLd c Visual C++ 2005 no longer provides single-threaded, statically linked CRT library support. You can use /MT
ompiler options and /MTd instead.
have been remo
ved.

/G3, /G4, /G5, / The compiler now uses a blended model that attempts to create the best output file for all architectures.
G6, /G7, and /G
B compiler optio
ns have been re
moved/

/Gf compiler opt You can use /GF instead. /GF puts pooled strings into a read-only section, which is safer than the writeable s
ion has been re ection where /Gf added them.
moved.

/GS compiler op Buffer overflow checking is now on by default. You can turn buffer overrun checking off with /GS-.
tion is now on b
y default.
/Zc:wchar_t vari This is ISO C++ standard behavior: A wchar_t variable will default to the built-in type instead of a short unsig
able is now on b ned integer. This change will break binary compatibility when the client code is linked with libraries that were
y default. compiled without /Zc:wchar_t. You can use /Zc:wchar_t- to revert to the old, non-standard behavior. This c
hange was introduced to create conformant code by default.

/Zc:forScope va This is ISO C++ standard behavior: Code that depends on the use of a variable declared in a for loop after th
riable is now on e for loop scope has ended will now fail to compile. You can use /Zc:forScope to revert to the old, non-stan
by default. dard behavior. This change was introduced to create conformant code by default.
Enforce paramet Code that passes named attributes to the attribute constructor in quotation marks when the type is not a stri
er checking for V ng, and without quotation marks when the type is a string, will now generate Compiler Error C2065 or Comp
isual C++ attribu iler Warning (level 1) C4581. Previously, all compiler attributes were parsed as strings, and if needed, the co
tes. mpiler inserted the missing quotation marks. Attribute support was enhanced by adding parameter checking
validation. This change will prevent unexpected behavior due to incorrect arguments being passed to an attri
bute constructor.

Compiler will no Code that is missing the type in a declaration will no longer default to type int. The compiler will generate Co
t inject type int a mpiler Warning C4430 or Compiler Warning (level 4) C4431. The ISO C++ standard does not support a defa
s the default typ ult int, and this change will help ensure that you get the type you explicitly specified.
e in declarations.

For more information, see Breaking Changes in the Visual C++ 2005 Compiler.
See Also
Other Resources
Developing Visual C++ Device Projects
Smart Device Development

Code Explanation: Wizard-Generated Code in Visual C++


Device Projects
Visual C++ capabilities and wizards simplify most of the mundane tasks of generating multiplatform device applications,
configuration files, and project files. This walkthrough describes the code automatically generated for you by the Windows 32
Device Application Wizard. That way, you can extend and modify your Windows applications to suit your needs.
Wizard-Generated Code for a Windows 32 Device Application
If you are familiar with Windows (win32) desktop programming, you can easily spot the main routines generated for you by
the wizard.
In a typical Windows device application, the main entry is located in the <yourprojectname>.cpp file. A sample listing of this
file follows.
At a quick glance, the application has the following main functionality:
WinMain function
MyRegisterClass function
InitInstance function
An About Dialog function
Each of these functions is further illustrated below:
WinMain function: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int
nCmdShow). For more information, see WinMain Function.

int WINAPI WinMain(HINSTANCE hInstance,


HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
MSG msg;

// Perform application initialization:


if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}

Win32 Platforms. For more information, see Win32 Platforms.

#ifndef WIN32_PLATFORM_WFSP
HACCEL hAccelTable;
hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_WIN32SMARTDEVICE);
#endif // !WIN32_PLATFORM_WFSP

Message loops. For more information, see Message Handling and Command Targets.

// Main message loop:


while (GetMessage(&msg, NULL, 0, 0))
{
#ifndef WIN32_PLATFORM_WFSP
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
#endif // !WIN32_PLATFORM_WFSP
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}

return (int) msg.wParam;


}

The MyRegisterClass function registers the window application.

// FUNCTION: MyRegisterClass()
ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
{
WNDCLASS wc;

wc.style = CS_HREDRAW | CS_VREDRAW;


wc.lpfnWndProc = (WNDPROC)WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WIN32SMARTDEVICE));
wc.hCursor = 0;
wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = szWindowClass;

return RegisterClass(&wc);
}

InitInstance: FUNCTION InitInstance(HANDLE, int) For more information, see InitInstance Member Function.

WIN32_PLATFORM_WFSP is used as a condition for Smartphone and WIN32_PLATFORM_PSPC for Pocket PC. You can always
define your own conditionals if you want to further differentiate.

// FUNCTION: InitInstance(HANDLE, int)


// PURPOSE: Saves instance handle and creates main window.
// COMMENTS:
// In this function, we save the instance handle in a global
// variable and create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
TCHAR szTitle[MAX_LOADSTRING];
// title bar text
TCHAR szWindowClass[MAX_LOADSTRING];
// main window class name

g_hInst = hInstance;
// Store instance handle in your global variable.

#ifdef WIN32_PLATFORM_PSPC
// SHInitExtraControls should be called once during your application's initializat
ion to initialize any
// of the Pocket PC special controls such as CAPEDIT and SIPPREF.
SHInitExtraControls();
#endif // WIN32_PLATFORM_PSPC

LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);


LoadString(hInstance, IDC_WIN32SMARTDEVICE, szWindowClass, MAX_LOADSTRING);

#if defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)


//If it is already running, then focus on the window, and exit.
hWnd = FindWindow(szWindowClass, szTitle);
if (hWnd)
{
// Set the focus to the foremost child window.
// The "| 0x00000001" is used to bring any owned windows
//to the foreground and activate them.
SetForegroundWindow((HWND)((ULONG) hWnd | 0x00000001));
return 0;
}
#endif // WIN32_PLATFORM_PSPC || WIN32_PLATFORM_WFSP

if (!MyRegisterClass(hInstance, szWindowClass))
{
return FALSE;
}

hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,


CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInsta
nce, NULL);

if (!hWnd)
{
return FALSE;
}

#ifdef WIN32_PLATFORM_PSPC
// When the main window is created using CW_USEDEFAULT,
// the height of the menubar is not taken into account.
// So the generated code resizes the window after creating it.
if (g_hWndMenuBar)
{
RECT rc;
RECT rcMenuBar;

GetWindowRect(hWnd, &rc);
GetWindowRect(g_hWndMenuBar, &rcMenuBar);
rc.bottom -= (rcMenuBar.bottom - rcMenuBar.top);

MoveWindow(hWnd, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top, FALSE);


}
#endif // WIN32_PLATFORM_PSPC

ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);

return TRUE;
}

An About dialog is also generated for your application as an example of how to build other dialogs you may want:
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
// win32smartdevice.cpp : Defines the entry point for the application.
#include "stdafx.h"
#include "win32smartdevice.h"
#include <windows.h>
#include <commctrl.h>

#define MAX_LOADSTRING 100

// Global Variables:
HINSTANCE g_hInst;
// Current instance:
HWND g_hWndMenuBar;
// Menu bar handle

// Forward declarations of functions included in this code module:


ATOM MyRegisterClass(HINSTANCE, LPTSTR);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
#ifndef WIN32_PLATFORM_WFSP
LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);
#endif
// !WIN32_PLATFORM_WFSP
// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
// PURPOSE: Processes messages for the main window.
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return

Some of the main messages, such as WM_COMMAND are already included for you and for extensibility. WinProc is included
for a processing system and user input messages: LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM
wParam, LPARAM lParam. For more information on WinProc, see Windows Overview.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
HGDIOBJ hbrWhite, hbrGray;
POINT aptStar[6] = {50,2, 2,98, 98,33, 2,33, 98,98, 50,2};

#if defined(SHELL_AYGSHELL) && !defined(WIN32_PLATFORM_WFSP)


static SHACTIVATEINFO s_sai;
#endif // SHELL_AYGSHELL && !WIN32_PLATFORM_WFSP
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
#ifndef WIN32_PLATFORM_WFSP
case IDM_HELP_ABOUT:
DialogBox(g_hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
break;
#endif // !WIN32_PLATFORM_WFSP
#ifdef WIN32_PLATFORM_WFSP
case IDM_OK:
DestroyWindow(hWnd);
break;
#endif // WIN32_PLATFORM_WFSP
#ifndef WIN32_PLATFORM_WFSP
case IDM_OK:
SendMessage (hWnd, WM_CLOSE, 0, 0);
break;
#endif // !WIN32_PLATFORM_WFSP
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_CREATE:
#ifdef SHELL_AYGSHELL
SHMENUBARINFO mbi;

memset(&mbi, 0, sizeof(SHMENUBARINFO));
mbi.cbSize = sizeof(SHMENUBARINFO);
mbi.hwndParent = hWnd;
mbi.nToolBarId = IDR_MENU;
mbi.hInstRes = g_hInst;

if (!SHCreateMenuBar(&mbi))
{
g_hWndMenuBar = NULL;
}
else
{
g_hWndMenuBar = mbi.hwndMB;
}

#ifndef WIN32_PLATFORM_WFSP
// Initialize the shell activate info structure
memset(&s_sai, 0, sizeof (s_sai));
s_sai.cbSize = sizeof (s_sai);
#endif // !WIN32_PLATFORM_WFSP
#endif // SHELL_AYGSHELL
hbrWhite = GetStockObject(WHITE_BRUSH);
hbrGray = GetStockObject(GRAY_BRUSH);
return 0L;
break;
case WM_PAINT:
RECT rc;
hdc = BeginPaint(hWnd, &ps);
GetClientRect(hWnd, &rc);
Polyline(hdc, aptStar, 6);
EndPaint(hWnd, &ps);
return 0L;

break;
case WM_DESTROY:
#ifdef SHELL_AYGSHELL
CommandBar_Destroy(g_hWndMenuBar);
#endif // SHELL_AYGSHELL
PostQuitMessage(0);
break;

#if defined(SHELL_AYGSHELL) && !defined(WIN32_PLATFORM_WFSP)


case WM_ACTIVATE:
// Notify shell of your activate message.
SHHandleWMActivate(hWnd, wParam, lParam, &s_sai, FALSE);
break;
case WM_SETTINGCHANGE:
SHHandleWMSettingChange(hWnd, wParam, lParam, &s_sai);
break;
#endif // SHELL_AYGSHELL && !WIN32_PLATFORM_WFSP

default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}

#ifndef WIN32_PLATFORM_WFSP
// Message handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
#ifdef SHELL_AYGSHELL
{
// Create a Done button and size it.
SHINITDLGINFO shidi;
shidi.dwMask = SHIDIM_FLAGS;
shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFUL
LSCREEN | SHIDIF_EMPTYMENU;
shidi.hDlg = hDlg;
SHInitDialog(&shidi);
}
#endif // SHELL_AYGSHELL

return TRUE;

case WM_COMMAND:
#ifdef SHELL_AYGSHELL
if (LOWORD(wParam) == IDOK)
#endif
{
EndDialog(hDlg, LOWORD(wParam));
return TRUE;
}
break;

case WM_CLOSE:
EndDialog(hDlg, message);
return TRUE;

#ifdef _DEVICE_RESOLUTION_AWARE
case WM_SIZE:
{
DRA::RelayoutDialog(
g_hInst,
hDlg,
DRA::GetDisplayMode() != DRA::Portrait ? MAKEINTRESOURCE(IDD_ABOUTBO
X_WIDE) : MAKEINTRESOURCE(IDD_ABOUTBOX));
}
break;
#endif
}
return FALSE;
}
#endif // !WIN32_PLATFORM_WFSP

See Also
Tasks
Walkthrough: Creating a Simple Windows Form
Reference
General, Device Tools, Options Dialog Box
Toolbox
Other Resources
Smart Device Walkthroughs
Developing Visual C++ Device Projects
Smart Device Development

How to: Specify the Remote Path for Primary Project Output
You can set the Remote Directory for the deployment of your project using the property pages of the device project. The
Remote Directory specifies the device directory where the application's output is deployed.
The Remote Directory is set to %CSIDL_PROGRAM_FILES%\<projectname>, by default. The first part is a CSIDL value and
the second is your project name. CSIDL values provide a system-independent way to identify Remote Directory folders.
These values supersede the use of environment variables for this purpose. The following table lists valid CSIDL values for the
Remote Directory parameter. Use % signs to encapsulate the value.

CSIDL Valu Description


e

CSIDL_DESKTOP 0x00 Not supported on Smartphone.


00

CSIDL_FAVORITE 0x00 The file system directory that serves as a common repository for the user's favorite items.
S 06

CSIDL_FONTS 0x00 The virtual folder that contains fonts.


14

CSIDL_PERSONA 0x00 The file system directory that serves as a common repository for documents.
L 05

CSIDL_PROGRA 0x00 The program files folder.


M_FILES 26

CSIDL_PROGRA 0x00 The file system directory that contains the user's program groups, which are also file system directorie
MS 02 s.

CSIDL_STARTUP 0x00 The file system directory that corresponds to the user's Startup program group. The system starts thes
07 e programs when a device is powered on.

CSIDL_WINDOW 0x00 The Windows folder.


S 24

To specify the remote path for primary project output


1. In Solution Explorer, right-click <Projectname>, and then on the shortcut menu, click Properties.
2. Expand the Configuration Properties node, and click Deployment.
3. In the rightmost pane, set the Remote Directory property of the project.
See Also
Other Resources
Developing Visual C++ Device Projects
Smart Device Development

How to: Change the Default Device (Native Projects)


Use the following steps to change the default target device in native projects.
To select a new default target device for a native project
1. In Solution Explorer, right-click <Projectname>.
2. On the shortcut menu, click Properties.
3. In the Properties dialog box, expand Configuration Properties, and then click Deployment.
4. On the drop-down list, change the value of the Deployment property to select a new default target device.
See Also
Tasks
How to: Change the Default Device (Managed Projects)
Reference
Deploy Dialog Box (Devices)
Other Resources
Developing Visual C++ Device Projects
Smart Device Development

Building and Debugging Visual C++ Device Projects


Building and debugging device projects is slightly different from building and debugging desktop projects. This section
contains topics that explain those differences.
The following is a list of building and debugging techniques:
The threading model for device project is Free by default. However, Windows CE does not fully support COM marshalling
and associated definitions, if the DCOM option is not chosen when you are building your CE OS image. Therefore, on
certain CE platforms, the compiler may generate warnings about DCOM support and single and multithreading
definition. This warning is to advise you to handle threading and synchronization in your own code. For example, when
compiling an ATL device project, the compiler may issue a warning about defining
_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA. This is also the case for scenarios such as creating COM objects,
consuming Web services, as well as ATL COM objects on the Windows Mobile platform. You can define this flag in your
main header file as follows for single-threaded objects: #define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA. If your
code is handling multithreading, you can safely ignore this warning. For more information about COM, DCOM and
threading models on Windows CE, see COM Threads and Processes and Component Services (COM and DCOM), in the
Windows CE 5.0 documentation.
Native device applications are created with static linking by default. You can add the following run-time DLLs to your
Additional Files project property if you choose to switch to dynamic linking:
MFC applications release build configurations: Add the following runtime DLLs to your Additional Files project
property: msvcr80.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\
<projectname>|0;atl80.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\
<projectname>|0;MFC80U.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\<projectname>|0;
MFC applications debug build configurations: Add the following run-time DLLs to your Additional Files project
property: msvcr80d.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\
<projectname>|0;msvcr80.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\
<projectname>|0;atl80.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\
<projectname>|0;MFC80Ud.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\<projectname>|0;
ATL applications release build configurations: Add the following run-time DLLs to your Additional Files project
property: msvcr80.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\
<projectname>|0;atl80.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\<projectname>|0;
ATL applications debug build configurations: Add the following run-time DLLs to your Additional Files project
property: msvcr80d.dll|$(BINDIR)\$(INSTRUCTIONSET)\%CSIDL_PROGRAM_FILES%\
<projectname>|0;msvcr80.dll|$(BINDIR)\$(INSTRUCTIONSET)\%CSIDL_PROGRAM_FILES%\
<projectname>|0;atl80.dll|$(BINDIR)\$(INSTRUCTIONSET)\%CSIDL_PROGRAM_FILES%\<projectname>|0;
For more information about Windows CE DLL loading, see Windows CE DLL loading LoadLibrary.
Note
Loading multiple DLLs, with the same name, at the same time, from different directories, for example \Windows
\aDLL.dll and \Program Files\aDLL.dll, may cause unpredictable results. It is recommended that you load one c
opy of a DLL at a time or expect the first loaded DLL to be called.

The following are some additional considerations:


When porting to MFC 8.0 #, define _WIN32_WCE_PSPC. This flag is not defined by default in MFC8.0.
The ARM4T option is not supported when targeting Pocket PC 2003 or Smartphone 2003 in the Compile For
Architecture drop-down list. This list is located in the <project name> Property Pages dialog box by clicking
Configuration Properties, then clicking C/C++, clicking Advanced, and then selecting Compile For Architecture.
GAPI functions are usable in C++ but not in C. Including gx.h in your code only works from C++. If you are using GAPI in
your code, do not compile with the /TC compiler option.
In MFC 8.0 for Devices, you control the creation and insertion of CommandBar. The CDialog::m_pWndEmptyCB
member is no longer supported. This member was used to point to the empty CCommandBar Class, also called
MenuBar on the Pocket PC, which was created for the dialog box, and you could reference it to insert your own
MenuBar.
Checked::_strlwr_s, _strlwr_s_l, _mbslwr_s, _mbslwr_s_l, _wcslwr_s, _wcslwr_s_l, Checked::tcslwr_s, and
Checked::gcvt_s are provided for Windows CE platforms and the underlying CRT methods will be secure in future
releases to maximize security.
The _WIN32_WCE_PSPC flag is no longer defined; you can use _WIN32_WCE_PSPC WIN32_PLATFORM_PSPC flag as
a workaround.
For STL application porting, include <deque> instead of #include <deque.h>.

Due to the multiplatform nature of the development environment, when hosting MFC or ATL ActiveX objects in a device
project, in a dialog box resource, you should create and register an equivalent control in an equivalent desktop ActiveX
project so that it can be added to the device dialog box template in the resource editor and run correctly. The desktop and
the device versions of the ActiveX control should have the same GUID and design-time properties, such as background
color.
In This Section
Debugging and Deployment Settings for Visual C++ Device Projects
Explains the debugging and deployment properties unique to Visual C++ device projects.
See Also
Reference
Debugging, Configuration Properties, <Projectname> Property Pages Dialog Box (Devices)
Concepts
Debugging and Deployment Settings for Visual C++ Device Projects
Other Resources
Debugging Device Projects
Creating and Porting Visual C++ Device Projects
Developing Visual C++ Device Projects
Smart Device Development

Debugging and Deployment Settings for Visual C++ Device


Projects
Visual C++ device projects support properties that are not supported for Visual C++ desktop projects. These properties are set
on the project's property page.
Unique Property Pages
Visual C++ device projects have the following unique property pages:
Debugging, Configuration Properties, <Projectname> Property Pages Dialog Box (Devices)
IDE Features Supporting Device Application Packaging
Debug Pane, Project Designer
For more information about property pages, see Building and Debugging Visual C++ Device Projects and
Property Pages (C++).
Accessing Visual C++ Device Project Properties
You can access device project property pages in the following ways:
In Solution Explorer, right-click the project, and click Properties.
In Solution Explorer, click the project name, and then on the Project menu, click Properties.
Note
When debugging an ATL .exe project such as when the deployment target is Windows CE 5.0 SDK with DCOM support,
set the Register Output setting in the Project Properties to YES and add /RegServer to the Command property. Thi
s will register the .exe when you start debugging. For more information, see
Deployment, Configuration Properties, <Projectname> Property Pages Dialog Box (Devices).

Note
When you deploy a native device project, dependent projects may not deploy automatically with the native device proj
ect, and may require separate deployment.

See Also
Other Resources
Building and Debugging Visual C++ Device Projects
Smart Device Development

Debugging Device Projects


Debugging projects that run on smart devices is very similar to debugging projects that run on the desktop. One obvious
difference is that the processor on which the debugging takes place in a device project is not on the development computer,
and therefore connection issues play a role in device debugging.
The topics in this section summarize the differences from debugging desktop projects, and provide some useful tips for
debugging on a device.
Security Note
Debugging applications on a device or emulator that has confidential or sensitive information might pose a security risk.

In This Section
Differences Between Device And Desktop Debuggers
Describes areas where the device debugging experience differs from that of the desktop.
How to: Attach to Managed Device Processes
Describes how to attach to managed processes that are already running.
How to: Change Device Registry Settings
Describes using the Remote Registry Editor to change registry settings on the device.
Walkthrough: Debugging a Solution That Includes Both Managed and Native Code
Describes the steps for alternately launching the native and managed debuggers.
See Also
Other Resources
Smart Device Development
Debugging and Profiling Applications
Mobile Developer Center
Smart Device Development

Differences Between Device And Desktop Debuggers


Device debuggers support most of the same features that desktop debuggers support, with the following exceptions.
Edit and Continue Not Supported
Device debuggers do not support the ability to edit the source and continue while in break mode. If you want to modify your
code while debugging, you need to stop debugging, edit your code, and then restart with the modified sources. If you try to
change your code while in break mode, the debugger issues a warning.
Function Evaluation Not Supported in Native Debugger
The native device debugger does not support function evaluation. You cannot type in an expression that has a function in it and
have the function evaluated and results returned.
The managed device debugger does support function evaluation.
Interop Debugging Limitations
You cannot debug native and managed code within a single instance of the debugger.
To debug applications that have mixed native and managed code (or managed code that uses pInvoke), set breakpoints in each
section where you want to begin stepping through your code. Then attach whichever debugger is required for a certain section
(for example, a managed section). Detach that debugger and attach the other when the other is needed. You can repeat these
detach/attach steps as often as necessary to step through your program. For more information, see
Walkthrough: Debugging a Solution That Includes Both Managed and Native Code.
Using the two debugging instances at the same time on the same process is currently not supported.
Attribute-Based Debugging Not Supported
The .NET Compact Framework does not currently support attribute-based debugging. Thus, the ability to define attributes for
visualizers and so on, is not available for users of the device debuggers.
Desktop Debugging Not Supported
You cannot use the device debuggers to debug applications written for the desktop. Use the desktop debuggers instead.
Kernel Debugging Not Supported
You cannot use the device debuggers for kernel debugging.
Just My Code Debugging Not Supported
You cannot use Just My Code debugging.
Runtime Debugger (Cordbg.exe) Additions
The Runtime Debugger helps tools vendors and application developers find and fix bugs in programs that target the .NET
Framework common language runtime (CLR). Device projects add a new command and a new mode argument to the Runtime
Debugger. The syntax for the new command and mode argument (inside a Cordbg.exe session) is described in the table below.
For more information and complete syntax, see Runtime Debugger (Cordbg.exe).
Command Description
m[ode] EmbeddedCLR EmbeddedCLR is a mode argument that sets the debugger to target device projects. To control this set
{0|1} ting, specify 1 for on or 0 for off.
conn[ect] machine_na Connects to a remote embedded CLR device.
me port
Parameters:
Machine_name
Required. The name or IP address of the remote computer.
Port
Required. The port to use to connect to the remote computer.

Connection Issues
Turning off the device while the debugger is running causes the debugger to close because of the connection failure. The
connection failure occurs because the application is still running in the background on the device. The X button on the Pocket
PC is a smart minimize feature and does not close the application. Instead it sets the application to run in the background.
To properly close an application running in the background on a Pocket PC, on the Start menu, tap Settings, tap the System
tab, and then tap Memory. On the Running Programs tab, tap the application that you want to close, and tap Stop.
See Also
Other Resources
Debugger Roadmap
Debugging Device Projects
Smart Device Development

How to: Attach to Managed Device Processes


You attach to a process on a device in much the same way as you would on the desktop, except that you must set a registry key
on the device to enable managed debugging if the process is already running without the debugger. The setting of this key
persists until you change it, or, in the case of an emulator, until the emulator is closed without saving its settings.
Note
Setting the device debug key reduces performance. When you are not debugging, reset the key.

An error message appears if you try to attach two debuggers or try to attach with a managed debugger when the device
registry key has not been set.
You can start a process in several ways, including File Explorer, the command line, and so on. In the following step, you start
the process by launching from the Debug menu. You can also start a process without the managed debugger, and then attach
it later.
If you are targeting a Windows CE platform generated from Platform Builder, you need to have the toolhelp.dll library to
populate the Available Processes pane. This library is included in the Windows Mobile SDKs.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Debug a Managed Process


To debug a managed process
On the Debug menu, click Start.
Note
If you detach from processes started from the Debug menu, you cannot reattach without performing the following ste
ps for attaching after a process is running. That is, the registry key on the device has to be set.

Attach to an Already Running Managed Process


If you plan to attach to a process that is already running, by, for example, clicking Start Without Debugging and then
attaching to a running managed process, you must first set the device registry key before the process starts and before you try
to attach using the Attach to Process dialog box. The following steps detail the process.
To set the device registry key to enable attaching to a running process
1. On the Windows Start menu, point to All Programs, point to Microsoft Visual Studio 2005, point to Visual Studio
Tools, and then click Remote Registry Editor.
2. Using the Remote Registry Editor, connect to the device.
3. Navigate to or create the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\Managed Debugger
4. Set or create a DWORD value named AttachEnabled.
5. Set the data for the value at 1.
Note
Setting the device debug key significantly reduces performance. When you are not debugging, disable managed attach
by resetting the data value to 0 or deleting the AttachEnabled value.
6. Close the Remote Registry Editor.
Managed attach is now enabled, and you will be able to start a process without the debugger and then attach to the
process using the Attach to Process dialog box.
To attach to a managed process after the process is running
1. After setting the registry key as described in the preceding steps, start a process without the debugger.
2. On the Tools menu, click Attach to Process.
3. In the Transport box, click Smart Device.
4. In the Qualifier box, click Browse.
Note
The Qualifier box is prepopulated with the most recently used devices from the current session.

5. In the Connect to Device dialog box, select the platform, select the device, and then click Connect.
6. In the Available Processes pane, select one or more processes to attach to, and then click Attach.
Note
By default, code type is set automatically to Managed (.NET Compact Framework) if available, otherwise to Native (
Smart Device). To override the default settings, click Select to open the Select Code Type dialog box. Note that you c
annot select both.

Note
Interop debugging is not supported. That is, you cannot debug both managed and native code types at the same time.

Detach From or Terminate a Process


To detach from or terminate a process
1. On the Debug menu, point to Windows, and then click Processes.
2. In the Processes window, right-click the process you want to detach from or terminate.
3. On the shortcut menu, click Terminate Process or Detach from Process.
Note
You can reopen the Attach to Process dialog box from this same shortcut menu.

Populate the Available Processes Pane


To populate the Available Processes pane in Windows CE projects
Include the file toolhelp.dll in the Windows CE OS image.
—or—
Manually copy the file toolhelp.dll to the target device.

See Also
Tasks
Walkthrough: Debugging a Solution That Includes Both Managed and Native Code
Other Resources
Debugging Device Projects
Building and Debugging Visual C++ Device Projects
Smart Device Development

How to: Change Device Registry Settings


Use the Remote Registry Editor to change registry settings on the device.
To change registry settings
1. On the Windows Start menu, point to All Programs, point to Visual Studio 2005, point to Visual Studio Remote Tools,
and then click Remote Registry Editor.
2. In the Select a Windows CE Device window, click the target device whose registry you want to edit.
A node representing the registry of the target device is displayed in the left pane of the Registry Editor.
3. Expand the node to make your changes.
See Also
Other Resources
Debugging Device Projects
Smart Device Development

Walkthrough: Debugging a Solution That Includes Both


Managed and Native Code
This walkthrough provides steps for debugging a solution that includes both managed, .NET Compact Framework, and native
components. Visual Studio 2005 does not support interop debugging of device applications as such. That is, you cannot have
the native and managed debuggers attached at the same time.
The recommended technique for debugging a solution that incorporates both native and managed elements is to attach
whichever debugger is required for a certain section, for example, a managed section, then detach that debugger and attach
the other when the other is needed. You can repeat these detach/attach steps as often as necessary to step through your
program.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

This walkthrough was written using Visual C# Development Settings. It contains the following sections:
Enabling Attachment of the Managed Debugger
Launching the Application
Setting a Breakpoint in the Native Code
Attaching with the Native Debugger
Running to the Native Breakpoint
Attaching with the Managed Debugger
Setting a Breakpoint in the Managed Code
Running to the Managed Breakpoint
Conclusion
Prerequisites
This walkthrough relies on the solution built with another walkthrough,
Walkthrough: Hello World: A COM Interop Example for Smart Devices. Ensure that this Hello World walkthrough has been
successfully built and run.
Enabling Attachment of the Managed Debugger
By default, devices, including emulators, do not allow the managed debugger to attach to processes that are already running.
Attaching the managed debugger to an already running process is a situation that you typically encounter in device solutions
that include both managed and native code.
Your first step, then, is to set the device to allow the managed debugger to attach to an already running process. You do this by
setting a registry key on the device.
Note
Setting the key affects only attaching to already-running managed processes. It does not affect launching a project using Sta
rt with Debugging (F5). However, if you detach after Start with Debugging, you will need this process to reattach and sta
rt debugging again.

To enable the managed debugger to attach to a running process


1. On the Windows Start menu, point to All Programs, point to Visual Studio 2005, point to Visual Studio Remote
Tools, and then click Remote Registry Editor.
2. In the Select a Windows CE Device window, expand Pocket PC 2003, and then click Pocket PC 2003 SE Emulator.
This is the target device for this walkthrough.
3. Click OK.
The Connecting to Device progress window opens, followed by the opening of the Device Emulator and the Windows
CE Remote Registry Editor.
4. In the Registry Editor, expand Pocket PC 2003 SE Emulator, and then create the following key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsot\.NETCompactFramework\Managed Debugger.
Create the key by right-clicking .NETCompactFramework, pointing to New, and then clicking Key.
Note that there is a space between "Managed" and "Debugger".
5. Create a DWORD named AttachEnabled.
Create the DWORD by right-clicking Managed Debugger, pointing to New, and then clicking DWORD Value.
6. Set the Name as AttachEnabled, and the Value as 1.
Note
Setting this device debug key significantly reduces performance. When you are not debugging, disable this functionalit
y by resetting the data value to 0.

7. Leave the Device Emulator open for the remaining steps to preserve the registry setting. You can close the Registry
Editor.
Launching the Application
Your next step is to launch the InteropSolution application.
To launch the application
1. Open the solution you created in Walkthrough: Hello World: A COM Interop Example for Smart Devices.
Ensure that Pocket PC 2003 SE Emulator appears in the Target Device box on the toolbar.
2. On the Visual Studio Debug menu, click Start Debugging or press F5.
This step immediately deploys the native project, HelloCOMObject, to the emulator without further user intervention.
3. When the Deploy SayHello dialog box opens, select Pocket PC 2003 SE Emulator, and then click Deploy.
This step deploys the managed project.
The application opens in the emulator. Do not click the button yet.
Setting a Breakpoint in the Native Code
Your next step is to set a breakpoint in the native code to prepare for attaching the native debugger.
To set a breakpoint in the native code
1. In Solution Explorer, right-click Hello.cpp, and then on the shortcut menu, click View Code.
2. Insert a breakpoint at the line that begins *text by clicking in the left margin of the Code Editor.
The breakpoint symbol appears as an empty circle with an exclamation point, indicating that the breakpoint cannot
currently resolve. This is because it lacks the appropriate symbols and sources at this time.
3. On the Visual Studio Debug menu, point to Windows, and then click Modules.
The Modules window displays all the modules loaded so far, for example, the managed application SayHello.exe. Note
that the native HelloCOMObject.dll has not yet been loaded, because you have not yet clicked the button in the
application.
Attaching with the Native Debugger
Your next step is to detach the managed debugger so that you can attach with the native debugger. Recall that both debuggers
cannot be attached at the same time for device projects. These are the steps you would use any time you need to switch from
the managed to the native debugger.
To attach with the native debugger
1. On the Visual Studio Debug menu, click Detach All.
This step detaches the managed debugger but allows the application to continue running.
2. On the Debug menu, click Attach to Process.
3. In the Transport box, select Smart Device.
4. To populate the Qualifier box, click Browse.
5. In the Connect to Device dialog box, select Pocket PC 2003 SE Emulator, and then click Connect.
6. To populate the Attach to box, click Select.
7. In the Select Code Type dialog box, select Debug these code types, clear the Managed check box, select the Native
check box, and then click OK.
8. In the Available Processes box, select SayHello.exe, and then click Attach.
You are now attached with the native debugger.
Running to the Native Breakpoint
You are now ready to advance to the breakpoint you set in the native code. When you look at the Modules window again, you
see native modules now present. However, HelloCOMObject.dll is not yet loaded because you have not yet clicked button1.
Note
If you have run this walkthrough earlier, debug symbols might already be loaded, and you can skip those steps. If not, the foll
owing section provides steps for loading them.

To advance execution to the native breakpoint


1. On the Device Emulator form, click button1.
The Hello World! message appears on the form, and hellocomobject.dll appears in the Modules window.
If the Symbol Status column for hellocomobject.dll shows No symbols loaded, follow these steps:
a. Right-click hellocomobject.dll, and then on the shortcut menu, click Load Symbols.
b. In the Find Symbols dialog box, navigate to InteropSolution\HelloCOMObject\Pocket PC 2003
(ARMV4)\Debug\HelloCOMObject.pdb.
c. Click Open.
The Symbol Status column changes from No symbols loaded to Symbols loaded, and the breakpoint indicator
now shows the breakpoint as resolved.
2. On the form on the Device Emulator, click OK on the Hello World! window, and then click button1 again.
The breakpoint indicator shows that execution has stopped at the breakpoint.
3. On the Debug menu, click Step into or press F11.
Note that execution moves to the next line. This shows that you can now step through the native portion of your solution.
Attaching with the Managed Debugger
Your next step is to detach the native debugger so that you can attach with the managed debugger. Recall that both debuggers
cannot be attached at the same time for device projects. These are the steps you would use any time you need to switch from
the native to the managed debugger.
To attach with the managed debugger
1. On the Visual Studio Debug menu, click Detach All.
This step detaches the native debugger, but the application continues to run.
2. On the Debug menu, click Attach to Process, and ensure that the Transport box contains Smart Device.
3. Populate the Qualifier box by clicking Select, then selecting Pocket PC 2003 SE Emulator, and then clicking Connect.
4. To populate the Attach to box, click Select, then select Debug these code types, then check the Managed box, clear
the Native box, and then click OK.
If a message appears reminding you that managed and native debugging are not compatible, click OK.
5. In the Available Processes box, select SayHello.exe, and then click Attach.
Now the managed debugger is attached.
Setting a Breakpoint in the Managed Code
Your next step is to set a breakpoint in the managed code to prepare for attaching the managed debugger.
To set a breakpoint in the managed code
1. In Solution Explorer, right-click Form1.cs, and then on the shortcut menu, click View Code.
2. Insert a breakpoint at the line string text;.

Running to the Managed Breakpoint


You are now ready to advance to the breakpoint you set in the managed code.
To advance execution to the managed breakpoint
In the Device Emulator, click button1.
Execution stops at the breakpoint.
Conclusion
For performance reasons, remember to reset the device registry key to 0 when you no longer need to attach the managed
debugger to an already running process.
See Also
Tasks
How to: Attach to Managed Device Processes
How to: Change Device Registry Settings
Other Resources
Debugging Device Projects
Debugging in Visual Studio
Smart Device Development

Packaging Device Solutions for Deployment


Distributing device applications to end users requires the creation of a CAB file.
In This Section
Packaging Device Solutions Overview
Describes the processes required to package a smart device application for distribution to end users.
IDE Features Supporting Device Application Packaging
Describes the Visual Studio environment elements used for packaging, as well as differences in packaging depending on
target platforms.
Walkthrough: Packaging a Smart Device Solution for Deployment
Provides step-by-step instructions for packaging an application and its resources.
Related Sections
Smart Device Development
Mobile Developer Center
Smart Device Development

Packaging Device Solutions Overview


Deployment is the process by which you transfer an application or component to the target device or devices that it is intended
to run on. Before you can deploy your solution, you must package it into a CAB file. A CAB file is a type of executable archive
file that can contain your application, dependencies such as DLLs, resources, Help files, and any other files you want to include
in it. When you build the CAB project, Microsoft Visual Studio 2005 generates an INF file which is used to create the CAB. The
INF file describes which folder each file is to be installed into, which versions of Windows CE the application is intended to run
on, whether the application is allowed to be uninstalled, and so on. You can also include in your CAB file a custom, native, DLL
to perform any custom install steps such as checking for version number for Windows CE or the .NET Compact Framework,
determining whether other components are present, and so on. After the CAB is copied to the target device, the user taps on it
to begin the installation process. This is called exploding the CAB.
Note
Microsoft Visual Studio 2005 provides tools for packaging your CAB file. It does not provide any tools for deploying the CAB
file to a target device. For simple scenarios, you can drag a CAB file from your desktop machine to your device using an Activ
eSync connection. Several third-party deployment solutions are available for more complex scenarios. For more information,
visit the Mobile and Embedded Application Developer Center.

Visual Studio 2005 makes it possible, in most cases, to perform all of the necessary packaging work directly in the Visual
Studio integrated development environment (IDE). You create a CAB file by first adding a Smart Device Cab project to your
existing solution, then adding the files, shortcuts, and registry entries to it using the same user interface as with desktop setup
projects. When you build the setup project, you create the CAB file.
There are some differences between the CAB files you create for a Pocket PC application and those you create for a
Smartphone application. Pocket PCs based on Windows Mobile 2003SE and earlier do not support compressed CAB files or
signed CAB files. Smartphone CAB files must be compressed and both the EXE or DLL file, and the CAB file itself, must be
digitally signed before they can be installed on the device.
After you have created the CAB file with Visual Studio, the next step is to transfer it to the target device using any of the typical
means for transferring files: via FTP or HTTP requests from the device, manual copying from your desktop development
machine into a folder on a connected device using Windows Explorer, over the air (OTA) transfer for Smartphones, and so on.
See Also
Tasks
Walkthrough: Packaging a Smart Device Solution for Deployment
Concepts
IDE Features Supporting Device Application Packaging
Other Resources
Smart Device Development
File Installation Management in Deployment
Smart Device Development

IDE Features Supporting Device Application Packaging


To package a solution for deployment to Smart Devices, you use the same or similar Microsoft Visual Studio 2005 integrated
development environment (IDE) features that you use for desktop solutions. These features are described in the following
table.
Feature How to Find Remarks
Smart Dev On the File menu, point to Add, c Click on this icon to add a new CAB project to your existing solution. Note that th
ice CAB pr lick New Project, click Other Pr is is the only project type in this dialog box that is valid for Smart Devices. After y
oject temp oject Types, and then click Setu ou select a name for the CAB project and click OK, the project is added to the sol
late p and Deployment. ution and is displayed in Solution Explorer.

File Syste Right-click on the CAB project na Use this editor to specify which files to add to the CAB and the device folders into
m Editor me in Solution Explorer, click Vi which they should be installed.
ew, and then click File System

Registry E Right-click the CAB project name Use this editor to specify any special registry keys required by your application.
ditor in Solution Explorer, click View,
and then click Registry.

Properties Select the CAB project in Solutio Use this window to specify the name, if you have one, of your CE Setup DLL, the
Window f n Explorer, and then click Prope manufacturer name of your application, the minimum and maximum versions of
or the CAB rties Window on the View men Windows CE that your application is designed to run on, and other options.
project u.

Project Pr Right-click the CAB project name Use this dialog box to specify configuration (for example, Debug), output file na
operty Pa in Solution Explorer, and then cl me, and security certificates.
ges ick Properties.
Note
Because these same editors are used for desktop setup projects, some options may be disabled for Smart Device CAB project
s.

In some cases, you may write an application that is only designed to run on particular platforms, such as Windows Mobile
2003 SE and later. In these cases, you can prevent your CAB file from installing on the unsupported platforms that you specify,
but to do so you must manually edit the INF file, then repackage the cab using command-line tools. If you repackage the CAB
using Visual Studio, your changes will be overwritten.
Pocket PC vs. Smartphone
On Windows Mobile 2003 SE and earlier, the primary difference between CAB files for Pocket PC and those for Smartphones is
that Pocket PC does not support compressed or signed CAB files. Smartphone CAB files must be compressed and both the .exe
or .dll file and the CAB file itself must be digitally signed before they can be installed on the device. For more information, see
Security in Device Projects.
Native vs. Managed Applications
The only difference between creating a Smart Device CAB project for an application written in C++ compared to one written in
Visual C# or Visual Basic is that with native applications, you must manually add the system dependencies, atl80.dll,
mfc80U[d].dll, and/or msvcrt[d].dll, to the CAB project. For managed applications, you will never add any .NET Compact
Framework DLLs to your CAB file. If you are targeting version 1.0, then all the DLLs are already present on any device based on
Windows Mobile 2003SE and later. If you are targeting version 2.0 of the .NET Compact Framework, then you will need to
determine whether the device already has that version installed. You can do this by writing a Windows CE Setup DLL that
checks for the version of mscoree.dll on the target device. If version 2.0 of the .NET Compact Framework is not present, then
you can deploy the appropriate CAB that is provided with Visual Studio under the Microsoft Visual Studio
8\SmartDevices\SDK\CompactFramework\2.0\WindowsCE path. You can either deploy this CAB separately from your
application CAB, or you can embed it inside your application CAB.
Caution
When you redistribute a native application that dynamically links to MFC/ATL, and deploy the MFC/ATL runtime DLLs to the
application directory, the application may not link to the DLLs in that directory. On Windows CE, if two DLLs have the same fil
e name but different paths, only the first DLL with that file name is loaded. Subsequent DLLs with the same file name are not
loaded. Instead, the application links to the DLL with that file name that had previously been loaded by another application.
To ensure that the application links against the DLLs in its directory, make sure that no other applications are using DLLs by t
he same file names.

Smart Device vs. Desktop Deployment


Both desktop and device setup projects can be accessed in the New Project dialog box, by clicking Other Project Types, and
then clicking Setup and Deployment. When deploying a desktop application, you have the choice of Setup Project, Merge
Module Project, Cab Project, Web Setup Project, and Setup Wizard. None of these project types can be used for device
applications. ClickOnce deployment is not supported for Smart Devices. To create a CAB file for deployment to any Windows
CE-based device, including Smartphone and Pocket PC, you must use the Smart Device CAB Project.
See Also
Tasks
Walkthrough: Packaging a Smart Device Solution for Deployment
Concepts
Packaging Device Solutions Overview
Smart Device Development

Walkthrough: Packaging a Smart Device Solution for


Deployment
This walkthrough demonstrates how to use Visual Studio 2005 to package your application and its resources into a CAB file so
that it can be deployed to an end-user's smart device.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

In this walkthrough, you begin with any smart device solution written in Visual Basic 2005, Visual C# 2005, or Visual C++
2005. For more information, see Walkthrough: Creating a Simple Application.
This walkthrough shows how to do the following:
Add a CAB project to the solution.
Change the product name.
Change the output path.
Populate the CAB file with the primary output of the application.
Add dependencies if necessary.
Create a shortcut to the application.
Edit a registry entry.
Prerequisites
An existing Smart Device solution. For purposes of this packaging walkthrough, consider creating and building a simple
project, such as the project described in Walkthrough: Creating Windows Forms Applications for a Device.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Setting Up the CAB Project


To add a Smart Device CAB project to the solution
1. Open the existing Smart Device Project and make sure that Solution Explorer is visible.
2. On the File menu, point to Add, and then click New Project.
The Add New Project dialog box appears.
3. In the Project Types pane on the left, expand the Other Project Types node, and click Setup and Deployment.
4. Under the Templates pane on the right, select Smart Device CAB Project.
This is the only type of CAB project valid for smart devices. The other project types are for desktop solutions only.
5. In the Name box, type CABProject, and then click OK.
The CAB project is added to your solution and is visible in Solution Explorer. The two panes of the File System Editor
are now displayed.
Customizing the CAB Project
To change the product name and other project properties
1. In Solution Explorer, select CABProject if it is not selected already.
2. On the View menu, click Properties Window to open the Properties window.
3. In the ProductName field of the property grid, change the value to MyProduct.
The value of the ProductName property determines the name that is displayed for the application in folder names and
in the Add or Remove Programs dialog box.
You can also use this window to change the name of the manufacturer and to specify the minimum and maximum
allowed versions of the operating system.
You can set the OSVersionMin property to 4.21 to indicate that your Pocket PC application has screen orientation
awareness. However, by setting this property to 4.21 you will prevent the application from installing on Pocket PCs
based on Windows Mobile 2003 and earlier. To allow installation on such devices and also indicate screen
orientation awareness to newer devices, you must manually edit the .inf file to set the BuildMax property to one of
the following values:
0xA0000000 to indicate the application supports square screens (240x240 pixels)
0xC0000000 to indicate the application supports screen rotation
-or-
0xE0000000 to indicate the application supports square screens and screen rotation.
For more information, see the MSDN whitepaper Developing Screen Orientation-Aware Applications.
For Pocket PC solutions based on Windows Mobile 2003SE and earlier, the Compress property and the
NoUninstall Device Deployment property must be false. Please note this option can be set to true for devices
equipped with Compact Framework 2.0. For more information, see Properties Window, Smart Device Cab Project.
If you are using a Windows CE setup DLL, use this property grid to specify the file name and location. For more
information on Windows CE setup DLLs, see the Pocket PC or Smartphone SDK documentation.
To change the CAB file name and add authentication
1. In Solution Explorer, right-click CABProject, and then click Properties.
The Property Pages dialog box appears for your CAB project. In the Output file name box, change the name of the CAB
file and path to Debug\MyApp.cab, and then click OK.
2. You can also use this property page to add authentication to your project. Authentication is required for Smartphone
solutions, and is not supported on Pocket PC solutions based on Windows Mobile 2003 SE and earlier. For more
information, see Security in Device Projects.

To add the device project application to the CAB project


1. In the left pane of the File System Editor, select the Application Folder node to specify that the files you select in the
following steps will be installed into this folder on the target device.
If the File System editor is not visible, right-click the CAB project name in Solution Explorer, select View, and click File
System.
2. On the Action menu in Visual Studio, point to Add, and then click Project Output.
3. In the Add Project Output Group dialog box, select your Smart Device Project from the Project drop-down list.
4. From the list of outputs, select Primary output, and then click OK.
Note
When creating a Smart Device CAB project for an application written in C++, you must manually add any dependencies, such
as atl80.dll, mfc80U.dll, and/or msvcr.dll, to the CAB project if you are dynamically linking to these DLLs. Static linking is stro
ngly recommended, however, in order to reduce dependencies on the MFC/ATL DLLs. If you are statically linking, the DLLs sh
ould not be redistributed with your application. If you are dynamically linking, and need to redistribute the DLLs in the CAB, d
o not install the DLLs to the system directory, such as \windows, on the device. Instead, install the DLLs into the local applicati
on directory. If you are redistributing a suite of applications, all of which dynamically link to the ATL/MFC run times, it is reco
mmended to install all the applications, and the run-time DLLs, to a single application directory, and provide shortcuts to the
applications that can be placed in their own folders. This will save some size while avoiding the danger of the DLLs in the syst
em directory being replaced later and breaking any applications that dynamically link to them.

To add dependencies to the CAB project (C++ projects only)


1. In Solution Explorer, right-click on your CAB project name, then point to Add, and click File.
2. Navigate to <Visual Studio installation folder>\VC\ce\dll\<platform>.
3. Select the files to add.
For an MFC project, press CTRL, and click MFC80U.DLL, atl80.dll, and msvcr80.dll. You may also need to click one or
more of the language-specific DLLs if your application requires MFC language specific resources.
For an ATL project, press CTRL, and click atl80.dll and msvcr80.dll. If your ATL solution supports MFC, click
MFC80U.DLL also.
For a Win32 project, click msvcr80.dll.
4. Click Open in the Add Files dialog box to add the files to your CAB project.
5. In the left pane of the File System Editor, right-click File System on Target Machine.
6. Click Add Special Folder, and then click Windows Folder.
7. In the left pane of File System Editor, click the folder that contains your primary output. The DLLs have been added by
default to the same folder as your primary output. To move them to the Windows folder, select the files in the center
pane of the File System Editor, drag them over to the Windows Folder icon.
8. Use the same procedure to add any other dependencies required by your solution. You can add dependencies into any
folder; it is not necessary to add them to the Windows folder.
To create a shortcut for the device project application
1. In the right pane of the File System Editor, select Primary output from <your application project name>.
2. On the Action menu, select Create Shortcut to Primary output from <your application project name>.
This command adds a Shortcut item below the Output item.
3. Right-click the Shortcut item, click Rename, and rename the shortcut to something suitable for a shortcut.

To add a registry entry


1. In Solution Explorer, select the CAB project.
2. On the View menu, point to Editor, and then click Registry.
3. In the Registry Editor, right-click HKEY_CURRENT_USER, and then click New Key on the shortcut menu.
4. When the New Key entry is displayed in the Registry Editor, rename it to SOFTWARE.
5. Right-click this new key, point to New, and then click Key.
6. When the New Key entry is displayed in the Registry Editor, rename it to MyCompany.
7. Right-click the MyCompany entry, and then click Properties Window on the shortcut menu.
The Name value has been changed to MyCompany.
Building and Deploying the CAB File
To build the CAB file
1. On the Build menu, click Build CABProject.
-or-
Right-click CABProject in Solution Explorer, and click Build.
2. On the File menu, click Save All.
CAB files for Smartphone solutions must be digitally signed before they are deployed to an end-user's device. Digital
signing is not supported on Pocket PC solutions based on Windows Mobile 2003SE and earlier. For more information,
see How to: Sign a CAB File (Devices).
To deploy the CAB file to the device
1. In Windows Explorer, navigate to the folder where you stored this solution. You will find the CAB file in the
CABProject\Release folder of your solution.
2. Copy the CAB file to a device that is connected with ActiveSync 4.0 or later.
When a user taps on the CAB file name in File Explorer on the device, Windows CE will explode the CAB, and install the
application on the device.
For more information, see the Smartphone and Pocket PC SDK documentation.
See Also
Other Resources
Smart Device Walkthroughs
Packaging Device Solutions for Deployment
Smart Device Development

Security in Device Projects


Devices restrict the installation and execution of applications and access to system resources based on security policy settings
and security roles. This section includes topics that explain how to set up your application to run on devices with different
security models.
In This Section
Security Overview (Devices)
Describes certificates, security models, provisioning, and other general information.
Graphical Flowchart of Signing Process for Devices
Graphically displays how signing works in device projects.
How to: Import and Apply Certificates in Device Projects
Describes how to use the Visual Studio environment to locate and apply certificates.
How to: Sign a Visual Basic or Visual C# Application (Devices)
Describes how to use the Visual Studio environment to apply certificates to EXE and DLL files in projects that use the .NET
Compact Framework.
How to: Sign a Visual Basic or Visual C# Assembly (Devices)
Describes how to use the Visual Studio environment to apply certificates to projects written against the .NET Compact
Framework.
How to: Sign the Project Output in a Visual C++ Project (Devices)
Describes how to use the Visual Studio environment to apply certificates to project output in Visual C++ projects.
How to: Sign a CAB File (Devices)
Describes how to use the Visual Studio environment to apply certificates to Smart Device Cab Projects.
How to: Provision a Device in a Visual Basic or Visual C# Project
Describes how to use the Visual Studio environment to add certificates to certificate stores for a project that uses the .NET
Compact Framework.
How to: Provision a Device in a Visual C++ Project
Describes how to use the Visual Studio environment to add certificates to certificate stores for projects written in Visual C++.
How to: Provision a Device with a Security Model
Describes how to set the security model for a device.
How to: Query a Device For Its Security Model
Describes how to discover what certificates are installed on a device.
How to: Launch Signtool.exe as a Post-Build Event (Devices)
Describes how to apply certificates after a post-build event has changed the original binaries.
Reference
Security (C# Programming Guide)
Security and Visual Basic Development
Security Best Practices for C++
Security in the .NET Compact Framework
See Also
Other Resources
Smart Device Development
Mobile Developer Center
Smart Device Development

Security Overview (Devices)


Devices restrict the installation and execution of applications and access to system resources, based on security policy settings
and security roles. In order for applications to run correctly on certain devices, they must be signed with the proper certificate,
and that certificate must be present in the device's certificate store.
What Files Should Be Signed?
Best practice requires that EXE, DLL, CAB, and MUI (Multilingual User Interface) files be signed. In managed projects, assembly
files should also be signed.
Security Models
There are also several security models that a device can be set to run in. The different security models can restrict access to
applications that do not have the proper authorization. For more information on device security models, see
Windows Mobile-Based Smartphone Developer's Guide and How to: Provision a Device with a Security Model.
Signing After Post-Build Binary Changes
If you run a post-build step that alters a binary, you need to re-sign the binary; that is, you must disable Authenticode Signing
in the project properties, and sign instead as a post-build step. This action is necessary because anything that alters the binary
after it is signed invalidates the signature. Thus, the binary must be re-signed.
Provisioning
Provisioning a device refers to adding digital certificates to the certificate stores of the device. When an attempt is made to
install or run an application on the device, the operating system of the device checks to see whether the certificate with which
the application is signed is in a certificate store on the device. For more information on certificate stores, see
A Practical Guide to the Smartphone Application Security and Code Signing Model for Developers.
Smartphones are pre-provisioned by mobile operators.
Windows Mobile 5.0-based Pocket PCs are pre-provisioned by OEMs; earlier Pocket PCs typically were not.
Images for the Device Emulator in Visual Studio are pre-provisioned.
For more information on provisioning, see the Smartphone or Pocket PC SDK documentation.
Certificate Files
To aid in developing applications for a variety of security models, Visual Studio 2005 includes the following certificate files,
located by default at \Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SDKTools\TestCertificates:
TestCert_Privileged.pfx
TestCert_UnPrivileged.pfx
These .pfx files contain both the certificate and the corresponding private key. (Signing fails if you try to sign an application
with a certificate that does not have a corresponding private key.) They have no password.
Import these .pfx files to your Personal Certificate Store on the desktop computer. If you try to import them into another store
(such as the Trusted Root Certification Authorities store), Visual Studio displays a detailed Security Warning. For more
information, see How to: Import and Apply Certificates in Device Projects.
See Also
Tasks
How to: Provision a Device in a Visual C++ Project
How to: Provision a Device in a Visual Basic or Visual C# Project
Concepts
Securing Connection Strings
Other Resources
Security in Device Projects
Smart Device Development

Graphical Flowchart of Signing Process for Devices


The graphical representation below shows how the parts of the signing process are related.
The first step in signing your project is to select a certificate. The certificate can be already in your certificate store, or you can
import new ones and select those.
After you have selected your certificate, you must decide whether to provision the device with it. If you do provision the device,
you must select which certificate store on the device (the privileged store or the unprivileged store) will receive the certificate.
Every time you build, your project is signed with the certificate you have selected. Every time you deploy (for example, F5), the
device is provisioned with the selected certificate, which is placed into the selected certificate store on the device.
In the Visual Studio IDE, you typically set your signing options on one of the project property pages.
If you do not want your project Authenticode-signed, then none of this flowchart applies to your project.
Flowchart

See Also
Tasks
How to: Sign a Visual Basic or Visual C# Application (Devices)
How to: Sign a Visual Basic or Visual C# Assembly (Devices)
How to: Sign the Project Output in a Visual C++ Project (Devices)
How to: Sign a CAB File (Devices)
Other Resources
Security in Device Projects
Smart Device Development

How to: Import and Apply Certificates in Device Projects


The Select Certificate dialog box is the central portal for signing device projects. It provides an entry to the Manage
Certificates dialog box and the Certificate Import Wizard as described in the following steps.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Displaying the Select Certificate Dialog Box


How you access the Select Certificate dialog box depends on the type of project you want to sign.
To display the Select Certificate dialog box
1. In Solution Explorer, right-click <Projectname>, and then on the shortcut menu, click Properties.
2. Continue by using one of the following procedures:
For Visual Basic and Visual C# projects: In the Project Designer, click Devices, select Authenticode Signature,
and then click Select Certificate.
In Visual C++ projects, select Authenticode Signing, and then click the ellipsis button in the Certificate property
row.
In Smart Device CAB projects, select Authenticode Signing, and then click Select from Store.
Selecting a Certificate for a Device Project
After you have displayed the Select Certificate dialog box as described in the previous steps, you can select the certificate you
want.
To select a certificate for the project using the Select Certificate dialog box
If the Select Certificate dialog box displays the certificate you want for the project, select the certificate, and click OK.
The project is signed with that certificate when the project is built.
If the Select Certificate dialog box does not display the certificate you want for the project, you can import a certificate
using the Certificate Import Wizard.
Importing a Certificate for a Device Project
The following steps show how to populate the Select Certificate dialog box by importing the test certificates provided by
Visual Studio and applying them to a project. You can follow this same procedure if you want to apply a different certificate.
Visual Studio provides three user interface elements for the task of importing a certificate to apply to a project:
The Select Certificate dialog box, which specifies which certificates are to be applied to the current project.
The Manage Certificates dialog box, which lists the certificate files available on the development computer.
The Certificate Import Wizard, which guides you in selecting your certificate file and specifying where you want to store
it.
To import a test certificate using the Certificate Import Wizard
1. In the Select Certificate dialog box, click Manage Certificates.
The Manage Certificates dialog box displays a list of certificates stored on the development computer.
2. Click Import to open the Certificate Import Wizard.
3. Click Next to open the File to Import page of the wizard.
4. Click Browse to navigate to the TestCertificates folder in Visual Studio.
By default, this folder is located under \Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SDKTools.
5. Change the Files of Type selection to All Files (*.*), select TestCert_Privileged.pfx or TestCert_Unprivileged.pfx, and then
click Open.
6. On the File to Import page of the wizard, click Next to open the Password page.
Leave the Passwod box blank. These test certificates do not have a password.
7. Click Next to open the Certificate Store page. Ensure that Personal is selected in the Certificate store box.
8. Click Next to display the completion page, and then click Finish.
The message Import was successful appears.
9. Click OK to dismiss the message.
The certificate now appears in the Manage Certificates list. Click Close to return to the Select Certificate dialog box.
10. Select the certificate you want, and then click OK.
The certificate is now listed on the property page you started from.

See Also
Tasks
How to: Sign a Visual Basic or Visual C# Application (Devices)
How to: Sign a Visual Basic or Visual C# Assembly (Devices)
How to: Sign the Project Output in a Visual C++ Project (Devices)
How to: Sign a CAB File (Devices)
Concepts
Security Overview (Devices)
Other Resources
Security in Device Projects
Smart Device Development

How to: Sign a Visual Basic or Visual C# Application (Devices)


The following steps assume you have a Smart Device Visual Basic or Visual C# project in your solution. For more information,
see Programming for Devices Using the .NET Compact Framework.
These steps are the same for both EXE and DLL projects.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To sign a Visual Basic or Visual C# device project


1. In Solution Explorer, right-click the Visual Basic or Visual C# project, and then on the shortcut menu, click Properties.
2. On the Devices page, click Authenticode Signature.
3. Click Select Certificate.
4. In the Select Certificate dialog box:
If the certificate you want is displayed in the list, select it, and then click OK to close the dialog box.
If the certificate you want does not appear in the list, click Manage Certificates to open the Manage Certificates
dialog box. For more information, see How to: Import and Apply Certificates in Device Projects.
When you have finished acquiring your certificate, click OK in the Select Certificate dialog box. Certificate details
appear in the Application Signing window of the Devices page.
See Also
Other Resources
Security in Device Projects
Smart Device Development

How to: Sign a Visual Basic or Visual C# Assembly (Devices)


The steps below assume you have a Smart Device Visual Basic or Visual C# project in your solution. For more information on
creating these projects, see Programming for Devices Using the .NET Compact Framework.
These steps are the same for both EXE and DLL projects.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To sign an assembly in a Visual Basic or Visual C# device project


1. In Solution Explorer, right-click the Visual Basic or Visual C# project, and then on the shortcut menu, click Properties.
2. On the Signing page, click Sign the assembly.
3. In the Choose a strong name key file box:
If you want to use a strong name key file that already exists, click <Browse…> to open the Select File dialog.
If you want to create a new strong name key file, click New to open the Create Strong Name Key dialog box.
To delay sign an assembly
After completing the above steps, click Delay sign only.
Use this feature when you do not have access to a private key you need. Delay signing provides the public key and defers
adding the private key until the assembly is handed off. For more information, see
How to: Delay Sign an Assembly (Visual Studio).

See Also
Concepts
Strong-Name Signing for Managed Applications
Other Resources
Security in Device Projects
Smart Device Development

How to: Sign the Project Output in a Visual C++ Project


(Devices)
The following steps assume you have a Smart Device Visual C++ project in your solution. For more information, see
Programming for Devices Using Visual C++.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To sign project output in a Visual C++ device project


1. In Solution Explorer, right-click the Visual C++ project, and then on the shortcut menu, click Properties.
2. Expand the Authenticode Signing page.
3. For the Authenticode Signature property, select Yes.
4. For the Certificate property, click the ellipsis button (…).
5. In the Select Certificate dialog box:
If the certificate you want appears in the list, select it, and then click OK to close the dialog box.
If the certificate you want does not appear in the list, click Manage Certificates to open the Manage Certificates
dialog box. For more information, see How to: Import and Apply Certificates in Device Projects.
When you have finished acquiring your certificate, click OK in the Select Certificate dialog box. The certificate
appears in the Certificate row of the Authenticode Signing page.
6. On the Authenticode Signing page, click OK.
See Also
Other Resources
Security in Device Projects
Smart Device Development

How to: Sign a CAB File (Devices)


The steps below assume you have a Smart Device Cab Project in your solution. For more information, see
Packaging Device Solutions Overview.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To sign a smart device .cab file


1. In Solution Explorer, right-click the Smart Device Cab project, and then click Properties on the shortcut menu.
2. On the Build page, select Authenticode Signature.
3. Click Select from Store.
4. In the Select Certificate dialog box:
If the certificate you want is displayed in the list, select it, and then click OK to close the dialog box.
If the certificate you want does not appear in the list, click Manage Certificates to open the Manage Certificates
dialog box. For more information, see How to: Import and Apply Certificates in Device Projects.
When you have finished acquiring your certificate, click OK in the Select Certificate dialog box. The certificate
appears in the Certificate box of the Build page.
5. On the Build page, click OK.
See Also
Other Resources
Security in Device Projects
Smart Device Development

How to: Provision a Device in a Visual Basic or Visual C#


Project
Provisioning a device refers to adding digital certificates to the certificate stores of the device. For more information, see
A Practical Guide to the Smartphone Security and Code Signing Model for Developers.
The following steps assume:
You have a Smart Device Visual Basic or Visual C# project in your solution. For more information, see
Programming for Devices Using the .NET Compact Framework.
You have signed the application. For more information, see How to: Sign a Visual Basic or Visual C# Application (Devices).
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To provision a device in a managed device project


1. In Solution Explorer, right-click the Visual Basic or Visual C# project, and then on the shortcut menu, click Properties.
2. Open the Devices page.
3. In the Device provisioning box, select one of the following options:
Don’t Provision the Target Device
Provision the Privileged Store
Provision the Unprivileged Store
See Also
Other Resources
Security in Device Projects
Smart Device Development

How to: Provision a Device in a Visual C++ Project


To complete the following procedure:
You must have a Smart Device Visual C++ project in your solution. For more information, see
Programming for Devices Using Visual C++.
You must have signed the project output of your Visual C++ project. For more information on signing Visual C++
projects, see How to: Sign the Project Output in a Visual C++ Project (Devices).
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To provision a device in a Visual C++ device project


1. In Solution Explorer, right-click the Visual C++ project, and then on the shortcut menu, click Properties.
2. Expand the Authenticode Signing page.
3. For the Provision Device property, select either Privileged Certificate Store or Unprivileged Certificate Store.
4. On the Authenticode Signing page, click OK.

See Also
Other Resources
Security in Device Projects
Smart Device Development

How to: Provision a Device with a Security Model


You can set the security model of a device explicitly to test an application under the various security models. If the device is
already locked by the original equipment manufacturer (OEM), then provisioning a different security model might not be
possible. However, if the device is not locked, you can provision it with any security model.
The following security model XML files are included with Visual Studio 2005. The default location is \Program Files\Microsoft
Visual Studio 8\SmartDevices\SDK\SDKTools\SecurityModels.
Locked.xml sets the following two-tier security model:
Prompt before running applications.
Do not run unsigned applications.
Prompt.xml sets the following two-tier security model:
Prompt before running applications.
Run unsigned applications as unprivileged.
Open.xml sets the following one-tier security model:
Do not prompt.
Run all applications, including unsigned, as privileged.
For more information, see Provisioning for Windows Mobile-Based Devices.
The following components are needed in order to provision the device with a security model:
ActiveSync.
RapiConfig.exe, located by default at \Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SDKTools.
Security XML file.
To provision a device with a security model
1. Establish an ActiveSync connection to the device.
2. Type the following command at the command prompt, where securityfile.xml is the security model XML file:

RapiConfig.exe /P /M <securityfile.xml>

See Also
Other Resources
Security in Device Projects
Smart Device Development

How to: Query a Device For Its Security Model


You can query a device to see what certificates are already installed in the device certificate store. You can use that information
to determine which certificate you want to sign your application with.
Querying is accomplished by running RapiConfig.exe and passing in a StoreQuery XML file, which contains the certificate store
query. RapiConfig.exe then outputs an XML file that contains the result of the query.
RapiConfig.exe, CertStoreQuery.xml, and several sample xml query files are located by default in \Program Files\Microsoft
Visual Studio 8\SmartDevices\SDK\SDKTools.
The following components are needed to query the device certificate store:
ActiveSync.
RapiConfig.exe.
Cert Store Query XML file (CertStoreQuery.xml).
To query a device for its security model
1. Establish an ActiveSync connection to the device.
2. Type the following command at the command prompt, where certstorequery.xml is the certificate store query XML file:

Rapiconfig.exe /P /M <certstorequery.xml>

3. View the generated RapiConfigOut.xml file.


See Also
Other Resources
Security in Device Projects
Smart Device Development

How to: Launch Signtool.exe as a Post-Build Event (Devices)


Run signtool.exe as a post-build event when other post-build events change the original binaries. Changes to signed binaries
invalidate the original signing.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To launch signtool.exe as a post-build event in Visual Basic and Visual C# device projects
1. In Solution Explorer, right-click the project, and then on the shortcut menu, click Properties.
2. On the Build Events page (Visual C#) or the Compile page (Visual Basic), click Edit Post-build.
3. In the Post-build Event Command Line dialog box, type the signtool command line with the options you select.
For more information on running signtool from the command line, see SignTool.
To launch signtool.exe as a post-build event in Visual C++ device projects
1. In Solution Explorer, right-click the project, and then on the shortcut menu, click Properties.
2. Under Configuration Properties, expand the Build Events node.
3. Click Post-Build Event.
4. Select the Command Line property, and then click the ellipsis button (…) to open the Command Line dialog box.
5. Type the signtool command line with the options you select.
For more information on running signtool from the command line, see SignTool.
See Also
Other Resources
Security in Device Projects
Smart Device Development

Samples and Walkthroughs (Smart Device Projects)


The following sample projects illustrate the syntax, structure, and techniques used to solve various device programming
challenges.
In This Section
Smart Device Samples
Provides already-built projects for inspection.
Smart Device Walkthroughs
Provides step-by-step instructions on how to create different types of applications and components. Includes both managed
and native projects.
Related Sections
Visual Studio Samples
Provides samples that demonstrate applications.
Visual Studio Walkthroughs
Demonstrates how to create different types of applications and components in various programming languages.
See Also
Other Resources
Smart Device Development
Mobile Developer Center
Smart Device Development

Smart Device Walkthroughs


This topic has been updated for Visual Studio 2005 SP1.
These walkthroughs provide step-by-step instructions for implementing various tasks in smart device projects. Each
walkthrough provides procedures for developing a specific type of device application. Visual Studio walkthroughs designed for
desktop applications typically do not work without modification in device applications, primarily because one or more classes
available in the .NET Framework are not present in the .NET Compact Framework.
The default target device used in the following walkthroughs is the emulator, so you can complete the walkthroughs without a
physical device. If you have a physical device connected to and communicating with the development computer, you can target
that device instead of the emulator. For more information, see
Hardware and Software Requirements for Smart Device Projects.
Note
Some interface elements, such as the New Project Wizard, can obscure the text of a walkthrough. One workaround is to switc
h the Help viewer from the Visual Studio integrated development environment (IDE) browser to an external window. To mak
e this change, on the Tools menu, click Options, click Environment, and then click Help. Select External help and restart t
he IDE for the change to take effect.

The following table has been updated for Visual Studio 2005 SP1.
In This Section
Walkthrough: Creating Windows Forms Applications for a Device
Describes how to develop a simple Windows Forms application and how to download it to a smart device.
Walkthrough: Authoring User Controls for Devices
Demonstrates how to author a user control in managed device projects.
Walkthrough: Adding a Simple Attribute to a User Control
Describes customizing user controls in device projects.
Walkthrough: A Database Master-Detail Application
Describes how to establish a SQL Server Mobile or SQL Server Compact Edition database as a data source, drag data objects
bound to controls onto a Windows Form, configure a master-detail relationship, and more.
Walkthrough: A Parameterized Query Application
Describes how to establish a SQL Server Mobile or SQL Server Compact Edition database as a data source, drag data objects
bound to controls onto a Windows Form, and include a parameterized query in the application.
Walkthrough: Hello World: A COM Interop Example for Smart Devices
Demonstrates how a managed project can host a COM object.
How to: Create a Multiplatform Device project (Visual C++)
Describes how to target multiple devices.
Walkthrough: Creating a Multiplatform MFC Application for Smart Devices
Describes how to build an MFC application that targets multiple platforms.
Walkthrough: Creating an MFC Multiplatform ActiveX Control for Smart Devices
Describes how to build an MFC ActiveX control.
Walkthrough: Creating an ATL Multiplatform ActiveX Control for Smart Devices
Describes how to create a multiplatform smart device ATL project and simple ATL control.
Related Sections
Walkthrough: Debugging a Solution That Includes Both Managed and Native Code
Describes the steps for alternately launching the native and managed debuggers.
Walkthrough: Packaging a Smart Device Solution for Deployment
Describes how to generate a CAB file to hand off to end users for installation on a device, and how to use the IDE, instead of
manually configuring the .inf file, to modify various settings.
Smart Device Samples
Provides complete projects that demonstrate applications based on the .NET Compact Framework, as well as links to samples
using native code.
Visual Studio Walkthroughs
Provides step-by-step instructions for different types of applications for the desktop.
See Also
Other Resources
Samples and Walkthroughs (Smart Device Projects)
Smart Device Development

Walkthrough: Creating Windows Forms Applications for a


Device
In this walkthrough, you build a simple Windows Forms application using either Visual Basic or Visual C#, and then run the
application on a Pocket PC emulator. This walkthrough demonstrates the main difference between desktop and device
programming, namely, that you must target a device. In this walkthrough, the device is a built-in emulator of the Pocket PC
2003.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

This walkthrough was written using Visual Basic Development Settings and Visual C# Development Settings.
This walkthrough consists of five main tasks:
Creating a device project that uses Windows Forms.
Adding a control to the form.
Adding event handling to the control.
Selecting a device on which to run the project.
Building and deploying the application to the device.
Choosing a Target Device
To ensure that you are prompted to select a device when you deploy your solution, complete the following procedure.
To prompt for device choices at deployment time
1. On the Tools menu, click Options, click Device Tools, and then click General. (If Device Tools is not visible, select
Show all settings at the bottom of the Options dialog box.)
2. Select the Show device choices before deploying a device project check box.
Creating the Application
Creating a Windows Forms project, as well as adding controls and event handling, follows the same process for device projects
as it does for desktop projects. The major difference you encounter is the smaller number of classes available in the .NET
Compact Framework.
To create a device project that uses Windows Forms
1. (Visual Basic) On the File menu in Visual Studio 2005, click New Project.
—or—
(Visual C#) On the File menu in Visual Studio 2005, point to New, and then click Project.
2. Under Project Types in the New Project dialog box, expand Visual Basic or Visual C#, expand Smart Device, and
then click Pocket PC 2003.
If the language you want does not at first appear, expand Other Languages. This display is governed by your
development settings.
3. Under Templates, click Device Application.
4. In the Name box, type DeviceSample, and then click OK.
5. (Visual C# only) In the Location box, verify where you want to store your project files, then click OK.
A representation of a Pocket PC device appears in the Windows Forms Designer.
To add a control to the form
1. From the Toolbox, drag a Button control onto the form.
If the Toolbox is not visible, click Toolbox on the View menu.
If the Device Controls tab is not visible in the Toolbox, right-click the Toolbox, and click Show All.
2. Right-click the Button control, and click Properties.
3. In the Properties window, type Say Hello, and press ENTER to set the Text property.
To add event handling for the Button control
1. Double-click the button on the form.
The Code Editor opens with the insertion point positioned in the event handler.
2. Insert the following Visual Basic code:

MessageBox.Show("Hello, World!")

—or—
Insert the following C# code:

MessageBox.Show("Hello, World!");

Building and Testing the Application


At this point, you encounter a difference from desktop projects. In a device project, you can typically choose from among
several targets where the project is to run. In this walkthrough, you choose a Pocket PC emulator. If you have a supported
physical device already in partnership with your development computer, you could also choose the physical device.
To build and test the application
1. On the Debug menu, click Start (or Start Debugging).
2. In the Deploy dialog box, select Pocket PC 2003 SE Emulator, and then click Deploy.
You can view progress in the Status bar.
3. When the application is running on the emulator, tap the button to ensure that "Hello, World!" appears.
Preparing for Additional Walkthroughs
If you plan to do additional walkthroughs or open other projects, you want to shut down the emulator completely and exit this
solution.
To close the emulator and the solution
1. On the File menu of the emulator, click Exit.
2. In the Device Emulator message box, click No to the message Save State Before Exiting?
3. On the Visual Studio Debug menu, click Stop Debugging.
4. If a message appears stating that the connection has been lost, click OK.
5. On the File menu, click Close Solution.
See Also
Tasks
Walkthrough: Creating a Simple Windows Form
Reference
General, Device Tools, Options Dialog Box
Toolbox
Other Resources
Smart Device Walkthroughs
Smart Device Development

Walkthrough: Authoring User Controls for Devices


In this walkthrough you create a control library and author a user control to put in it. Distinguish a user control, a combination
of Windows Forms controls in a single reusable unit, from a custom control, a control that requires UI or functionality not
available through standard controls.
The user control in this walkthrough is a simple clock display for devices, and is modeled after similar desktop walkthroughs,
such as Walkthrough: Authoring a Composite Control with Visual Basic and
Walkthrough: Authoring a User Control with Visual C#.
The walkthrough consists of four main tasks:
Creating a control library and a control.
Renaming the library and the control.
Adding components to the control.
Testing the control on the Device Emulator.
You can use either Visual Basic or Visual C# for this walkthrough. Where both languages call for the same file name but with a
language-specific extension, a vertical bar reminds you to choose the extension for the language you are using, as in
filename.vb|cs.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
This walkthrough was written using Visual Basic Development Settings and Visual C# Development Settings.

Prerequisites
None.
Choosing a Target Device
To ensure that you are prompted to select a device when you deploy your solution, complete the following procedure.
To prompt for device choices at deployment time
1. On the Tools menu, click Options, click Device Tools, and then click General.
(If Device Tools is not visible, select Show all settings at the bottom of the Options dialog box.)
2. Select the Show device choices before deploying a device project check box.
Creating the Project
The name you give a new project also sets the root namespace and the assembly name.
To create the control library and the control
1. (Visual Basic) On the File menu, click New Project.
—or—
(Visual C#) On the File menu, point to New, and then click Project.
2. Under Project Types in the New Project dialog box, expand Visual Basic or Visual C#, expand Smart Device, and
then click Pocket PC 2003.
If the language you want does not at first appear, expand Other Languages. This display is governed by your
development settings.
3. Under Templates, click Control Library.
4. In the Name box, type ctlDevClockLib.
5. (Visual C# only) In the Location box, verify where you want to store your project files.
6. Click OK.
The Component Designer appears.
You have already specified the project name, root namespace, and assembly name (ctlDevClockLib). However, components
within the project have default names assigned by Visual Studio (for example, UserControl1). You typically want to change
these names to more meaningful terms.
To rename the library and the control
1. In Solution Explorer, right-click UserControl1.vb|cs, and then click Properties on the context menu.
2. Change the File Name to ctlDevClock.vb|cs.
3. (Visual C# only) In the message box asking whether you want all references to this code element renamed, click Yes.
The name change in the Properties window now propagates to other references, such as the class name and
constructor.
Next you add components from the Toolbox to provide functionality and user interaction for your user control. In this
walkthrough, you add a Timer control to access the system time and a Label control to display the time.
To add components and change their properties
1. In the Toolbox, double-click Label.
A label control is added to the user control in the Component Designer.
2. In the Properties window for the label control, do the following:
Property Change to
Name lblDisplay

Text (blank space)

TextAlign TopCenter

Font.Size 14

1. In the Toolbox, double-click Timer.


A Timer control appears in the component tray.
2. In the Properties window for the timer control, do the following:
Property Change to
Interval 1000

Enabled True

1.
In the next steps you add an event handler to display clock ticks in the Label control.
To add an event handler
1. In the component tray, double-click timer1 to open the code editor at the tick event.
2. (Visual Basic) Insert this event-handing code:
lblDisplay.Text = Format(Now, "hh:mm:ss")

—or—
(Visual C#)

lblDisplay.Text = DateTime.Now.ToLongTimeString();

3. (Visual Basic) Change the access modifier from Private to Protected, and add the Overridable keyword, so that the
handler code resembles the following:

Protected Overridable Sub Timer1_Tick(ByVal sender As Object, _


ByVal e As System.EventArgs) Handles Timer1.Tick
' Causes the label to display the current time
lblDisplay.Text = Format(Now, "hh:mm:ss")
End Sub

—or—
(Visual C#) Change the access modifier from private to protected, and add the virtual keyword, so that the handler
code resembles the following:

protected virtual void timer1_Tick(object sender, System.EventArgs


e)
{
// Causes the label to display the current time.
lblDisplay.Text = DateTime.Now.ToLongTimeString();
}

4. On the File menu, click Save All.


5. (Visual Basic only) In the Save Project dialog box, save the project as ctlDevClockLib to a location of your choice.
Testing the Control
This simple device application serves as a test container for your control.
To build the control and create a test container
1. On the Build menu, click Build (or Build ctlDevClockLib).
2. On the File menu, point to Add, and then click New Project.
3. In the Add New Project dialog box, click Pocket PC 2003 in the Project Types pane, and then click Device
Application in the Templates pane.
4. In the Name box, type Test, and then click OK.
5. In Solution Explorer, right-click the Test project, and then click Set as StartUp Project.
6. Again right-click the Test project, and then click Add Reference.
7. In the Add Reference dialog box, click the Projects tab, and then double-click ctlDevClockLib.
8. In the Toolbox, locate the ctlDevClockLib Components tab, and then double-click the ctlDevClock component.
The control is loaded into the designer.
9. On the Debug menu, click Start (or Start Debugging).
10. In the Deploy dialog box, select Pocket PC 2003 SE Emulator, and then click Deploy.
See Also
Concepts
Control Type Recommendations
Other Resources
Developing Windows Forms Controls at Design Time
Smart Device Development

Walkthrough: Adding a Simple Attribute to a User Control


This walkthrough demonstrates adding an attribute to a user control in a device project. Specifically, you add a custom
attribute that makes a property of the control invisible at design time. You might want to add this feature to a project to
prevent a property value from being changed.
The process is similar to that of the desktop, except that device projects store this information in a separate metadata file
(.xmta).
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
This walkthrough was written using Visual C# Development Settings.

To create the UserControl1 class


1. On the File menu, point to New, and then click Project.
2. In the Project types pane, expand Visual C#, expand Smart Device, and then click Pocket PC 2003.
3. In the Templates pane, click Control Library.
4. In the Name box, type MyControlLibrary, and then click OK.
The designer opens with a square representing the new user control class.
To add a property
1. In Solution Explorer, right-click UserControl1.cs, and then on the shortcut menu, click View Class Diagram.
A rounded rectangle representing the class diagram opens.
2. Right-click the class diagram, and then on the shortcut menu, click Class Details.
3. In the Properties section of the Class Details window, at the <Add Property> prompt, type MyProperty.
4. In the Type column, replace int with string.
5. Right-click the icon at the beginning of the MyProperty row, and then on the shortcut menu, click Properties.
6. To specify a value for the Custom Attributes property, click the ellipsis button (…) to open the Custom Attributes
dialog box.
7. Type Browsable(false), and then click OK.
Solution Explorer displays a design-time attribute .xmta file (DesignTimeAttributes.xmta) that contains the custom
attribute.
To build the control library
1. In Solution Explorer, right-click UserControl1.cs, and then on the shortcut menu, click View Code.
2. Comment out the line that throws the System.NotImplementedException, and insert return ""; instead as the get
action.
3. On the Build menu, click Build MyControlLibrary.
To test that MyProperty does not appear in the Properties browser
1. In Solution Explorer, right-click MyControlLibrary, on the shortcut menu, point to Add, and then click New Item.
2. In the Add New Item dialog box, select Windows Form, and then click Add.
3. From the Toolbox, drag UserControl1 onto the form.
4. Right-click the user control image on the form, and then on the shortcut menu, click Properties.
MyProperty does not appear in the Property browser.
5. In Solution Explorer, double-click the .xmta file, and then replace false with true.
6. Repeat the steps to view the Properties grid. Note that MyProperty now appears.
See Also
Other Resources
Smart Device Walkthroughs
Smart Device Development

Walkthrough: A Database Master-Detail Application


This topic has been updated for Visual Studio 2005 SP1.
This walkthrough shows you how to use the Visual Studio 2005 environment to connect to a database, select database objects
for inclusion in a project, and create data-bound controls to display the data in a smart device application.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
This walkthrough was written using Visual Basic Development Settings and Visual C# Development Settings.

Prerequisites
Northwind database for SQL Server Mobile Edition (included in Visual Studio 2005).
Northwind database for Microsoft SQL Server 2005 Compact Edition (included when you install SQL Server Compact Edition
for use with Visual Studio 2005 SP1).
Note
If you are not an Administrator on your development computer, you cannot open the Northwind.sdf file in its default locati
on (\Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SQL Server\Mobile\v3.0). Copy the file to the desktop or to
My Documents and open it from there when you are prompted.

The following procedure has been updated for Visual Studio 2005 SP1.
Choosing a Target Device
To ensure that you are prompted to select a device when you deploy your solution, complete the following procedure.
To prompt for device choices at deployment time
1. On the Tools menu, click Options, click Device Tools, and then click General.
2. Select the Show device choices before deploying a device project check box.
Creating the Application
This is a simple Windows Forms application to host the data functionality of this walkthrough.
To create a Windows Forms device project
1. (Visual Basic) On the File menu in Visual Studio 2005, click New Project.
—or—
(Visual C#) On the File menu in Visual Studio 2005, point to New, and then click Project.
2. Under Project Types in the New Project dialog box, expand Visual Basic or Visual C#, expand Smart Device, and
then click Pocket PC 2003.
If the language you want does not at first appear, expand Other Languages. This display is governed by your
development settings.
3. Under Templates, click Device Application.
Note
Do not select Device Application (1.0), which relies on version 1 of the .NET Compact Framework and is not suitable
for this walkthrough.
4. In the Name box, type MasterDetailSample.
5. (Visual C# only) In the Location box, verify where you want to store your project files.
6. Click OK.
A representation of a Pocket PC device appears in the Windows Forms Designer.
Adding Data Functionality
This section consists of the following tasks:
Selecting a data source type
Selecting and configuring a data connection
Selecting database objects
Adding data-bound controls to the form
To select a data source type
1. On the Data menu, click Add New Data Source to open the Data Source Configuration Wizard.
2. On the Choose a Data Source Type page, select Database, and then click Next.
To select and configure a data connection
1. On the Choose Your Data Connection page, click New Connection.
2. In the Choose Data Source dialog box, select Microsoft SQL Server Mobile Edition, and then click Continue.
—or—
In the Choose Data Source dialog box, select Microsoft SQL Server Compact Edition, and then click Continue.
Note
Depending on settings and previous projects, the Add Connection dialog box might appear instead of the Choose Da
ta Source dialog box. If this happens, click Change in the Add Connection dialog box to open the Change Data Sou
rce dialog box. Then select Microsoft SQL Server Mobile Edition or Microsoft SQL Server Compact Edition and cl
ick OK.

3. In the Add Connection dialog box, select My Computer.


4. Again in the Add Connection dialog box, click Browse.
5. In the Select SQL Server Mobile Edition Database File dialog box, select Northwind.sdf, and then click Open.
—or—
In the Select SQL Server Compact Edition Database File dialog box, select Northwind.sdf, and then click Open.
6. In the Add Connection dialog box, leave the Password box empty.
This database has no password.
7. Click Test Connection to verify the connection.
Note
If access to the Northwind.sdf file is denied, copy the file to the desktop, and browse to that copy to open. This situatio
n can occur if you do not have sufficient rights on the development computer to open the file in its default location, whi
ch is listed at the beginning of this walkthrough.

8. Click OK on the message box that shows the connection succeeded, and then click OK to close the Add Connection
dialog box.
9. Close the Choose Your Data Connection page by clicking Next.
10. In the message box that asks whether you want to copy the file to your project, click Yes.

To select database objects


1. On the Choose Your Database Objects page, expand the Tables node, and then select the Customers and Orders
tables.
2. Click Finish.
The NorthwindDataset is created. You can view this data source by selecting Show Data Sources on the Data menu.

To add data-bound controls to the form


1. In the Data Sources window, select the Customers table, click the drop-down arrow, and then select the DataGrid
option.
2. Drag the Customers table from the Data Sources window onto the form in the designer.
Locate the grid toward the top of the window.
3. In the Data Sources window, expand the Customers table to expose the Orders table.
Note
This is the Orders table as it appears within the Customers table, not the Orders table that is at the same tree level as t
he Customers table.

4. Click the drop-down arrow for this Orders table, and select the DataGrid option.
5. Drag this Orders table from the Data Sources window onto the form in the designer.
Locate the grid toward the bottom of the window.
Testing the Application
In this section you build the application, download it to the Pocket PC 2003 SE emulator, and verify that the application works
correctly.
To test the application
1. On the Debug menu, click Start or Start Debugging.
2. In the Deploy dialog box, select Pocket PC 2000 SE Emulator, and then click Deploy.
Deployment progress appears in the Status bar. Deployment to the emulator can take some time.
3. When the application is running on the emulator, use the up and down arrows on your keyboard or the NAVIGATION
control on the emulator to change the selected records in the Customers grid. Verify that the selected records change in
the Orders grid.
Preparing for Additional Walkthroughs
If you plan to do additional walkthroughs or open other projects, you want to shut down the emulator completely and exit this
solution.
To close the emulator and the solution
1. On the File menu of the emulator, click Exit.
2. In the Device Emulator message box, click No to the message asking if you want to save the emulator state.
3. In the message box that advises the connection has been lost, click OK.
4. (Visual Basic) On the File menu, click Close Project.
If you are prompted to save the project or solution, click Save if you want to use it again later; otherwise, click Discard
and your files will not be saved.
—or—
(Visual C#) On the File menu, click Close Solution.
See Also
Tasks
How to: Install Sample Databases
Reference
Data Source Configuration Wizard
Other Resources
Data Walkthroughs
Accessing Data (Visual Studio)
Smart Device Development

Walkthrough: A Parameterized Query Application


This topic has been updated for Visual Studio 2005 SP1.
This walkthrough shows you how to use the Visual Studio 2005 environment to develop a simple parameterized query
application. Databinding and much of the user interface are generated for you automatically. Relying on the familiar
Northwind database, this application provides for the scenario where smart device users need to determine the Shipping
Country when they know only the Order Number. The application you build here provides for user input of the Order Number
and the consequent display of the corresponding Shipping Country.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
This walkthrough was written using Visual Basic Development Settings and Visual C# Development Settings.

The following procedures have been updated for Visual Studio 2005 SP1.
The installed database varies according to which release of Visual Studio you have installed:
Microsoft SQL Server Mobile Edition (Visual Studio 2005)
Microsoft SQL Server 2005 Compact Edition (Visual Studio 2005 SP1)
Prerequisites
The Northwind database for SQL Server Mobile or SQL Server Compact Edition, included in Visual Studio 2005.
Note
If you are not an Administrator on your development computer, you cannot open the Northwind.sdf file in its default locati
on, \Program Files\Microsoft Visual Studio 8\SmartDevices\SDK\SQL Server\Mobile\v3.0. Copy the file to the desktop or to
My Documents and open it from there when you are prompted.

Choosing a Target Device


To ensure that you are prompted to select a device when you deploy your solution, complete the following procedure.
To prompt for device choices at deployment time
1. On the Tools menu, click Options, click Device Tools, and then click General.
2. Select the Show device choices before deploying a device project check box.
Creating the Application
This is a simple Windows Forms application to host the data functionality of this walkthrough.
To create a Windows Forms device project
1. (Visual Basic) On the File menu in Visual Studio 2005, click New Project.
—or—
(Visual C#) On the File menu in Visual Studio 2005, point to New, and then click Project.
2. Under Project Types in the New Project dialog box, expand Visual Basic or Visual C#, expand Smart Device, and
then click Pocket PC 2003.
If the language you want does not at first appear, expand Other Languages. This display is governed by your
development settings.
3. Under Templates, click Device Application.
Note
Do not select Device Application (1.0), which relies on version 1.0 of the .NET Compact Framework and is not suitabl
e for this walkthrough.

4. In the Name box, type ParamQuerySample.


5. (Visual C# only) In the Location box, verify where you want to store your project files.
6. Click OK.
A representation of a Pocket PC device appears in the Windows Forms Designer.
Adding Data Functionality
This section consists of the following tasks:
Selecting a data source type.
Selecting and configuring a data connection.
Selecting database objects.
Adding data-bound controls to the form.
To select a data source type
1. On the Data menu, click Add New Data Source to open the Data Source Configuration Wizard.
2. On the Choose a Data Source Type page, select Database, and then click Next.
To select and configure a data connection
1. On the Choose Your Data Connection page, click New Connection.
2. In the Choose Data Source dialog box, select Microsoft SQL Server Mobile Edition, and then click Continue.
—or—
In the Choose Data Source dialog box, select Microsoft SQL Server Compact Edition, and then click Continue.
Note
Depending on settings and previous projects, the Add Connection dialog box might appear instead of the Choose Da
ta Source dialog box. If this happens, click Change in the Add Connection dialog box to open the Change Data Sou
rce dialog box. Then select Microsoft SQL Server Mobile Edition or Microsoft SQL Server Compact Edition, and cl
ick OK.

3. In the Add Connection dialog box, select My Computer.


4. Again in the Add Connection dialog box, click Browse.
5. In the Select SQL Server Mobile Edition Database File dialog box, select Northwind.sdf, and then click Open.
—or—
In the Select SQL Server Compact Edition Database File dialog box, select Northwind.sdf, and then click Open.
6. In the Add Connection dialog box, leave the Password box empty.
This database has no password.
7. Click Test Connection to verify the connection.
Note
If access to the Northwind.sdf file is denied, copy the file to the desktop, and browse to that copy to open. This situatio
n can occur if you do not have sufficient rights on the development computer to open the file in its default location, whi
ch is listed toward the beginning of this walkthrough.
8. Click OK on the message box that shows the connection succeeded, and then click OK to close the Add Connection
dialog box.
9. Close the Choose Your Data Connection page by clicking Next.
10. In the message box that asks whether you want to copy the file to your project, click Yes.
To select database objects
1. On the Choose Your Database Objects page, expand the Tables node, and then select the Orders table.
2. Click Finish.
The NorthwindDataset is created. You can view this data source by selecting Show Data Sources on the Data menu.

To create the query


1. In the Data Sources window, expand the Orders table.
2. Click the Ship Country column, click the drop-down arrow, and then select the Label option.
3. Drag the Ship Country column onto the form in the designer.
4. On the label control in the designer, click the smart tag, and then on the shortcut menu, click Add Query.
5. In the Search Criteria Builder dialog box, click Query Builder.
6. In the Filter column of the Order ID row, type a question mark (?).
This symbol indicates that users of the application will have to enter a value for Order ID.
7. Click OK.
The WHERE clause in the Query Text box should now read ([Order ID]=@PARAM1).

8. Click OK to close the Search Criteria Builder dialog box.


A panel appears on the form in the designer.

To refine the user interface


1. Right-click the PARAM1 label control in the designer, and then on the shortcut menu, click Properties.
2. Change the Text property to Order ID.
3. Select the FillBy button, and then change its text property to Show country.
4. Expand the panel and controls to eliminate the scroll bars and show all the text. Be especially careful that the
Ship_CountryLabel and its text box are not hidden behind the FillByPanel and its controls.
Testing the Application
In this section you build the application, download it to the Pocket PC 2003 SE emulator, and verify that the application works
correctly.
To test the application
1. On the Debug menu, click Start or Start Debugging.
2. In the Deploy dialog box, select Pocket PC 2000 SE Emulator, and then click Deploy.
Deployment progress appears in the Status bar. Deployment to the emulator can take some time.
3. When the application is running on the emulator, type an order number, which run from 10000 to 11077 in the
Northwind database, and then click Show country.
The Ship Country for that order appears in the label control.
Preparing for Additional Walkthroughs
If you plan to do additional walkthroughs or open other projects, you want to shut down the emulator completely and exit this
solution.
To close the emulator and the solution
1. On the File menu of the emulator, click Exit.
2. In the Device Emulator message box, click No to the message asking if you want to save the emulator state.
3. (Visual Basic) On the File menu, click Close Project.
—or—
(Visual C#) On the File menu, click Close Solution.
If you are prompted to save the project or solution, click Save if you want to use it again later; otherwise, click Discard
and your files will not be saved.
See Also
Tasks
How to: Create Parameterized Queries (Devices)
How to: Install Sample Databases
Reference
Data Source Configuration Wizard
Other Resources
Smart Device Walkthroughs
Data in Managed Device Projects
Smart Device Development

Walkthrough: Hello World: A COM Interop Example for Smart


Devices
This walkthrough combines in one solution a simple COM object and a managed application.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
This walkthrough was written using Visual C++ Development Settings.

Create a COM Object


To create a Smart Device ATL project
1. On the File menu, point to New, click Project, expand the Visual C++ node in the Project types pane, and then click
Smart Device.
2. In the Templates pane, click ATL Smart Device Project.
3. In the Name box, type HelloCOMObject.
4. In the Solution name box, type InteropSolution.
5. Click OK to launch the ATL Smart Device Project Wizard.
6. Click Finish to close the wizard.
For this walkthrough, you do not need to change any default settings in the wizard.
To add a class
1. In Solution Explorer, right-click the HelloCOMObject project, point to Add, and then click Class to open the Add Class
dialog box.
2. In the Categories pane, click Smart Device.
3. In the Templates pane, click ATL Simple Object, and then click Add to open the ATL Simple Object Wizard.
4. In the Short name box, type Hello.
5. In the left pane, click Options to open the Options page.
6. Under Threading model, select Free, and then click Finish.
To add a method to the class
1. Open the Class View window from the tab on the desktop or from the View menu.
2. Expand HelloCOMObject to display the IHello interface.
3. Right-click IHello, point to Add, and then click Add Method to open the Add Method Wizard.
4. In the Method name box, type HelloWorld.
5. In the Parameter type box, select BSTR*.
6. In the Parameter name box, type text.
7. Under Parameter attributes, select out.
8. Click Add.
The method box displays [out] BSTR* text.
9. Click Finish to close the Add Method Wizard.
The method STDMETHOD(HelloWorld)(BSTR* text) is displayed in the file Hello.h.

To add implementation to the method


1. In Solution Explorer, double-click Hello.cpp to open that file in the Code Editor.
2. In the STDMETHODIMP section, insert the following implementation code before the return statement:

*text = SysAllocString(L"Hello World!");

3. On the Build menu, click Build HelloCOMObject.


A COM object is now part of the solution, and the first part of the walkthrough is complete.
Create a Managed Project
To add a managed project to the solution
1. In Solution Explorer, right-click InteropSolution, point to Add, add then click New Project.
2. In the Project types pane, navigate to the Visual C# node, expand it, expand the Smart Device node, and then click
Pocket PC 2003.
3. In the Templates pane, click Device Application.
4. In the Name box, type SayHello, and then click OK.
The SayHello managed project is created as part of the solution, and a Pocket PC form appears in the Designer window.
Add the COM Object as a Reference in the Managed Project
To add the COM object as a reference in the managed project
1. In Solution Explorer, right-click the SayHello project, and then on the shortcut menu, click Add Reference.
2. In the Add Reference dialog box, click Browse.
The SayHello folder is displayed in the Look in box.
3. Navigate to the parent folder (in this walkthrough, InteropSolution).
4. In the window showing folder contents, double-click HelloCOMObject, double-click Pocket PC 2003 (ARMV4), double-
click Debug, and then click HelloCOMObject.dll.
5. Click OK to close the Add Reference dialog box.
6. In Solution Explorer, right-click Form1.cs, and then on the shortcut menu, click View Code.
7. In the Using directives region at the top of the file, add the following code:

using HelloCOMObjectLib;

Add Event Handling to the Managed Project


To add event handling to the managed project and build it
1. Open the Form1 Designer.
2. From the Toolbox, drag a button onto the form.
3. Double-click the button to open the code editor at the click event.
4. Insert the following event-handling code for the button:

string text;
HelloClass h = new HelloClass();
h.HelloWorld(out text);
MessageBox.Show(text);

5. On the Build menu, click Build SayHello.


Make Final Adjustments to the Solution
To configure the solution for deployment
1. In Solution Explorer, right-click the SayHello project, and then on the shortcut menu, click Set as StartUp Project.
2. In Solution Explorer, right-click the InteropSolution, and then on the shortcut menu, click Project Dependencies.
3. In the Project Dependencies dialog box, select SayHello in the Projects box, and then in the Depends on box, select
HelloCOMObject.
4. Click OK.
The solution is ready for deployment.
Deploy the Mixed Solution
To deploy the solution
1. On the Debug menu, click Start Without Debugging.
2. In the Deploy dialog box, select Pocket PC 2003 SE Emulator, and then click Deploy.
Save this Solution for use in the Walkthrough: Debugging a Solution That Includes Both Managed and Native Code.
See Also
Concepts
COM Interoperability for Devices
Other Resources
Smart Device Walkthroughs
Smart Device Development

How to: Create a Multiplatform Device project (Visual C++)


You can target multiple devices from the same development project with C++ for devices. Using Visual Studio 2005, you can
have one device project target multiple device platforms, such as Pocket PC and Smartphone, and you can add a device project
to a desktop project. For more information, see Device Support for Desktop Projects.
There are two ways that you can set your device project to target multiple platforms:
1. When you create your project, using the Smart Device Project Wizard. This is the more efficient technique.
The Smart Device Project Wizard generates the project files for all the selected device platforms, such as source,
header, and resource files. You can install additional new platforms by installing the platform's or device's SDK.
Using Visual Studio 2005, you can install any device SDK supporting Smartphone or Pocket PC 2003 or higher, as well as
any Windows CE device version 5.0 or higher. For additional information see
How to: Create a Multiplatform Device Project Using the Wizard.
2. After you create your project, using the New Platform pane of the
Configuration Manager Settings, Smart Device Project Wizard dialog box. For additional information see
How to: Add a New Platform to a Device Project.
See Also
Tasks
How to: Change the Default Device (Native Projects)
Using Resources on Multiple Platforms
Other Resources
How to Maintain a Single Binary for Pocket PC and Smartphone
Smart Device Development

How to: Create a Multiplatform Device Project Using the


Wizard
There are advantages to using the Smart Device Application Wizard to create a multiplatform device project when you
create a project, rather than adding a platform after the project has been created. These are the following:
When you select more than one platform on the Platforms page in the application wizard, a resource file will be
generated and configured for each of your platforms. However, if you add a platform after you create your project, you
will need to manually add platform and resource files. For more information, see Using Resources on Multiple Platforms.
When you select more than one platform on the Platforms page in the application wizard, the generated files have an
#if defined statement embedded in the source to accommodate multiplatform coding. However, if you add a platform
after you create your project, you will need to manually add the #if defined statement to the appropriate sections of the
code.
The following procedures show how to use each of these techniques. For more information, see
Code Explanation: Wizard-Generated Code in Visual C++ Device Projects.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To create a multiplatform device project using the New Project Wizard


1. On the File menu, point to New, and then click Project.
The New Project dialog box appears.
2. Under Project types, expand the Visual C++ node, click Smart Device, and then click MFC Smart Device Application
or another one of the available project types.
3. In the Name box, type MultiPlatformProject.
4. In the Location box, verify where you want to store your project files, and then click OK.
The <Project Type> Smart Device Application Wizard appears.
5. Click Next, and then on the Platforms pane, select the platforms you want to target, such as Pocket PC 2003 and
Smartphone 2003.
6. Click Finish.
Your project will be displayed in Solution Explorer.
To add a new device configuration using the Configuration Manager
1. On the Visual Studio Build menu, click Configuration Manager.
The Configuration Manager dialog box appears.
2. On the Active solution configuration drop-down list, select New to add a new configuration.
The New Solution Configuration dialog box appears.
3. In the Name box, type a name for the new configuration.
4. In the Copy settings from box, specify an existing configuration.
5. Click OK.
See Also
Tasks
How to: Add a New Platform to a Device Project
How to: Change the Default Device (Native Projects)
Using Resources on Multiple Platforms
Other Resources
How to Maintain a Single Binary for Pocket PC and Smartphone
Smart Device Development

How to: Add a New Platform to a Device Project


The following procedures show how to add a platform to an existing device project.
This is an alternative to creating a multiplatform project from inception using the wizard. Using the wizard is a superior way.
For more information see How to: Create a Multiplatform Device Project Using the Wizard.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To add a new platform using the Configuration Manager


1. On the Build menu of your device project, click Configuration Manager
The Configuration Manager Dialog Box appears.
2. Under Active Solution Platform drop-down list, select New to add a new configuration.
The New Solution Platform dialog box appears.
3. Under Name, select or type in the platform you wish to add, such as Smartphone 2003. .
4. From the Copy settings from drop-down list, you can select an existing platform to copy the settings for your new
platform, or create a new platform with empty settings. In the latter case, you have to set the project settings manually.
5. Make sure the Create new project platforms check box is selected.
If not, you will have to manage and add the configuration files, any platform dependent code that the wizard can
generate for you, and other project files such as resources.
6. Click OK.
The New Solution Platform dialog box generates the project files for the newly added platforms, such as source,
header, and resource files.
7. Click OK to close the Configuration Manager dialog box.
Note
Having created a device project, you can always add more platforms, after the initial creation. However, adding a new p
latform to the project after the initial creation does not add the additional dependent run-time DLLs to the Additional
Files configuration property. For example, if your application dynamically links to MFC, you will need to add the followi
ng DLLs to the Additional Files property for the newly added platform: Mfc80u.dll, Atl80.dll, Msvcr80.dll. This ex
ample assumes a retail configuration.

See Also
Tasks
How to: Change the Default Device (Native Projects)
Using Resources on Multiple Platforms
Smart Device Development

Walkthrough: Creating a Multiplatform MFC Application for


Smart Devices
You can use Visual C++ to write code targeting multiple devices. The following walkthrough illustrates how to build a
multiplatform MFC application. For more information, see MFC Smart Device Application Wizard.
Create an MFC Multiplatform Project
This walkthrough consists of three main tasks:
Creating a multiplatform smart device MFC project.
Adding code to the multiplatform OnDraw() method.
Deploying the multiplatform solution.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.
This walkthrough was written using Visual C++ Development Settings.

To create a multiplatform smart device MFC project


1. On the File menu, point to New, click Project, expand the Visual C++ node in the Project Types pane, and then click
Smart Device.
2. In the Templates pane, click MFC Smart Device Application.
3. In the Name box, type HelloMFC.
4. Click OK to launch the MFC Smart Device Application Wizard.
5. Click Next to select the platform SDKs to be added to the current project.
6. From the Installed SDKs pane, select the platforms you want to add to the current project, such as, Smartphone 2003
and Pocket PC 2003.
7. Click Next to open the Application Type page.
8. Select the Single Document and Use MFC in a Static Library check boxes. Leave the Document/View architecture
support check boxselected.
9. Click Finish to complete and close the wizard, or click Next to accept the defaults for all the remaining options in the
wizard.
Note
Having created a device project, you can always add more platforms ; however, adding a new platform to the project after th
e initial creation does not add the additional dependent run-time DLLs to the Additional Files configuration property for the
added platform. For example, if your application dynamically links to MFC, you will need to add the following DLLs to the Ad
ditional Files property for the configuration of the new platform you added: Mfc80u.dll, Atl80.dll, Msvcr80.dll. This exampl
e assumes a retail configuration.

Add Code to the Multiplatform OnDraw() Method


To add code to the OnDraw() method
1. In Solution Explorer, expand the Source Files node. Double-click HelloMFCView.cpp to open the source file in the
editor.
2. Modify the OnDraw signature to uncomment pDC in the OnDraw(CDC* pDC) method. The resulting line should read:
void CHelloMFCView::OnDraw(CDC* pDC)

3. Insert the following code after the //TODO comment in the OnDraw method:

// Define a rectangle to draw on the screen.


CRect rect;
// Use the client area of the MFC form for drawing.
GetClientRect(&rect);
// Draw the text on the screen.
pDC->DrawTextW(_T("Hello World"),11, &rect,1);

4. On the Build menu, click Rebuild Solution.


Choosing a Target Device
To ensure that you are prompted to select a device when you deploy your solution, complete the following procedure.
To prompt for device choices at deployment time
1. On the Tools menu, click Options, click Device Tools, and then click General.
If Device Tools is not visible, select Show all settings at the bottom of the Options dialog box.
2. Select the Show device choices before deploying a device project check box.
Deploy the Multiplatform MFC Solution
To deploy the solution
1. On the Target Device drop-down list on the Visual Studio toolbar, select your target, for example, Pocket PC 2003 SE
Emulator or Pocket PC 2003 Device.
2. On the Build menu, click Deploy.
For more information about the code generated for this walkthrough, see
Code Explanation: Hello World: A Multiplatform MFC Application for Smart Devices.
See Also
Other Resources
Smart Device Walkthroughs
How to: Create a Multiplatform Device project (Visual C++)
Smart Device Development

Code Explanation: Hello World: A Multiplatform MFC


Application for Smart Devices
Whether you use Visual Studio C++ to target Windows CE (Mobile) and other popular mobile devices, or embedded Visual
C++ to develop device applications, you will find that the C++ Multiplatform MFC Application for Smart Devices Wizard
simplifies most of the mundane tasks of generating project files. Some of the files include resource files, and multiplatform
project configuration files. The wizard also introduces jumpstart code, so you can concentrate on developing your core
business application functions.
This walkthrough familiarizes you with the code automatically generated by the Multiplatform MFC Application for Smart
Devices Wizard, so you can easily extend and modify the application to suit your needs.
For more information, see Walkthrough: Creating a Multiplatform MFC Application for Smart Devices,
MFC Reference for Devices, and MFC Reference.
Code Listing for a Multiplatform MFC Application for Smart Devices C++
The wizard generated code includes the following:
include section.

#include "stdafx.h"

stdafx.h. For more information, see Precompiled Header Files.

#include "MFCHello1.h"
#include "MFCHello1Doc.h"
#include "MFCHello1View.h"

// Debug configuration.

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

IMPLEMENT_DYNCREATE(CMFCHello1View, CView)

MFC message maps and more specifically BEGIN_MESSAGE_MAP.


IMPLEMENT_DYNCREATE see IMPLEMENT_DYNCREATE.

BEGIN_MESSAGE_MAP(CMFCHello1View, CView)
END_MESSAGE_MAP()

Construction code. For more information, see Constructor Design and for exception handling, see Handling Exceptions.

// CMFCHello1View construction/destruction
CMFCHello1View::CMFCHello1View()
{
// TODO: add construction code here.
}
CMFCHello1View::~CMFCHello1View()
{
}
MFC PreCreateWindow.

BOOL CMFCHello1View::PreCreateWindow(CREATESTRUCT& cs)


{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs.

return CView::PreCreateWindow(cs);
}

Remember that the drawing on the screen, screen painting, happens in the CView::OnDraw method. In this method you
can take control of the Graphical Device interface (GDI), namely in code, CDC* pDC, which is provided to you as a
parameter. Do not forget to uncomment it. For example, you can use the full power of the GDI for everything from text to
drawing graphics for animated games in your application. In this GDI example, CDC::DrawText method is then used for
drawing the "Hello World" text inside the rectangle defined by CWnd::GetClientRect.
BEGIN_MESSAGE_MAP.
CDC Class.
GetClientRect.

// CMFCHello1View drawing
void CMFCHello1View::OnDraw(CDC* pDC)
{
CMFCHello1Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);

// TODO: add draw code for native data here.


CRect rect;
GetClientRect(&rect);
// Length and string to draw are hard coded for simplicity of
// example.

DrawText and other related methods. For more information, see CDC Class.

pDC->DrawTextW(_T("Hello World"),11, &rect,1);


// nCount ( set to 11) can be a –1, then
//lpszString is assumed to be
// a long pointer to a null-terminated string
// and DrawText method automatically
// computes the character count.
}
// CMFCHello1View diagnostics
#ifdef _DEBUG
void CMFCHello1View::AssertValid() const
{
CView::AssertValid();
}
#ifndef _WIN32_WCE
void CMFCHello1View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
#endif // !_WIN32_WCE
CMFCHello1Doc* CMFCHello1View::GetDocument() const
// non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMFCHello1Doc)));
return (CMFCHello1Doc*)m_pDocument;
}
#endif //_DEBUG
// CMFCHello1View message handlers

Information Available in the Readme File Created by the Wizard


The Application Wizard has created this MFCHello1 application for you. This application not only demonstrates the basics of
using the Microsoft Foundation Classes, but is also a starting point for writing your application.
The files generated are listed here, along with a summary of what you will find in each file. These files collectively make up
your jumpstart point into your MFC application development.
The name HelloMFC is used for an example. You may wish to use your own project name.
HelloMFC.vcproj
The main project file for VC++ projects generated using an application wizard. It contains information about the version of
Visual C++ that generated the file, and information about the platforms, configurations, and project features selected with the
application wizard.
HelloMFC.h
The main header file for the application. It includes other project-specific headers and declares the CMFCHello1App application
class.
HelloMFC.cpp
The main application source file that contains the class definition for the application class CMFCHello1App.
HelloMFCppc.rc
The project's main reasource file listing of all of the Microsoft Windows resources that the project uses when compiling for the
Pocket PC platform, or a platform that supports the same user interface model. It includes the icons, bitmaps, and cursors that
are stored in the RES subdirectory. This file can be directly edited in Microsoft Visual C++. Your project resources are in 1033.
When the .rc file is persisted, the defines in the data section are persisted as the hexadecimal version of the numeric value they
are defined to, rather than the friendly name of the define.
res\HelloMFCppc.rc2
A file containing resources that are not edited by Microsoft Visual C++. You should place all resources not editable by the
resource editor in this file.
HelloMFCsp.rc
The project's main reasource file listing of all of the Microsoft Windows resources that the project uses when compiling for the
Smartphone platform, or a platform that supports the same user interface model. It includes the icons, bitmaps, and cursors
that are stored in the RES subdirectory. This file can be directly edited in Microsoft Visual C++. Your project resources are in
1033. When the .rc file is persisted, the defines in the data section are persisted as the hexadecimal version of the numeric
value they are defined to rather than the friendly name of the define.
res\HelloMFCsp.rc2
A file containing resources that are not edited by Microsoft Visual C++. You should place all resources not editable by the
resource editor in this file.
res\HelloMFC.ico
An icon file, used as the application's icon. This icon is included by the main resource file.
MainFrm.h, MainFrm.cpp
Files containing the frame class CMainFrame, which is derived from CFrameWnd and controls all SDI frame features.
The application wizard also creates one MFC document type and one MFC view:
HelloMFCDoc.h, HelloMFCDoc.cpp
Files containing your HelloMFCDoc class. Edit these files to add your special document data and to implement file saving
and loading (using CMFCHello1Doc::Serialize).
HelloMFCView.h, HelloMFCView.cpp
Files containing your HelloMFCView class. HelloMFCView objects are used to view HelloMFCDoc objects.
StdAfx.h, StdAfx.cpp
Files used to build a precompiled header (PCH) file named HelloMFC.pch and a precompiled types file named StdAfx.obj.
Resourceppc.h and Resourcesp.h
The standard header file, which defines new resource IDs. Microsoft Visual C++ reads and updates this file.
The application wizard uses TODO: to indicate parts of the source code you can add to or customize.
If your application uses MFC in a shared DLL, and your application is in a language other than the operating system's current
language, you may want to copy the corresponding localized resource's MFC80XXX.DLL to your application directory. In this
name, "XXX" stands for the language abbreviation. For example, MFC80DEU.DLL contains resources translated to German.
Otherwise, some of the UI elements of your application will remain in the language of the operating system.
See Also
Other Resources
Samples and Walkthroughs (Smart Device Projects)
Smart Device Development

Walkthrough: Creating an MFC Multiplatform ActiveX Control


for Smart Devices
You can use Visual C++ to write MFC ActiveX control code targeting multiple devices. This walkthrough illustrates how to build
a C++ multiplatform MFC ActiveX control for use with multiple devices.
Create an MFC ActiveX Multiplatform Control Project
This walkthrough consists of three main tasks:
Creating a multiplatform smart device MFC ActiveX control project.
Adding code to the OnDraw() method of MFC ActiveX control.
Deploying the Multiplatform MFC ActiveX control solution for testing.
For more information, see MFC Smart Device ActiveX Control Wizard.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

This walkthrough was written using Visual C++ Development Settings.


To create a Multiplatform Smart Device MFC ActiveX control project
1. On the File menu, point to New, click Project, expand the Visual C++ node in the Project Types pane, and then click
Smart Device.
2. In the Templates pane, click MFC Smart Device ActiveX Control.
3. In the Name box, type MFCAX.
4. In the Solution box, accept the default option Create directory for solution.
5. Click OK to launch the MFC Smart Device ActiveX Control Wizard.
6. Click Next on the MFC Smart Device Application Wizard Welcome page. The
Platforms, MFC Smart Device ActiveX Control Wizard appears, and you can select the platform or platforms to be added
to the current project.
From the Installed SDKs pane, select the platforms you would like to target and add to the current project, such as
Smartphone 2003 and Pocket PC 2003. To add a platform, select the platform in the left pane, such as Smartphone
2003, and click the button with the right arrow (>) on it. To remove a platform, select the platform in the right pane, such
as Pocket PC 2003, and click the button with the left arrow (<) on it.
7. Click Finish to complete and close the wizard, or click Next to accept the defaults for all the remaining options in the
wizard.
Note
Having created a device project, you can always add more platforms, after the initial creation. However, adding a new p
latform to an existing project does not add the additional dependent runtime DLLs to the Additional Files config prop
erty. For example, if your application dynamically links to MFC, you will need to include the following DLLs in the Addit
ional Files property of the newly added platform: Mfc80u.dll, Atl80.dll, Msvcr80.dll. This example assumes a retail confi
guration.

8.
Add Code to the OnDraw() Method of the Multiplatform MFC Control
To add code to the OnDraw method of MFC ActiveX control
To add code to the OnDraw method of MFC ActiveX control
1. In Solution Explorer, expand the Source Files node, and select and open the MFCAXCtrl.cpp source file in the editor.
2. Replace the code for the OnDraw method with the following code, specifically the last three lines:

void CMFCAXCtrl::OnDraw(
CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
if (!pdc)
return;

CRect rect;
GetClientRect(&rect);
pdc->DrawTextW(_T("Hello World"),11, &rect,1);
}

3. On the Build menu, click Rebuild Solution.

Deploy the Multiplatform Solution


To deploy the solution
1. In order to run the deployed solution, on the target device, deploy and register the ActiveX control project first.
2. On the Target Device drop-down list on the Visual Studio toolbar, select your target, for example, Pocket PC 2003 SE
Emulator or Pocket PC 2003 Device.
3. On the Build menu, click Deploy.
Choosing a Target Device
To ensure that you are prompted to select a device when you deploy your solution, complete the following procedure.
To prompt for device choices at deployment time
1. On the Tools menu, click Options, click Device Tools, and then click General. If Device Tools is not visible, select
Show all settings at the bottom of the Options dialog box.
2. Select the Show device choices before deploying a device project check box.
For more information, visit the Mobile Developer Center.
See Also
Other Resources
Smart Device Walkthroughs
How to: Create a Multiplatform Device project (Visual C++)
Smart Device Development

Code Explanation: Hello World: A Multiplatform ActiveX


Control for Smart Devices
The C++ ActiveX MFC for Smart Devices Wizard frees you of most of the mundane tasks of generating Multiplatform MFC
ActiveX controls for Smart Devices projects such as resource files and multiplatform project configuration files. The wizard
generates the basic files.
This walkthrough familiarizes you with the code automatically generated for you when using the Multiplatform MFC ActiveX
controls for Smart Devices Wizard so you can easily extend and modify the application to suit your needs.
Code walkthrough
Anyone familiar with MFC ActiveX controls programming or ActiveX programming in general, can easily spot the main
functions generated for you by the wizard. The wizard code contains the following:
An include section:

#include "stdafx.h"

stdafx.h. For more information, see Precompiled Header Files.

#include "stdafx.h"
#include "<PROJECTNAME>.h"
#include "MFCAXCtrl.h"
#include "MFCAX1PropPage.h"

Debug configuration:

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

IMPLEMENT_DYNCREATE. For more information, see IMPLEMENT_DYNCREATE.


MFC message maps. For more information, see BEGIN_MESSAGE_MAP.

// Message map

BEGIN_MESSAGE_MAP(CMFCAXCtrl, COleControl)
ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()

MFC Dispatch maps. For more information, see BEGIN_DISPATCH_MAP.

// Dispatch map
BEGIN_DISPATCH_MAP(CMFCAXCtrl, COleControl)
#ifndef WIN32_PLATFORM_WFSP
DISP_FUNCTION_ID(CMFCAXCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VT
S_NONE)
#endif // !WIN32_PLATFORM_WFSP
END_DISPATCH_MAP()

MFC Event maps. For more information, see BEGIN_EVENT_MAP.


// Event map

BEGIN_EVENT_MAP(CMFCAXCtrl, COleControl)
END_EVENT_MAP()

STDMETHODIMP CMFCAXCtrl::XObjectSafety::SetInterfaceSafetyOptions(REFIID riid, DWORD dwOpti


onSetMask, DWORD dwEnabledOptions)
{
// Return S_OK if modified, and S_FALSE otherwise.
METHOD_PROLOGUE_EX_(CMFCAXCtrl, ObjectSafety)
// Check if we support the interface and
// return E_NOINTEFACE if we don't.
IUnknown* pUnk;
if (FAILED(this->QueryInterface(riid, (void**)&pUnk)))
return E_NOINTERFACE;

// If we are asked to set options we don't support then fail


if (dwOptionSetMask & ~pThis->m_dwSupportedSafety)
return E_FAIL;
// Set the safety options we have been asked to.
pThis->m_dwCurrentSafety = (pThis->m_dwCurrentSafety & ~dwOptionSetMask) | (dwOp
tionSetMask & dwEnabledOptions);
return S_OK;
}
#endif //defined(_WIN32_WCE) && (_WIN32_WCE < 0x500)

Information Available in the Readme File Created by the Wizard


The application wizard has created this jumpstart application for you. This application not only demonstrates the basics of
using the Microsoft Foundation Classes but is also a starting point for writing your ActiveX control application.
The files generated are listed here, along with a summary of what you will find in each file. These files collectively make up
your jumpstart point into your MFC ActiveX development.
The name MFCAX1 is used for an example. You may wish to use your own name for your project name.
MFCAXDLL.vcproj
The wizard has created this project for your MFCAX1 ActiveX Control DLL, which contains one control.
MFCAX1.vcproj
The main project file for VC++ projects generated using an Application Wizard. It contains information about the version of
Visual C++ that generated the file, and information about the platforms, configurations, and project features selected with the
Application Wizard.
MFCAX1.h
The main include file for the ActiveX Control DLL. It includes other project-specific includes.
MFCAX1.cpp
The main source file that contains code for DLL initialization, termination, and other bookkeeping.
MFCAX1ppc.rc
A listing of all of the Microsoft Windows resources that the project uses when compiling for the Pocket PC platform, or a
platform that supports the same user interface model. When the .rc file is persisted, the instances of #defines in the data
section are persisted as the hexadecimal version of the numeric value they are defined to rather than the friendly name of the
definitions.
MFCAX1sp.rc
A listing of all of the Microsoft Windows resources that the project uses when compiling for the Smartphone platform, or a
platform that supports the same user interface model. When the .rc file is persisted, the instances of #defines in the data
section are persisted as the hexadecimal version of the numeric value they are defined to rather than the friendly name of the
definitions.
MFCAX1.rc2
A file containing resources that are not edited by Microsoft Visual C++. You should place all resources not editable by the
resource editor in this file.
MFCAX1.def
A file containing information about the ActiveX control DLL that must be provided to run with Microsoft Windows.
MFCAX1.idl
A file containing the Object Description Language source code for the type library of your control.
C MFCAX1Ctrl control files:
MFCAX1Ctrl.h: A file containing the declaration of the C<PROJECTNAME>Ctrl C++ class.
MFCAX1Ctrl.cpp: A file containing the implementation of the C MFCAX1Ctrl C++ class.
MFCAX1PropPage.h: A file containing the declaration of the C MFCAX1PropPage C++ class.
MFCAX1PropPage.cpp: A file containing the implementation of the C MFCAX1PropPage C++ class.
CMFCAX1Ctrl.bmp: A file containing a bitmap that a container will use to represent the CMFCAX1Ctrl control when it
appears on a tool palette. This bitmap is included by the main resource (.rc) file
Other standard files:
stdafx.h, stdafx.cpp: Files used to build a precompiled header (PCH) file named MFCAX1.pch, and a precompiled types
(PCT) file named stdafx.obj.
resourceppc.h: The standard header file, which defines new resource IDs. The Visual C++ resource editor reads and
updates this file.
resourcesp.h: The standard header file, which defines new resource IDs. The Visual C++ resource editor reads and
updates this file. The Control Wizard uses TODO to indicate parts of the source code you should add to or customize.

See Also
Other Resources
Samples and Walkthroughs (Smart Device Projects)
Smart Device Development

Walkthrough: Creating an ATL Multiplatform ActiveX Control


for Smart Devices
You can use Visual C++ for devices to write ActiveX controls targeting multiple devices. The following walkthrough illustrates
how to build a multiplatform ATL ActiveX control.
In this walkthrough, you perform these main tasks:
Create a multiplatform smart device ATL project.
Add an ActiveX control to the project using the wizard. Notice that most of the basic structure and code is generated by
the wizard.
Modify the code in your stdafx.h and samplecontrol.h files to define your threading model and avoid compiler
warnings.
Deploy the multiplatform solution. Note that an Internet Explorer file is also generated to ease the testing and running of
the control.
This walkthrough was written using Visual C++ Development Settings.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

Create a Multiplatform ATL ActiveX Control


To create a multiplatform ATL ActiveX control
1. On the File menu, point to New, click Project, expand the Visual C++ node in the Project Types pane, and then click
Smart Device.
2. In the Templates pane, click ATL Smart Device Project.
3. In the Name box, type ATLAXControl, and then click OK.
The ATL Smart Device Project Wizard is launched.
4. Click Next on the ATL Smart Device Project Wizard welcome page.
The Platforms, ATL Smart Device Project Wizard is displayed so you can select the platform SDKs to be added to the
current project.
5. From the Installed SDKs list, select the platforms you want to add to the current project, such as Smartphone 2003 and
Pocket PC 2003. To add a platform select the platform in the left pane, such as Smartphone 2003, and click the button
with the right arrow > on it. To remove a platform select the platform in the right pane, such as Pocket PC 2003, and
click the button with the left arrow < on it.
6. Click Finish to complete and close the wizard.
Add an ActiveX Control to the Project
To add an ActiveX control to the project
1. In Solution Explorer, right-click ATLAXControl, point to Add, and then click Class.
2. In the Categories pane, click Smart Device.
3. In the Templates pane, click ATL Control, and then click Add.
The ATL Control Wizard dialog box appears.
4. In the Short Name text box, type samplecontrol.
5. Click Finish to complete and close the wizard.
Modify the Code in Header Files
To modify the code in stdafx.h
1. In Solution Explorer, double-click stdafx.h to open it in the editor.
2. Add the following define #define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA after the #pragma once, as shown here:

// Add this define after


#pragma once
#define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA

3. Add an ActiveX Control to the project as shown in the following procedure.


To add an ActiveX Control to the project
1. In Solution Explorer, double-click samplecontrol.h to open it in the editor.
2. Replace the string ATL 8.0 : samplecontrol with Hello World ActiveX Control in the code defining Isamplecontrol.

Note
ActiveX controls for a DCOM platform should be marked as apartment-model threaded when built. This is the ATL control wi
zard's default setting. You can safely ignore the warning generated during compile. Also ATL, GUI, and EXE projects, such as t
hose to which you have added atlwin.h, atlctl.h, or atlhost.h to an ATL EXE project, should have _CE_ALLOW_SINGLE_THREADED_
OBJECTS_IN_MTA defined in the stdafx.h before the inclusion of the ATL header files. This practice is the same as when you are
developing for the desktop. For more information see, Building and Debugging Visual C++ Device Projects.

Deploy the Multiplatform ATL Solution


To deploy the solution
1. On the Build menu, click Rebuild Solution to build the control.
2. On the Build menu, click Deploy Solution.
3. On the Target Device drop-down list on the Visual Studio toolbar, select your target, for example, Pocket PC 2003 SE
Emulator or Pocket PC 2003 Device.
4. On the Build menu, click Deploy.
Choosing a Target Device
To ensure that you are prompted to select a device when you deploy your solution, complete the following procedure.
To prompt for device choices at deployment
1. On the Tools menu, click Options, expand the Device Tools node, and then click General.
2. If Device Tools is not visible, select Show all settings at the bottom of the Options dialog box.
3. Select the Show device choices before deploying a device project check box, and then click OK.
To run the control, use File Explorer on the device, navigate to Program Files\ATLAXControl, and double-click the Internet
Explorer file ATLAXControl. One or more security messages will be displayed. Click Yes to run the page.
See Also
Other Resources
Smart Device Walkthroughs
How to: Create a Multiplatform Device project (Visual C++)
Smart Device Development

How to: Host an ActiveX Control in a Dialog Resource


When you use Visual Studio 2005 to design ActiveX controls for devices, you need to add a few extra steps. Because the
Resource Editor relies on the control being registered on the desktop computer to manipulate it at design time and because
you cannot register device controls on the desktop computer, the following steps provide an alternative design time
experience. The following procedures assume you already have your ActiveX control project and host project, and you are
hosting the ActiveX control in a dialog box.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings
or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see
Visual Studio Settings.

To add ActiveX controls by using the Dialog editor


1. In the Dialog editor, open the dialog box of the host project.
2. From the Toolbox, drag a custom control onto the dialog box.
3. Position and size the custom control on the dialog box to reflect how you want your ActiveX control to appear.
4. Right-click the custom control, and then click Properties.
5. In the Class property, paste the GUID of the ActiveX control. Remember to include the curly braces "{…}".
6. In Solution Explorer, right-click the Project Name.RC2 file, and then click View Code.
7. In the Add manually edited resources here section, add the following code. The custom control requires a dialog init
section to display correctly. The contents of the actual dialog init section are not used. Remember to replace <project
name> with the name of your project.

IDD_<project name>_DIALOG DLGINIT BEGIN IDC_CUSTOM1, 0x376, 22, 0 0x0000, 0x0000, 0x08
00, 0x0000, 0x094d, 0x0000, 0x043d, 0x0000, 0x0013, 0xcdcd, 0xcdcd, 0

8. Build and run your host project. Remember to deploy and register the ActiveX control on the target device.
To use an alternative method for hosting ActiveX Controls
1. Register the AtlAxWin80 window class by calling AtlAxWinInit at some point in the application. ATL applications do this
in the module initialization code. Win32 applications should call this function in the WinMain function. For MFC
applications, follow these steps:
a. Right-click the project node in Solution Explorer and click Add and then click Class.
b. Click Add ATL support to MFC (under the Smart Device heading).
c. Add the AtlAxWinInit call to the top of the InitInstance method of the host application class.
2. In a dialog resource (such as an ATL dialog or composite control, or MFC dialog):
a. Drag a custom control from the Toolbox.
b. Set the window class property to AtlAxWin80.
c. Set the caption to the GUID in curly braces, or the progid.
3. For MFC, add atl.lib as additional link input.
4. For MFC, add these lines to the Deployment | Additional Files option. The lines will already be there for dynamic link
libraries, but need to be added for MFC statically linked libraries.

msvcr80.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\$(ProjectName)|0
atl80.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\$(ProjectName)|0
msvcr80d.dll|$(BINDIR)\$(INSTRUCTIONSET)\|%CSIDL_PROGRAM_FILES%\$(ProjectName)|0

See Also
Other Resources
Programming for Devices Using Visual C++
Smart Device Walkthroughs
Smart Device Development

Smart Device Samples


You can find many device samples online by visiting the Mobile Developer Center.
The following Visual C# samples expose features of the .NET Compact Framework. The native samples use Visual C++ to
exemplify common device application scenarios.
In This Section
Creating a Custom Control (Visual C#)
Provides a two-line ListView custom control, including WYSIWYG design-time.
Based on .NET Compact Framework version 2.0.
CompactNav (Visual C#)
Provides a Smartphone file-system browser showing such techniques as calling unmanaged APIs.
Based on .NET Compact Framework version 1.0.
Native Samples (Devices)
Provides links to three sample native applications on the Mobile Developer Center site.
See Also
Other Resources
Programming for Devices Using the .NET Compact Framework
Samples and Walkthroughs (Smart Device Projects)
Smart Device Development

Creating a Custom Control (Visual C#)


Download sample
This Visual C# sample demonstrates making a two-line ListView custom control, including a WYSIWYG design-time experience.
The sample can be built for Pocket PC or Smartphone, using either version 1.0 or version 2.0 of the .NET Compact Framework.
Security Note
This sample code is provided to illustrate a concept and should not be used in applications or Web sites, as it may not illustra
te the safest coding practices. Microsoft assumes no liability for incidental or consequential damages should the sample code
be used for purposes other than as intended.

To run this sample


1. Click Download Sample.
The File Download message box appears.
2. Click Open, and on the left column of the zip folder window, click Extract all files.
The Extraction Wizard opens.
3. Click Next. You can change the directory that the files will be extracted to, and then click Next again.
Make sure that the Show extracted files check box is selected, and then click Finish.
4. Double-click the sample's .sln file.
The sample solution is displayed in Solution Explorer. You might get a security warning that says the solution location
is not trusted. Click OK to continue.
What this Sample Demonstrates
This sample illustrates how to implement a TwoLineListBox custom control using custom drawing with full design-time
support, including the following techniques:
Custom paint control appearance using classes from System.Drawing and System.Drawing.Imaging namespaces.
Event handling to redraw a custom control.
Using databinding to load data from a data source to populate the control.
Displaying an image in a custom control.
Adding design-time support for description, category, and other properties and events by using Class Diagram and
DesignTimeAttributes.
Adding design-time support to bind a control to an existing data source.
Applying DataSourceListEditor and DataMemberFieldEditor to properties (DataSource, Data) through
DesignTimeAttributes.
Applying Custom editor (Contact Editor) to property (Context) through DesignTimeAttributes.
Setting a default value for some properties, such as Line1DisplayMember, Line2DisplayMember.
Serializing the collection property to code from the custom editor, Contact Editor.
Deserializing the collection property to a custom editor, Contact Editor, from code.
Serializing an image from the custom editor, Contact Editor, into a .resx file.
Deserializing an image from a .resx file into the custom editor, Contact Editor.
Smart Device Development

CompactNav (Visual C#)


Download sample
The CompactNav sample is a Smartphone file-system browser written in managed code using version 1.0 of the .NET Compact
Framework.
Security Note
This sample code is provided to illustrate a concept and should not be used in applications or Web sites, as it may not illustra
te the safest coding practices. Microsoft assumes no liability for incidental or consequential damages should the sample code
be used for purposes other than as intended.

To run this sample


1. Click Download Sample.
The File Download message box appears.
2. Click Open, and on the left column of the zip folder window, click Extract all files.
The Extraction Wizard opens.
3. Click Next. You can change the directory that the files will be extracted to, and then click Next again.
Make sure that the Show extracted files check box is selected, and then click Finish.
4. Double-click the sample's .sln file.
The sample solution is displayed in Solution Explorer. You might get a security warning that says the solution location
is not trusted. Click OK to continue.

What the Sample Demonstrates


This sample illustrates how to implement a basic file-system navigator, including the following techniques:
Using Platform Invoke (pInvoke) to make calls to unmanaged APIs such as CreateProcess.
Exception handling.
How to load images from the file system.
Executing executable files by selecting them using CreateProcess.
Entering directories by selecting them and pressing the action key.
Accessing parent directories by using a menu item (UpDir) or by selecting the conventional ".." directory.
Implementing a Quit option for testing convenience only, as they are not typical or recommended for real Smartphone
applications.
Smart Device Development

Native Samples (Devices)


Visit the Mobile Developer Center for samples of device applications using Visual C++. These samples include the following:
Sample Description
PhoneMenus Demonstrates menus in a Smartphone application.

TextEditor Demonstrates the basics of using the Microsoft Foundation Classes, and provides a starting point for writing you
r own MFC application.

PoomViewer Demonstrates a device-independent user-interface in a program that queries and displays all of the fields in the
appointment, contact, and task databases.

For more information on these samples and the features they demonstrate, see the Readme.txt file included with each sample.
See Also
Other Resources
Smart Device Samples
Smart Device Development

Reference (Devices)
This section provides reference information for smart device projects. Related Sections provides links to language-specific
reference topics for device projects.
In This Section
.NET Compact Framework Reference for Device Projects
Provides information on the .NET Compact Framework.
ATL Reference for Devices
Provides directions for displaying ATL reference topics supported in device projects.
MFC Reference for Devices
Provides reference topics for MFC for Devices.
C Run-Time Library Reference for Devices
Provides reference topics for the C Run-Time Library for Devices.
Standard C++ Library Reference for Devices
Provides reference topics for the subset of the Standard C++ library available for device application development.
Compilers for Smart Devices
Describes ARM, Renesas, and MIPS family processors, and lists differences between desktop and device compilers.
User Interface Reference for Devices
Lists interface elements available exclusively for smart device application development.
Visual Basic Language Reference for Devices
Summarizes the differences in available Visual Basic programming elements in smart device projects.
Error Messages (Devices)
Provides information on resolving issues for particular errors.
See Also
Other Resources
Smart Device Development
Smart Device Development

.NET Compact Framework Reference for Device Projects


The .NET Compact Framework is a subset of the .NET Framework class library and also contains classes exclusively designed
for it. It inherits the full .NET Framework architecture of the common language runtime and managed code execution.
For more information, see .NET Compact Framework.
See Also
Other Resources
.NET Framework
Smart Device Development

ATL Reference for Devices


Due to device limitations, ATL for devices does not support everything that standard ATL supports. This section contains topics
that explain the differences.
In This Section
How to: Find Help for ATL Classes and Methods Supported for Devices
Describes how to use the filtering mechanism of Help to display up-to-date information on ATL references for devices, the
ATL classes, and methods supported on the devices.
Differences Between ATL for Devices and Standard ATL
Describes the differences between standard ATL and ATL for devices.
Related Sections
ATL Reference
If you are new to ATL, this topic introduces you to the Active Template Library for desktop computers.
See Also
Other Resources
Reference (Devices)
Smart Device Development

How to: Find Help for ATL Classes and Methods Supported for
Devices
Visual Studio Help provides a Smart Device Development filter for the table of contents and index. When you apply this
filter, the visible topics are reduced to include only documentation considered essential for smart device developers. Applying
this filter is an excellent way to display only the smart device subsets of reference topics, including the ATL libraries.
For viewing C++ topics and reference documentation, use Visual C++ Settings.
If you apply a language filter, such as Visual C#, smart device development topics are excluded from the viewable topics. For
this reason, it is better to use either the Smart Device Development filter or no filter at all. Start Visual Studio using a
language development setting, such as the Visual C# Development Setting. You can change the setting to Visual C++
Settings.
How to set the Smart Device Development filter
To set the Smart Device Development filter
1. On the Visual Studio Help menu, click Contents or Index.
2. In the Filtered by box, select Smart Device Development.
To change your development setting
1. On the Visual Studio Tools menu, click Import and Export Settings.
2. On the Welcome page of the wizard, click Reset all settings, and then click Next.
If you are not sure of your options, press F1 to open the Help topic for the wizard.
3. On the Save Current Settings page, select whether to save your current settings, and then click Next.
4. On the Choose a Default Collection of Settings page, select Visual C++ Settings, and then click Finish.
See Also
Tasks
How to: Find Help for MFC Classes and Methods Supported for Devices
Concepts
Help Filters for Visual Studio
Other Resources
Getting Started with Smart Device Projects
Smart Device Development

Differences Between ATL for Devices and Standard ATL


ATL has traditionally been used for developing COM-based applications. ATL 8.0 has features to help make COM programming
easier, such as classes for string manipulation and conversion, for managing arrays, and for lists and trees. Some differences
that ATL device developers will see in ATL 8.0 compared to eMbedded Visual C++ include Web services client support,
extended socket support (IPv6), and improved security. However, ATL 8.0 for Devices will not have all the desktop ATL
functionality. While Web services consumption is included in ATL device version, Security, Services, ATL Data and ATL Server
are not included in the device version.
This section contains topics that explain the differences and similarities between ATL for devices and standard ATL. For more
information about filtering Help topics for ATL references for devices, see
How to: Find Help for ATL Classes and Methods Supported for Devices.
In This Section
List of Supported ATL Classes
Provides a list of all of the ATL classes that are fully supported for device projects
Unique ATL for Devices Classes
Provides a list of ATL classes that are not supported for devices only.
See Also
Reference
List of Supported ATL Classes
Other Resources
ATL Reference for Devices
Unique ATL for Devices Classes
Smart Device Development

List of Supported ATL Classes


The following are the supported ATL classes for devices. Due to the limitations of devices, the functionality of a class available
on the desktop may not be available on the device. To see details of the classes and methods supported on devices, you can
use the filtering mechanism of the development environment's Help.
For information on filtering the development environment's Help in order to see ATL topics and references, including ATL
methods for devices, refer to How to: Find Help for ATL Classes and Methods Supported for Devices.
Supported ATL classes for the devices include:
allocator Class
AtlHtmlAttrs Class
CAdapt Class
CAtlBaseAuthObject Class
CAtlBaseModule Class
CAtlComModule Class
CAtlException Class
CAtlFile Class
CAtlFileMappingBase Class
CAtlHttpClientT Class
CAtlNavigateData Class
CAtlTemporaryFile Class
CAtlWinModule Class
CAutoPtr Class
CAutoPtrArray Class
CAutoPtrElementTraits Class
CAutoPtrList Class
CAutoVectorPtr Class
CAutoVectorPtrElementTraits Class
CBasicAuthObject Class
CCacheDataBase Class
CComAggObject Class
CComAllocator Class
CComAutoCriticalSection Class
CComBSTR Class
CComCachedTearOffObject Class
CComClassFactory Class
CComClassFactory2 Class
CComClassFactorySingleton Class
CComContainedObject Class
CComCriticalSection Class
CComCritSecLock Class
CComDynamicUnkArray Class
CComFakeCriticalSection Class
CComHeap Class
CComHeapPtr Class
CComModule Class
CComMultiThreadModel Class
CComMultiThreadModelNoCS Class
CComObject Class
CComObjectGlobal Class
CComObjectNoLock Class
CComObjectRootEx Class
CComObjectStack Class
CComPolyObject Class
CComPtr Class
CComPtrBase Class
CComQIPtr Class
CComSafeArrayBound Class
CComTearOffObject Class
CComUnkArray Class
CComVariant Class
CContainedWindowT Class
CCriticalSection Class
CCRTAllocator Class
CCRTHeap Class
CCryptDerivedKey Class
CCryptHash Class
CCryptHMACHash Class
CCryptImportKey Class
CCryptKey Class
CCryptKeyedHash Class
CCryptMACHash Class
CCryptMD2Hash Class
CCryptMD4Hash Class
CCryptMD5Hash Class
CCryptProv Class
CCryptRandomKey Class
CCryptSHAHash Class
CCryptSSL3SHAMD5Hash Class
CCryptUserExKey Class
CCryptUserSigKey Class
CDefaultCharTraits Class
CDefaultCompareTraits Class
CDefaultElementTraits Class
CDefaultHashTraits Class
CDynamicChain Class
CElementTraits Class
CElementTraitsBase Class
CEvent Class
CExpireCuller Class
CFileTime Class
CFileTimeSpan Class
CFirePropNotifyEvent Class
CFixedLifetimeCuller Class
CGlobalHeap Class
CHandle Class
CHtmlGen Class
CHtmlGenBase Class
CHttpResponse Class
CImage Class
CLifetimeCuller Class
CLocalHeap Class
CLOUFlusher Class
CLRUFlusher Class
CMutex Class
CNoDllCachePeer Class
CNoExpireCuller Class
CNoFileCachePeer Class
CNoFlusher Class
CNonStatelessWorker Class
CNoStatClass Class
CNoWorkerThread Class
CNTLMAuthObject Class
COldFlusher Class
COleDateTime Class
COleDateTimeSpan Class
COrCullers Class
COrFlushers Class
CPoint Class
CPrimitiveElementTraits Class
CRect Class
CRegKey Class
CSemaphore Class
CSimpleArrayEqualHelper Class
CSimpleArrayEqualHelperFalse Class
CSimpleDialog Class
CSimpleMap Class
CSimpleMapEqualHelper Class
CSimpleMapEqualHelperFalse Class
CSocketAddr Class
CStrBufT Class
CStreamFormatter Class
CStreamOnWriteStream Class
CStringRefElementTraits Class
CTime Class
CTimeSpan Class
CUrl Class
CWin32Heap Class
CWindow Class
CWriteStreamHelper Class
Win32ThreadTraits Class
See Also
Other Resources
Differences Between ATL for Devices and Standard ATL
ATL Reference for Devices
Smart Device Development

Unique ATL for Devices Classes


ATL for devices has one unique class. This section describes this class.
In This Section
CAtlCEValidateThreadIDDefault Methods
A class that provides thread-related macros and methods unique to device projects.
See Also
Tasks
How to: Find Help for ATL Classes and Methods Supported for Devices
Other Resources
ATL Reference for Devices
Smart Device Development

CAtlCEValidateThreadIDDefault Class
Introduces the CAtlCEValidateThreadIDDefault class, which provides thread-related macros and methods unique to device
projects.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in atlcore.h.
See Also
Concepts
CAtlCEValidateThreadIDDefault Methods
Other Resources
Unique ATL for Devices Classes
Smart Device Development

CAtlCEValidateThreadIDDefault Methods
The following table lists the CAtlCEValidateThreadIDDefault methods:

CAtlCEValidateThreadIDDefault::CAtlCEValidateThreadIDDefault Creates an instance of a CAtlCEValidateThreadIDDefault o


bject and sets the m_ThreadId private data member.

CAtlCEValidateThreadIDDefault::Validate Indicates whether the thread identifier, which is used as the ha


ndle of the calling thread, is the same as the original calling th
read or the current thread identifier is different.

The following table lists the CAtlCEValidateThreadIDDefault macros:

CE_VALIDATE_THREADID_ASSERT Macro In debug builds, CE_VALIDATE_THREADID_ASSERT generates a debug report when t


he CAtlCEValidateThreadIDDefault::Validate method returns false

CE_VALIDATE_THREADID_RETURN Macro Returns the parameter of the macro if the thread identifier is validated.

CE_VALIDATE_THREADID_THROW Macro Throws an exception if the thread identifier is validated.

See Also
Concepts
CAtlCEValidateThreadIDDefault Class
Other Resources
Unique ATL for Devices Classes
Smart Device Development

CAtlCEValidateThreadIDDefault::CAtlCEValidateThreadIDDefault
Creates an instance of a CAtlCEValidateThreadIDDefault object and sets the m_ThreadId private data member to the current
thread identifier, which is used as the handle of the calling thread.

CAtlCEValidateThreadIDDefault();

Requirements
Windows CE versions 5.0 and later.
Header file: Declared in atlcore.h.
See Also
Concepts
CAtlCEValidateThreadIDDefault Methods
Other Resources
Unique ATL for Devices Classes
Smart Device Development

CAtlCEValidateThreadIDDefault::Validate
Indicates whether the thread identifier, which is used as the handle of the calling thread, is the same as the original calling
thread or the current thread identifier is different.

bool Validate ();

Return Value
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in atlcore.h.
See Also
Concepts
CAtlCEValidateThreadIDDefault Methods
Other Resources
Unique ATL for Devices Classes
Smart Device Development

CE_VALIDATE_THREADID_ASSERT Macro
In debug builds, CE_VALIDATE_THREADID_ASSERT generates a debug report when the
CAtlCEValidateThreadIDDefault::Validate method returns false.

CE_VALIDATE_THREADID_ASSERT();

Requirements
Windows CE versions 5.0 and later.
Header file: Declared in atlcore.h.
See Also
Concepts
CAtlCEValidateThreadIDDefault Methods
Other Resources
Unique ATL for Devices Classes
Smart Device Development

CE_VALIDATE_THREADID_RETURN Macro
Returns the parameter of the macro if the thread identifier is validated.

CE_VALIDATE_THREADID_RETURN(r);

Parameters
The following table describes the parameter for the CE_VALIDATE_THREADID_RETURN macro of the
CAtlCEValidateThreadIDDefault class.
Parameter Description
r The parameter to return if the thread is validated.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in atlcore.h.
See Also
Reference
CAtlCEValidateThreadIDDefault::Validate
Concepts
CAtlCEValidateThreadIDDefault Methods
Other Resources
Unique ATL for Devices Classes
Smart Device Development

CE_VALIDATE_THREADID_THROW Macro
Throws an exception if the thread identifier is validated.

CE_VALIDATE_THREADID_THROW(e);

Parameters
The following table describes the parameter for the CE_VALIDATE_THREADID_THROW macro of the
CAtlCEValidateThreadIDDefault class.
Parameter Description
e Exception to throw.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in atlcore.h.
See Also
Reference
CAtlCEValidateThreadIDDefault::Validate
Concepts
CAtlCEValidateThreadIDDefault Methods
Other Resources
Unique ATL for Devices Classes
Smart Device Development

MFC Reference for Devices


In Visual Studio 2005, Smart Device projects use version 8.0 of MFC for devices. MFC 8.0 for devices is different than both the
Standard Desktop MFC and the embedded Visual C++ MFC 3.0. This section explains where to find help.
The MFC for devices files are located under the folder %Program Files%\Microsoft Visual Studio 8\VC\ce
In This Section
MFC Classes
The location for the majority of MFC for devices documentation.
Notice that MFC for devices shares documentation with Standard Desktop MFC.
Behavior deviations from Standard Desktop MFC are noted within the topic in the section titled "Smart Device Developer
Notes".
Unique MFC for Devices Classes
The location where the MFC classes unique to smart devices are documented. There are only a few unique classes.
How to: Find Help for MFC Classes and Methods Supported for Devices
Describes how to use the filtering mechanism to display up-to-date information on MFC/ATL references for devices.
List of Desktop MFC Classes Supported for Devices
Lists Standard Desktop MFC classes that are supported on devices.
List of Unsupported Desktop MFC Classes for Devices
Lists Standard Desktop MFC classes not supported on devices.
List of eVC Classes Not Supported from MFC 3.0 to 8.0
Describes the differences between eVC MFC 3.0 and Visual Studio 2005 MFC 8.0 for devices.
Differences Between MFC C++ for Devices and Standard MFC
Charts illustrating the classes supported on the desktop, which are also supported on the MFC C++ Devices.
See Also
Concepts
eMbedded Visual C++ to Visual Studio 2005 Upgrade Wizard
Standard C++ Library Reference for Devices
Other Resources
Reference (Devices)
Smart Device Development

MFC for Windows CE Wizards C++


Using Visual C++ wizards, you can write MFC applications targeting multiple Windows CE devices. Visual C++ wizards include
MFC Smart Device Application, MFC Smart Device ActiveX Control, and MFC Smart Device DLL.
MFC for Windows CE Wizards C++
MFC for Windows CE Wizards C++ includes:
MFC Smart Device Application Wizard
The MFC Smart Device Application Wizard generates an application with the built-in functionality and basic features of a
Windows CE executable (.exe) application. For more information, see:
Advanced Features, MFC Smart Device Application Wizard
Application Type, MFC Smart Device Application Wizard
Platforms, MFC Smart Device Application Wizard
User Interface Features, MFC Smart Device Application Wizard
Document Template Strings, MFC Smart Device Application Wizard
Generated Classes, MFC Smart Device Application Wizard
MFC Smart Device ActiveX Control Wizard
The MFC wizard-generated project includes C++ source (.cpp) files, resource (.rc) files, and a project (.vcproj) file. For
more information, see:
Control Settings, MFC Smart Device ActiveX Control Wizard
Control Names, MFC Smart Device ActiveX Control Wizard
Platforms, MFC Smart Device ActiveX Control Wizard
Application Settings, MFC Smart Device ActiveX Control Wizard
MFC Smart Device DLL Wizard
You can use the MFC Smart Device Control DLL project to create a Smart Device DLL. For more information, see:
Application Settings, MFC Smart Device DLL Wizard
Platforms, MFC Smart Device DLL Wizard.
See Also
Tasks
Walkthrough: Creating a Multiplatform MFC Application for Smart Devices
Smart Device Development

How to: Find Help for MFC Classes and Methods Supported for
Devices
Visual Studio Help provides a Smart Device Development filter for the table of contents and index. When you apply this
filter, the visible topics are reduced to include only documentation considered essential for smart device developers. Applying
this filter is an excellent way to display only the smart device subsets of reference topics, including the MFC libraries.
For viewing C++ topics and reference documentation, use Visual C++ Settings.
If you apply a language filter, such as Visual C#, smart device development topics are excluded from the viewable topics. For
this reason, it is better to use either the Smart Device Development filter or no filter at all.
Start Visual Studio with a language development setting, such as Visual C# Development Settings. You can change this
default setting to Visual C++ Settings.
How to Set the Smart Device Development Filter
To set the Smart Device Development filter
1. On the Visual Studio Help menu, click Contents or Index.
2. In the Filtered by box, select Smart Device Development.
To change your development setting
1. On the Visual Studio Tools menu, click Import and Export Settings.
2. On the Welcome page of the wizard, click Reset all settings, and then click Next.
If you are not sure of your options, press F1 to open the Help topic for the wizard.
3. On the Save Current Settings page, select whether to save your current settings, and then click Next.
4. On the Choose a Default Collection of Settings page, select Visual C++ Settings, and then click Finish.
See Also
Concepts
List of Unsupported Desktop MFC Classes for Devices
Help Filters for Visual Studio
Other Resources
Getting Started with Smart Device Projects
Smart Device Development

List of eVC Classes Not Supported from MFC 3.0 to 8.0


This topic has been updated for Visual Studio 2005 SP1.
Embedded Visual C++
CDaoFieldExchange Class
CDBVariant Class
CFieldExchange Class
CFontDialog Class
CLongBinary Class
COleCmdUI Class
COleCurrency Class
COleDataObject Class
COlePropertyPage Class
CPrintDialog Class
CPrintInfo Members
CSocketFile Class
In Visual Studio 2005 SP1, fifteen eVC MFC classes were added to device MFC libraries to improve embedded Visual C++
project migration. The following classes are not supported in Visual Studio 2005 MFC for devices, but are supported in Visual
Studio 2005 SP1 for devices.
CBitmap Class
CDialogBar Class
CEditView Class
CFindReplaceDialog Class
CHttpConnection Class
CHttpFile Class
CInternetConnection Class
CInternetException Class
CInternetFile Class
CInternetSession Class
COleSafeArray Class
CReBar Class
CReBarCtrl Class
CRecentFileList Class
CSplitterWnd Class
The following classes are typedef that use template classes to provide equivalent functionality:
CByteArray Class
CDWordArray Class
CMapPtrToPtr Class
CMapPtrToWord Class
CMapStringToOb Class
CMapStringToPtr Class
CMapStringToString Class
CMapWordToOb Class
CMapWordToPtr Class
CObArray Class
CObList Class
COleSafeArray Class
CPtrArray Class
CPtrList Class
CStringArray Class
CStringList Class
CUIntArray Class
CWordArray Class
Behavioral Differences of APIs from MFC 3.0 to MFC 8.0
The CDocument::SaveModified dialog class and associated resources have been dropped from MFC 8.0 for all platforms.
Therefore, on Pocket PC 2003 and Smartphone 2003 platforms DoSave and SaveModified methods have no default
file name when used, nor do they have a default prompt for the file name such as an auto-generated file name. However,
an option is provided to override this behavior and prompt for file name on the Pocket PC 2003 platform. On the
Smartphone platform, you can call CDocManager::DoPromptFileName, if you wish to prompt for file name. DoSave
and SaveModified methods' default-file name behavior is supported on Windows CE platform and the functionality is
the same as that on the desktop.
MFC 8.0 for devices has no docking support. For example CCommandBar::m_pDockBar and
CCommandBar::m_pDockContext members are not supported. For more information, see CCommandBar Class. For
more information about docking support, see Docking and Floating Toolbars.
In MFC 8.0 for devices, CDC::FrameRect is no longer a member of CDC Class.
In MFC 8.0 for devices, CCeDocList is renamed to CDocList Class.
In MFC 8.0 for devices, CCeSocket functionality is encapsulated in CAsyncSocket Class.
In MFC 8.0 for devices, CFont::CreateFont is not supported, you can use CFont::CreatePointFont instead.
In MFC 8.0 for devices, CCommandBar::m_pDockBar and CCommandBar::m_pDockContext members are no longer
supported.
In MFC 8.0 for devices, LPINLINEIMAGEINFO structure is replaced with INLINEIMAGEINFO.
The Visual Studio 2005 wizard-generated resources follow the Windows Mobile 5.0 User Interface (UI) guidelines. This
means all applications' MenuBar classes will always have the customary New button on the left side and a Menu on the
right side. Therefore, MFC 8.0 for devices does not support the m_bShowSharedNewButton variable. For example, if
your application code is using wndCommandBar.m_bShowSharedNewButton = TRUE;, you can comment the code line out
and get your application to port to MFC 8.0 for devices.
If your application code is using ON_NOTIFY(DLN_CE_CREATE, AFXCE_ID_DOCLIST, or OnCreateDocList,you will get the
following compile errors:
MainFrm.cpp(42) : error C2065: 'DLN_CE_CREATE' : undeclared identifier
MainFrm.cpp(42) : error C2065: 'AFXCE_ID_DOCLIST' : undeclared identifier
In MFC 8.0, you can safely use DLN_DOCLIST_CREATE, DLN_DOCLIST_DESTROY, and AFX_ID_DOCLIST.
When using MFC 8.0, you cannot link to the standard CRT libraries.
When porting to MFC 8.0, include # define _WIN32_WCE_PSPC. This flag is not defined by default in MFC 8.0.

For more information, see List of Unsupported Desktop MFC Classes for Devices.

See Also
Concepts
Differences Between MFC C++ for Devices and Standard MFC
Other Resources
Unique MFC for Devices Classes
Smart Device Development

Differences Between MFC C++ for Devices and Standard MFC


For device constraint reasons, such as memory, MFC for devices does not support all classes and abilities that the standard
desktop MFC supports. The following table describes the classes that are and are not supported on the latest Visual Studio
release for devices (MFC version 8.0).
You can also use the filtering mechanism of the Help functionality to get a list of MFC classes supported on the desktop which
are also supported on devices.
For more information about filtering Help topics for MFC references for devices, including supported classes and
methods, see How to: Find Help for MFC Classes and Methods Supported for Devices.
For more information about MFC classes supported for devices, see List of Desktop MFC Classes Supported for Devices.
For more information about MFC classes not supported for devices, see
List of Unsupported Desktop MFC Classes for Devices.
The following chart illustrates the classes supported on the Desktop that are also supported on the MFC C++ Devices.
Charts of Differences Between MFC 8.0 for Devices and Standard Desktop MFC 7.0
Legend
Symbol Description
Standard Desktop MFC 7.0 classes supported in MFC for Devices 8.0

Standard Desktop MFC 7.0 classes not supported in MFC for Devices 8.0

Classification of classes
See Also
Other Resources
MFC Reference for Devices
Unique MFC for Devices Classes
Smart Device Development

List of Desktop MFC Classes Supported for Devices


This topic has been updated for Visual Studio 2005 SP1.
The following are the supported MFC classes on the latest Visual Studio release for devices. Due to limitations of devices, some
functionality of a class available on the desktop is not available on the device.
The following list has been updated for Visual Studio 2005 SP1.
Supported MFC classes for the devices include:
CArchive Class
CArchiveException Class
CArray Class
CAsyncSocket Class
CBitmap Class
CBitmap Class (supported in Visual Studio 2005 SP1)
CBrush Class
CButton Class
CClientDC Class
CCmdTarget Class
CCmdUI Class
CColorDialog Class
CComboBox Class
CCommandBar Class
CCommandLineInfo Class
CCommonDialog Class
CConnectionPoint Class
CControlBar Class
CCriticalSection Class
CCtrlView Class
CDataExchange Class
CDateTimeCtrl Class
CDC Class
CDialog Class
CDialogBar Class (supported in Visual Studio 2005 SP1)
CDocList Class
CDocListDocTemplate Class
CDocTemplate Class
CDocument Class
CEdit Class
CEditView Class (supported in Visual Studio 2005 SP1)
CEvent Class
CException Class
CFile Class
CFileDialog Class
CFileException Class
CFindReplaceDialog Class (supported in Visual Studio 2005 SP1)
CFixedStringT Class
CFont Class
CFontHolder Class
CFormView Class
CFrameWnd Class
CGdiObject Class
CHeaderCtrl Class
CHttpConnection Class (supported in Visual Studio 2005 SP1)
CHttpFile Class (supported in Visual Studio 2005 SP1)
CImageList Class
CInternetConnection Class (supported in Visual Studio 2005 SP1)
CInternetException Class (supported in Visual Studio 2005 SP1)
CInternetFile Class (supported in Visual Studio 2005 SP1)
CInternetSession Class (supported in Visual Studio 2005 SP1)
CInvalidArgException Class
CList Class
CListBox Class
CListCtrl Class
CListView Class
CMap Class
CMemFile Class
CMemoryException Class
CMenu Class
CMonthCalCtrl Class
CMultiLock Class
CMutex Class
CNotSupportedException Class
CObject Class
COccManager Class
COleControl Class
COleControlContainer Class
COleControlModule Class
COleControlSite Class
COleDateTime Class
COleDispatchDriver Class
COleDispatchException Class
COleException Class
COleObjectFactory Class
COlePropertyPage Class
COleSafeArray Class (supported in Visual Studio 2005 SP1)
COleStreamFile Class
COleVariant Class
CPaintDC Class
CPalette Class
CPen Class
CProgressCtrl Class
CPropertyPage Class
CPropertySheet Class
CPropExchange Class
CReBar Class (supported in Visual Studio 2005 SP1)
CReBarCtrl Class (supported in Visual Studio 2005 SP1)
CRecentFileList Class (supported in Visual Studio 2005 SP1)
CRectTracker Class
CResourceException Class
CRgn Class
CScrollBar Class
CScrollView Class
CSemaphore Class
CSimpleException Class
CSimpleStringT Class
CSingleDocTemplate Class
CSingleLock Class
CSliderCtrl Class
CSocket Class
CSocketFile Class
CSpinButtonCtrl Class
CSplitterWnd Class (supported in Visual Studio 2005 SP1)
CStatic Class
CStatusBar Class
CStatusBarCtrl Class
CStdioFile Class
CStringT Class
CSyncObject Class
CTabCtrl Class
CTime Class
CTimeSpan Class
CToolBar Class
CToolBarCtrl Class
CTreeCtrl Class
CTreeView Class
CTypedPtrList Class
CUserException Class
CView Class
CWinApp Class
CWindowDC Class
CWinThread Class
CWnd Class
There are some behavioral differences between these classes. For more information, see
List of eVC Classes Not Supported from MFC 3.0 to 8.0.
To see the details of supported MFC topics and MFC references, you can use the filtering mechanism of the development
environment's Help. For more information about this filtering mechanism, see
How to: Find Help for MFC Classes and Methods Supported for Devices.
See Also
Concepts
List of eVC Classes Not Supported from MFC 3.0 to 8.0
Other Resources
MFC Reference for Devices
Unique MFC for Devices Classes
Smart Device Development

List of Unsupported Desktop MFC Classes for Devices


This topic has been updated for Visual Studio 2005 SP1.
Due to limitations of devices, the functionality of MFC classes available on the desktop may not be available on the device. For
a list of supported MFC classes for devices, see List of Desktop MFC Classes Supported for Devices. Standard Desktop MFC
classes not supported in MFC for devices include:
CAnimateCtrl Class
CAsyncMonikerFile Class
CByteArray Class
CCachedDataPathProperty Class
CCheckListBox Class
CComboBoxEx Class
CDaoDatabase Class
CDaoException Class
CDaoFieldExchange Class
CDaoQueryDef Class
CDaoRecordset Class
CDaoRecordView Class
CDaoTableDef Class
CDaoWorkspace Class
CDatabase Class
CDataPathProperty Class
CDBException Class
CDBVariant Class
CDHtmlDialog Class
CDocItem Class
CDockState Class
CDocObjectServer Class
CDocObjectServerItem Class
CDragListBox Class
CDumpContext Class
CDWordArray Class
CFieldExchange Class
CFileFind Class
CFileTime Class
CFileTimeSpan Class
CFontDialog Class
CFtpConnection Class
CFtpFileFind Class
CGopherConnection Class
CGopherFile Class
CGopherFileFind Class
CGopherLocator Class
CHotKeyCtrl Class
CHtmlEditCtrl Class
CHtmlEditCtrlBase Class
CHtmlEditDoc Class
CHtmlEditView Class
CHtmlStream Class
CHtmlView Class
CHttpArg Structure
CHttpArgList Class
CHttpFilter Class
CHttpFilterContext Class
CHttpServer Class
CHttpServerContext Class
CImage Class
CIPAddressCtrl Class
CLinkCtrl Class
CLongBinary Class
CMapPtrToPtr Class
CMapPtrToWord Class
CMapStringToOb Class
CMapStringToPtr Class
CMapStringToString Class
CMapWordToOb Class
CMapWordToPtr Class
CMDIChildWnd Class
CMDIFrameWnd Class
CMetaFileDC Class
CMiniFrameWnd Class
CMonikerFile Class
CMultiDocTemplate Class
CMultiPageDHtmlDialog Class
CObArray Class
CObList Class
COleBusyDialog Class
COleChangeIconDialog Class
COleChangeSourceDialog Class
COleClientItem Class
COleCmdUI Class
COleConvertDialog Class
COleCurrency Class
COleDataObject Class
COleDataSource Class
COleDateTimeSpan Class
COleDBRecordView Class
COleDialog Class
COleDocObjectItem Class
COleDocument Class
COleDropSource Class
COleDropTarget Class
COleInsertDialog Class
COleIPFrameWnd Class
COleLinkingDoc Class
COleLinksDialog Class
COleMessageFilter Class
COlePasteSpecialDialog Class
COlePropertiesDialog Class
COleResizeBar Class
COleServerDoc Class
COleServerItem Class
COleTemplateServer Class
COleUpdateDialog Class
CPageSetupDialog Class
CPictureHolder Class
CPrintDialog Class
CPrintDialogEx Class
CPrintInfo Members
CPoint Class
CPtrArray Class
CPtrList Class
CRecordset Class
CRecordView Class
CRect Class
CRichEditCntrItem Class
CRichEditCtrl Class
CRichEditDoc Class
CRichEditView Class
CSharedFile Class
CSize Class
CStrBufT Class
CStringArray Class
CStringData Class
CStringList Class
CToolTipCtrl Class
CTypedPtrArray Class
CTypedPtrMap Class
CUIntArray Class
CWaitCursor Class
CWinFormsControl Class
CWinFormsDialog Class
CWinFormsView Class
CWordArray Class
In Visual Studio 2005 SP1, fifteen desktop MFC classes were added to device MFC libraries. The following classes are not
supported in Visual Studio 2005 MFC for devices, but are supported in Visual Studio 2005 SP1 for devices.
CBitmap Class
CDialogBar Class
CEditView Class
CFindReplaceDialog Class
CHttpConnection Class
CHttpFile Class
CInternetConnection Class
CInternetException Class
CInternetFile Class
CInternetSession Class
COleSafeArray Class
CReBar Class
CReBarCtrl Class
CRecentFileList Class
CSplitterWnd Class
See Also
Reference
List of Desktop MFC Classes Supported for Devices
Concepts
List of eVC Classes Not Supported from MFC 3.0 to 8.0
Other Resources
MFC Reference for Devices
Unique MFC for Devices Classes
MFC Classes
Smart Device Development

Unique MFC for Devices Classes


MFC for devices has a few unique classes. This section describes these classes.
In This Section
CCommandBar Class
Combines the functionality of menu bars and toolbars, and is designed specifically for devices with small displays.
CDocList Class
Wraps the operating system implementation of the DocList window type, with additional features for integration with an
MFC Doc/View architecture.
CDocListDocTemplate Class
A refinement of the SDI application type, as facilitated by CSingleDocTemplate.
AfxEnableDRA
Function that enables device resolution awareness.
Related Sections
MFC Reference for Devices
How to: Find Help for MFC Classes and Methods Supported for Devices
Smart Device Development

CCommandBar Class
This class enables you to create and modify command bars. A command bar is a toolbar that can include a menu bar as well as
a Close button, a Help button, and the OK button. A command bar can contain menus, combo boxes, buttons, and separators.
A separator is a blank space used to divide other elements into groups or to reserve space in a command bar. After you create
a CCommandBar object, use the InsertMenuBar, InsertComboBox, and InsertSeparator methods to insert menu bars, combo
boxes, and separators, respectively. When you finish adding all other elements to the command bar, use the AddAdornments
method to add the Cancel button, and optionally, the Help and OK buttons. Use the DrawMenuBar method to redraw the
command bar each time you modify a menu on the command bar.
In Windows CE 5.0, CDialog::m_pWndEmptyCB member is no longer supported and you control the creation and insertion
process. Previously, this member variable was used to point to the empty CommandBar or MenuBar on Pocket PC.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CCommandBar Methods
The following table lists CCommandBar methods:

CCommandBar::AddAdornments Adds a Close button, and optionally, Help and OK buttons to the command bar.

CCommandBar::AddBitmap This method adds one or more images to the list of button images available for use in the co
mmand bar.

CCommandBar::AddButtons Adds one or more buttons to a toolbar control.

CCommandBar::CCommandBar Creates and initializes a CCommandBar object.

CCommandBar::Create Instantiates a new command bar.

CCommandBar::DrawMenuBar Repositions and redraws the command bar after a command bar menu is modified.

CCommandBar::GetMenu Retrieves the handle to a menu on the command bar.

CCommandBar::Height Retrieves the height of the command bar in pixels.

CCommandBar::InsertButton This method adds one or more buttons to a toolbar control.

CCommandBar::InsertComboBox Adds a combo box to the command bar.

CCommandBar::InsertMenuBar Adds a menu bar to the command bar.

CCommandBar::InsertSeparator Adds a separator to the command bar.

CCommandBar::Show Shows or hides the command bar.

CCeDocList class has become CDocList Class in MFC 8.0. The following is code from an MFC 3.0 application:

CCommandBar* pDocListCB = pDocList->GetCommandBar();

This code generates the following error:


MainFrm.cpp(115) : error C2039: 'GetCommandBar' : is not a member of 'CDocList'
Instead of using this code, you can create a CDocListCommandBar object in MFC 8.0.
See Also
Reference
CCommandBar Class
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CCommandBar::AddAdornments
Adds a Close button, and optionally, Help and OK buttons, to the command bar.

BOOL AddAdornments(
Dword dwFlags = 0 );

Parameters
The following table describes the parameters for the AddAdornments method of the CCommandBar Class.
Param Description
eter
dwFlag Specifies optional buttons to add to the command bar. The value is zero if only the Close button is needed, or a combi
s nation of the following values to create additional buttons:
Value Description
CMDBAR_ Adds a Help button to the command bar. When clicked, this button sends a WM_HELP message.
HELP

CMDBAR_ Adds an OK button to the command bar. When selected, this button sends a WM_COMMAND message w
OK ith IDOK as the message identifier.

Return Values
true if successful; otherwise, false.
Remarks
This method creates a minimum of two buttons: a separator that aligns the selected adornments to the right side of the
command bar, and the selected adornments.
When a user clicks the Close, OK, or Help button, the message associated with that button is placed in the message queue of
the application. Every command bar must have a Close button. The OK button and the Help button are optional.
Call this method after all other elements such as menus, buttons, and combo boxes are added to the command bar.
Existing applications should be redesigned to remove dependency on AddAdornments.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CCommandBar::AddBitmap
Adds one or more images to the list of button images available in the command bar.

int AddBitmap (
int nBitMapID,
int nNumImages );

Parameters
The following table describes the parameters for the AddBitmap method of the CCommandBar Class.
nBitMapID
Specifies the resource identifier of the bitmap that contains the button image or images to add.
nNumImages
Specifies the number of button images in the bitmap.
Return Values
Zero-based index of the first new image, if successful, and –1 otherwise.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CCommandBar::AddButtons
Adds one or more buttons to a toolbar control.

BOOL AddButtons(
UINT uNumButtons,
LPTBBUTTON lpButtons );

Parameters
The following table describes the parameters for the AddButtons method of the CCommandBar Class.
uNumButtons
Specifies the number of buttons to add.
lpButtons
Specifies the address of an array of TBBUTTON structures that contains information about the buttons to add. There must be
the same number of elements in the array as buttons specified by nNumButtons.
Return Values
true if successful; otherwise, false.
Remarks
The lpButtons pointer points to an array of TBBUTTON structures.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CCommandBar::CCommandBar
Creates an instance of a CCommandBar object.

CCommandBar ( );

Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CCommandBar::Create
Instantiates a new command bar.

BOOL CommandBar::Create(
CWnd* pWndParent,
DWORD dwStyle,
UINT nBarID = AFX_IDW_TOOLBAR
);

Parameters
The following table describes the parameters for the Create method of the CCommandBar Class.
pWndParent
A pointer to the parent of the command bar object.
dwStyle
Specifies the command-bar style. See remarks.
nBarID
Optional parameter. Specifies the child-window ID of the toolbar = AFX_IDW_TOOLBAR.
Return Values
true if successful; otherwise, false.
Remarks
The Create function creates an empty command bar. On Pocket PCs and Smartphones, the command bar is created at the
bottom of the window. In Windows CE 5.0, CDialog::m_pWndEmptyCB is no longer supported, and you control the create
and insert process. Previously, this member variable was used to point to the empty CommandBar or MenuBar on Pocket PC.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CCommandBar::DrawMenuBar
Repositions and redraws the command bar after a menu in the command bar is modified.

BOOL DrawMenuBar(
WORD wButton )
const;

Parameters
The following table describes the parameter for the DrawMenuBar method of the CCommandBar Class.
wButton
Specifies the zero-based index of the menu bar within the command bar.
Return Value
true if successful; otherwise, false.
Remarks
Always call this method after modifying a menu in a command bar.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CCommandBar::GetMenu
Retrieves the handle to a menu on the command bar.

HMENU CommandBar_GetMenu();

Return Values
The handle to the menu indicates success. NULL indicates failure.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CCommandBar::Height
Retrieves the height of the command bar in pixels.

int Height();

Return Value
Returns the height, in pixels, of the command bar.
Remarks
The command bar occupies part of the client area of an application's main window; you can call this function as a means to
determine the actual size of the client area.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CCommandBar::InsertButton
Adds one or more buttons to a toolbar control.

BOOL InsertButton(
int nButton,
LPTBBUTTON lpButton );

Parameters
The following table describes the parameters for the InsertButton method of the CCommandBar Class.
nButton
Specifies the zero-based index of a button. This method inserts the new button to the left of this button.
lpButton
Specifies the address of a TBUTTON structure containing information about the button to insert.
Return Values
true if successful; otherwise, false.
Remarks
The lpButton pointer points to a TBUTTON structure.
Requirements
Windows CE version 5.0 or higher.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CCommandBar::InsertComboBox
Inserts a combo box into the command bar.

CComboBox* InsertComboBox(
int nWidth,
DWORD dwStyle,
WORD wComboBoxID,
WORD wButton );

Parameters
The following table describes the parameters for the InsertComboBox method of the CCommandBar Class.
nWidth
Specifies the width, in pixels, of the combo box.
dwStyle
Specifies which window styles apply to the combo box. The WS_VISIBLE and WS_CHILD styles are applied automatically. The
default styles are CBS_DROPDOWNLIST and WS_SCROLL.
wComboBoxID
Specifies the identifier of the combo box.
wButton
Specifies the zero-based index of a button in the command bar.
Return Values
A pointer to the menu identified by wComboBoxID if successful, and null otherwise.
Remarks
This method inserts the combo box to the left of the button identified by wButton.
Requirements
Windows CE version 5.0 or higher.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CCommandBar::InsertMenuBar
Inserts a menu bar into the command bar.

BOOL InsertMenuBar(
WORD wMenuID,
WORD wButton );

Parameters
The following table describes the parameters for the InsertMenuBar method of the CCommandBar Class.
wMenuID
Specifies the resource ID of the MenuBar.
wButton
Specifies the zero-based index of a button in the command bar.
Return Values
true if successful; otherwise, false.
Remarks
This method places the MenuBar at the button position indicated by wButton.
Requirements
Windows CE version 5.0 or higher.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CCommandBar::InsertSeparator
Inserts a separator button on the command bar.

BOOL InsertSeparator(
int nWidth = 6,
WORD wButton );

Parameters
The following table describes the parameters for the InsertSeparator method of the CCommandBar Class.
nWidth
Specifies the width, in pixels, of the separator button.
wButton
Specifies the zero-based index of a button in the command bar which is greater or equal to zero and less than the number of
buttons in the bar. CMDBAR_END specifies the end of CommandBar.
Return Values
true if successful; otherwise, false.
Remarks
This method places the separator in the button position indicated by wButton. A separator does not receive user input.
Requirements
Windows CE version 5.0 or higher.
Header file: Declared in afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CCommandBar::Show
Shows or hides the command bar.

BOOL Show(BOOL bShow)

Parameters
The following table describes the parameter for the Show method of the CCommandBar Class.
bShow
Boolean that specifies whether to show or hide the command bar. Set this parameter to false to show the command bar, or
true to hide it.
Return Value
Returns the previous show state of the CCommandBar. Returns true if the command bar was displayed, false if it was hidden.
Remarks
Command bars are created with the show state set to true. To hide the command bar, call Show(false).
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CCommandBar Methods
Other Resources
Unique MFC for Devices Classes
CCeCommandBar
Smart Device Development

CDocList Class
Use CDocList to display lists of documents in a consistent way. The CDocList class wraps the operating system
implementation of the DocList window type with additional features for integration with an MFC Doc/View architecture.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Other Resources
Unique MFC for Devices Classes
CDocList Methods
CCeDocList
Smart Device Development

CDocList Methods
The following are the methods of the CDocList Class, which wraps the operating system implementation of the DocList
window type.

CDocList::CDocList Constructs a CDocList object.

CDocList::Create Creates and initializes the list associated with the CDocList object.

CDocList::DeleteSelection Deletes selected items.

CDocList::DisableUpdate Disables updating of CDocList.

CDocList::EnableUpdate Enables updating of CDocList.

CDocList::GetFilterIndex Gets current file filter selection, for example, for setting the current filter for a combo bo
x.

CDocList::GetItemCount Gets a count of items.

CDocList::GetNextItem Gets the next item in CDocList.

CDocList::GetNextWaveFile Selects the next .wav file.

CDocList::GetPrevWaveFile Selects the previous .wav file.

CDocList::GetSelectCount Gets the number of items selected.

CDocList::GetSelectedPathname Gets the pathname associated with the selected item.

CDocList::ReceiveIR Receives infrared signals.

CDocList::Refresh Refreshes CDocList.

CDocList::RenameMoveSelectedItems Displays the Rename/Move dialog box for selected items.

CDocList::SelectItem Selects the item associated with the path.

CDocList::SendEMail Sends e-mail.

CDocList::SendIR Sends infrared signals.

CDocList::SetFilterIndex Indicates file filter has been changed; for example, user has changed settings in an Opti
ons dialog box.

CDocList::SetFolder Sets a folder.

CDocList::SetItemState Changes the state of an item in CDocList.

CDocList::SetSelectedPathname Causes the item associated with the path to be selected during the next refresh.

CDocList::SetSelection Selects an item by index.


CDocList::SetSortOrder Sorts CDocList.

CDocList::Update Refreshes CDocList but does not restore the selection.

CCeDocList class has become CDocList Class in MFC 8.0. The following is code from an MFC 3.0 application:

CCommandBar* pDocListCB = pDocList->GetCommandBar();

This code generates the following error:


MainFrm.cpp(115) : error C2039: 'GetCommandBar' : is not a member of 'CDocList'
In MFC 8.0, create an instance of CDocListCommandBar instead.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::CDocList
Creates an instance of a CDocList object.

CDocList();

Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::Create
Creates and initializes the list associated with the CDocList object.

BOOL Create (
CWnd* pParentWnd,
LPCTSTR lpszFilterList,
LPCTSTR lpszFolder,
DWORD dwFlags = DLF_SHOWEXTENSION ) ;

Parameters
The following table describes the parameters for the Create method of the CDocList Class.
Parameter Description
pParentWnd Pointer to parent window—required.

lpszFilterList Pointer to the list of filters, a vertical bar (|) delimited list terminated with a ||\0.

lpszFolder Pointer to the folder.

dwFlags DLF_SHOWEXTENSION is the only value permitted in the current version.


Return Values
true if the list is successfully created and displayed; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::DeleteSelection
Deletes selected items.

HRESULT DeleteSelection();

Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::DisableUpdate
Disables the updating of the doclist.

void DisableUpdate();

Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::EnableUpdate
Enables the updating of the doclist.

void EnableUpdate();

Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::GetFilterIndex
Gets the current file-filter selection.

int GetFilterIndex();

Return Value
The index of the vertical bar (|) delimited filter list for the current filter selection. The index is one-based, not zero-based.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::GetItemCount
Gets the count of items.

int GetItemCount();

Return Value
The number of documents in the document list.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::GetNextItem
Gets the next item in the document list.

int GetNextItem(
int nStart,
UINT nFlags );

Parameters
The following table describes the parameters for the GetNextItem method of the CDocList Class.
Param Description
eter
nStart Specifies the item number in the document list to start the search.

nFlags Specifies the geometric relation of the requested item to the specified item, and the state of the requested item. The g
eometric relation can be one of these values:
Value Description
LVNI_ABOVE Searches for an item that is above the specified item.

LVNI_ALL Searches for a subsequent item by index, the default value.

LVNI_BELOW Searches for an item that is below the specified item.

LVNI_TOLEFT Searches for an item to the left of the specified item.

LVNI_TORIGHT Searches for an item to the right of the specified item.

Additionally you can specify the item's state, which can be zero, or it can be one or more of the following values:
Value Description
LVNI_DROPHILITED The item has the LVIS_DROPHILITED state flag set.

LVNI_FOCUSED The item has the LVIS_FOCUSED state flag set.

LVNI_SELECTED The item has the LVIS_SELECTED state flag set.

Remarks
If an item does not have all of the specified state flags set, the search continues with the next item.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::GetNextWaveFile
Gets the next .wav file.

BOOL GetNextWaveFile(
int* pnItem );

Parameters
The following table describes the parameter for the GetNextWaveFile method of the CDocList Class.
Parameter Description
pnItem Pointer to the next .wav file on the list.
Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::GetPrevWaveFile
Gets the previous .wav file.

BOOL GetPrevWaveFile(
int* pnItem );

Parameters
The following table describes the parameter for the GetPrevWaveFile method of the CDocList Class.
Parameter Description
pnItem Pointer to the previous .wav file on the list.
Return Value
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::GetSelectCount
Gets the number of selected items.

int GetSelectCount();

Return Value
The number of items selected in the document list.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::GetSelectedPathname
Gets the path associated with the selected item.

BOOL GetSelectedPathname(
LPTSTR pszPath,
WORD nSize );

Parameters
The following table describes the parameters for the GetSelectedPathname method of the CDocList Class.
pszPath
Pointer to the path of the selected item in the document list.
nSize
Specifies the length, in characters, of the buffer that receives the path.
Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::ReceiveIR
Used to receive infrared information.

void ReceiveIR(
LPTSTR pszPath );

Parameters
The following table describes the parameter for the ReceiveIR method of the CDocList Class.
pszPath
Pointer to the string containing the path.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::Refresh
Refreshes the document list.

BOOL Refresh();

Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::RenameMoveSelectedItems
Displays the Rename/Move dialog box for selected items.

BOOL RenameMoveSelectedItems();

Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::SelectItem
Causes the item associated with the path to be selected.

HRESULT SelectItem(
LPTSTR pszPath,
BOOL fVisible );

Parameters
The following table describes the parameters for the SelectItem method of the CDocList Class.
Parameter Description
pszPath Pointer to the string containing the path.

fVisible Indicates whether the document has become visible or invisible.


Return Value
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::SendEMail
Used to send e-mail.

void SendEMail(
LPTSTR pszPath );

Parameters
The following table describes the parameter for the SendEMail method of the CDocList Class.
Parameter Description
pszPath Pointer to the string containing the path.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::SendIR
Used to send infrared information.

void SendIR(
LPTSTR pszPath );

Parameters
The following table describes the parameter for the SendIR method of the CDocList Class.
Parameter Description
pszPath Pointer to the string containing the path.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::SetFilterIndex
Indicates that a file filter has been changed.

HRESULT SetFilterIndex(
int nIndex );

Parameters
The following table describes the parameter for the SetFilterIndex method of the CDocList Class.
Parameter Description
nIndex The index of the filter list delimited by the vertical bar (|). The index is one-based, not zero-based.
Return Value
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::SetFolder
Sets a folder.

void SetFolder(
LPTSTR pszFolder );

Parameters
The following table describes the parameter for the SetFolder method of the CDocList Class.
Parameter Description
pszFolder Pointer to the string containing the folder name.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::SetItemState
Changes the state of an item in the document list.

BOOL SetItemState(
int nItem,
UINT nState,
UINT nStateMask );

Parameters
The following table describes the parameters for the SetItemState method of the CDocList Class.
Parameter Description
nItem The index number for the item.

nState Specifies values for states to be changed.

nStateMask Specifies which states are to be changed.


Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::SetSelectedPathname
Causes the item associated with the path to be selected during the next refresh.

void SetSelectedPathname(
LPTSTR pszPath );

Parameters
The following table describes the parameter for the SetSelectedPathname method of the CDocList Class.
Parameter Description
pszPath Pointer to the string containing the path.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::SetSelection
Selects an item by index.

BOOL SetSelection(
int wItem );

Parameters
The following table describes the parameter for the SetSelection method of the CDocList Class.
Parameter Description
wItem The index number for the item.
Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocList::SetSortOrder
Sorts the document list. The sort order is always ascending.

BOOL SetSortOrder();

Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocList::Update
Refreshes the document list, but does not restore the selection.

HRESULT Update();

Return Values
true if successful; otherwise, false.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Reference
CDocList Class
Other Resources
Unique MFC for Devices Classes
CCeDocList
Smart Device Development

CDocListDocTemplate Class
This class is a refinement of the SDI application type, as facilitated by CSingleDocTemplate Class. Using this class lets an
application exist in DocList mode when no document is open.
After adding this document type to the application, call the ShowDocList member to initially create an instance of the
CDocList class.
Requirements
Windows CE versions 5.0 and higher.
Header file: Declared in Afxext.h.
See Also
Other Resources
Unique MFC for Devices Classes
Smart Device Development

CDocListDocTemplate Methods
CDocListDocTemplate Class is a similar class to the desktop CDocListDocTemplate which is a refinement of the SDI
application type.
This class lets an application exist in document mode when no document is present.
After adding this document type to the application, call the ShowDocList member to create a CDocList instance.
In This Section
CDocListDocTemplate::CDocListDocTemplate
Constructs a CDocListDocTemplate object.
CDocListDocTemplate::ShowDocList
Displays the document list. The CDocList is automatically created when CDocListDocTempate::ShowDocList is called.
See Also
Other Resources
Unique MFC for Devices Classes
CCeDocListDocTemplate
Smart Device Development

CDocListDocTemplate::CDocListDocTemplate
Constructs a CDocListDocTemplate object. Using this class you can dynamically allocate a CDocListDocTemplate object
and pass it to CWinApp::AddDocTemplate from the InitInstance method of your application class.

CDocListDocTemplate(
UINT nIDResource,
CRuntimeClass* pDocClass,
CRuntimeClass* pFrameClass,
CRuntimeClass* pViewClass,
LPCTSTR lpszFilterList,
LPCTSTR lpszFolder );

Parameters
The following table describes the parameters for the CDocListDocTemplate method of the CDocListDocTemplate Class.
Param Description
eter
nIDRes Specifies the identifier of the resources used with the document type. This may include menu, icon, accelerator table, a
ource nd string resources.

pDocCl Pointer to the CRuntimeClass object of the document class. This class is a CDocument-derived class you define to re
ass present your documents.

pFram Pointer to the CRuntimeClass object of the frame window class. This class can be a CFrameWnd-derived class, or it c
eClass an be CFrameWnd if you want default behavior for your main frame window.

pView Pointer to the CRuntimeClass object of the view class. This class is a CView-derived class you define to display your d
Class ocuments.

lpszFilt Pointer to the list of filters, a vertical bar (|) delimited list terminated with a ||\0.
erList

lpszFol Pointer to the folder.


der
Remarks
For additional information see CDocListDocTemplate.
Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxext.h.
See Also
Other Resources
Unique MFC for Devices Classes
CCeDocListDocTemplate
Smart Device Development

CDocListDocTemplate::ShowDocList
Used as a call from CWinApp::InitInstance to initially show the document list.

virtual void ShowDocList();

Requirements
Windows CE versions 5.0 and later.
Header file: Declared in Afxwin.h.
See Also
Other Resources
Unique MFC for Devices Classes
Smart Device Development

AfxEnableDRA
This function enables device resolution awareness in device application projects.

void AfxEnableDRA(BOOL bEnable);

Parameters
bEnable
Specifying TRUE enables device resolution awareness; specifying FALSE, or not calling the function, disables device
resolution awareness.
Remarks
The Device Resolution Awareness feature allows the application to respond to changes in resolution at run time, such as
changing from portrait to landscape mode.
Use the AfxEnableDRA() function when you instantiate CDialog directly. In this situation you are using the OnSize method
defined in dlgcore.cpp and implemented in the MFC DLL and LIB. In these library versions, AfxIsDRAEnabled() is used to
perform a run-time check to determine whether or not to call DRA::RelayoutDialog(...). AfxIsDRAEnabled() returns true
only if AfxEnableDRA(TRUE) has previously been called.
Note
When you use wizards to create an MFC project for devices, the generated code implements an override (CDialog::OnSize(i
nt, int)) for CDialog-derived classes. Device resolution awareness is then checked at compile time, and the decision to call o
r not call DRA::RelayoutDialog(...) is made.

Example
AfxEnableDRA(TRUE); //Enable Device Resolution Awareness
...
void CDialog::OnSize(UINT nType, int cx, int cy)
{
if (AfxIsDRAEnabled())
{
DRA::RelayoutDialog(
AfxGetInstanceHandle(),
this->m_hWnd,
DRA::GetDisplayMode() != DRA::Portrait ?
m_lpszWideTemplateName : m_lpszTemplateName);
}
else
{
CWnd::OnSize(nType, cx, cy);
}
}

See Also
Other Resources
Unique MFC for Devices Classes
Smart Device Development

C Run-Time Library Reference for Devices


The Microsoft C Run-Time Library for devices supports a subset of the functions that are available in the full Microsoft C Run-
Time Library for the desktop.
Supporting only a subset of the full library enables applications to run devices that have more limited resources than desktop
computers. For more information about filtering help topics for Run-Time Library references for devices, see
How to: Find Help for MFC Classes and Methods Supported for Devices and
How to: Find Help for ATL Classes and Methods Supported for Devices.
C Run-Time Library
For full documentation on the C Run-Time Library for devices, see Microsoft C Run-time Library for Windows CE.
Secure APIs
The following APIs have been added for device projects in Visual Studio 2005.

wcsncpy_s wcscpy_s wcscat_s

strncpy_s strcpy_s strcat_s

memmove_s memcpy_s _wsplitpath_s

_wmakepath_s _ultoa_s _ui64tow_s

_ui64toa_s _ltoa_s _localtime64_s

_itow_s _itoa_s _i64tow_s

_i64toa_s _gmtime64_s

See Also
Other Resources
Reference (Devices)
Smart Device Development

Standard C++ Library Reference for Devices


The device version of the Standard C++ Library is a subset of the full Standard C++ Library Reference.
New Functionality
Stream support has been added to this version of the Standard C++ Library.
Unsupported Functionality
The Standard C++ Library for devices does not include locale support.
uncaught_exception is only supported on Windows CE 5.0 and higher versions, including Windows Mobile 2005
platforms.
Unsupported Headers
The device version of the Standard C++ Library does not support the following headers:
<cerrno>
<csignal>
<locale>
See Also
Other Resources
Reference (Devices)
Visual C++ Libraries Reference
Smart Device Development

Compilers for Smart Devices


Visual Studio 2005 includes the following compilers that target microprocessors used in smart devices:
A 32-bit C/C++ compiler used to compile and link 32-bit ARM C and C++ programs.
A 32-bit C/C++ compiler used to compile and link 32-bit Renesas SH-4 C and C++ programs.
A C/C++ compiler used to compile and link MIPS16, MIPS32, MIPS64 C and C++ programs.
The compilers produce Common Object File Format (COFF) object files.
In This Section
Supported Device Microprocessors
List the microprocessor families that device compilers support.
Differences Between Desktop and Device Compilers

Provides reference information about compiler options, intrinsic functions, and predefined macros. In addition, describes
differences in data alignment and Structured Exception Handling that may be important when programming for smart
devices.
ARM Family Processors
Provides information about ARM technology compiler options, intrinsic functions, and call specifications.
Renesas Family Processors
Provides information about Renesas technology compiler options, intrinsic functions, and call specifications.
MIPS Family Processors
Provides information about MIPS technology compiler options, intrinsic functions, and call specifications.
Related Sections
Online Help for Smart Device Projects
Describes Visual Studio 2005 support for smart device programming.
Smart Device Development

Supported Device Microprocessors


The device compilers support a wide variety of microprocessors used for devices. Support includes compilers, intrinsic
functions that allow full optimization, and assemblers for tasks that cannot be supported in other ways.
Supported Microprocessors
The following list shows supported microprocessor families:
ARM licensed technologies for architectures v4, v4T, Thumb, v5TE, and Intel XScale
For information about ARM-licensed microprocessors, see ARM Web site.
For information about ARM-licensed Intel microprocessors, see Intel Web site.
Renesas SuperH SH4 microprocessors
For information about Renesas microprocessors, see Renesas Web site.
MIPS licensed technologies developed by NEC, Toshiba, Philips Semiconductor, Integrated Device Technologies, LSI
Logic, and Quantum Effect Design
For information about MIPS-licensed technologies, see MIPS Web site
For information about MIPS-licensed NEC microprocessors, see NEC Web site
For information about MIPS-licensed Toshiba microprocessors, see Toshiba Web site
For information about MIPS-licensed Phillips Semiconductor microprocessors, see
Philips Semiconductor Web site
See Also
Other Resources
Differences Between Desktop and Device Compilers
Smart Device Development

Differences Between Desktop and Device Compilers


The following topics provide descriptions of the differences between desktop and device compiler operation, including detailed
reference information about intrinsic functions and compiler errors.
In This Section
Unique Build Options

Describes build options uniquely defined for device compilers,


Shared Build Options
Lists build options shared with desktop compilers.
Intrinsic Functions for Device Compilers
Provided detailed reference information about the intrinsic functions common to all device compilers.
Pre-defined Macros

Provides reference information about macros included with device compilers.


RISC Processor Data Alignment
Provides programmer information about data alignment issues that vary across different microprocessors.
Exception Handling for Device Compilers
Describes the unique ways RISC-based microprocessor compilers manage exception handling.
Device Compiler Error Messages
Provides information about compiler and linker error messages that you might encounter when working with device
compilers.
Related Sections
ARM Family Processors

Provides information about ARM technology compiler options, intrinsic functions, and call specifications.
Renesas Family Processors
Provides information about Renesas technology compiler options, intrinsic functions, and call specifications.
MIPS Family Processors

Provides information about MIPS technology compiler options, intrinsic functions, and call specifications.
Smart Device Development

Unique Build Options


Nearly all of the build options offered for desktop compilers are also available for device compilers, and are implemented in
identical ways. Linker option implementation is identical in both environments.
For a list compiler options that are common to both desktop compilers and device compilers, see Shared Build Options.
The following table shows compiler options that support device compilers in a way that differs significantly from desktop
implementations.
Option Description
/callcap - Enable callcap profiling Inserts callcap profiling hooks at the beginning and end of each function.

/GS - Enable Security Checks Enables stack checking to detect buffer overrun attacks.

In addition, each supported microprocessor family has processor-specific compiler options that implement unique
functionality.
See Also
Reference
ARM Compiler Options
Renesas Compiler Options
MIPS Compiler Options
Smart Device Development

/callcap - Enable callcap profiling


The /callcap option causes the compiler to insert calls to profiling hooks at the beginning and end of each function.
You must compile profiling hooks without the /callcap switch. If you compile the profiling hook functions with the /callcap
switch, the functions will perform infinite recursive calls to themselves.
The following code example, callcaphooks.c, shows a profiling hook function, _CAP_Enter_Function, for compilation without
callcap.
The /callcap switch inserts calls to the profiling hooks for all functions compiled with the /callcap compiler switch.

int main()
{
double d0 = 2.0, d1 = 4.0, result;
// No profiling for printf, because the library
// function is not compiled with /callcap.
printf("\n");
// callcap profiling hooks are called
// after the function is entered and before
// leaving it.
// The following example shows how to insert profiling hooks.
// File: callcaphooks.c

#include <stdio.h>
int main();
void _CAP_Enter_Function(void *p)
{
if (p != main)
printf("Enter function (at address %p) at %d\n",
p, GetTickCount());
return;
}
void _CAP_Exit_Function(void *p)
{
if (p != main)
printf("Leaving function (at address %p) at %d\n",
p, GetTickCount());
return;
}

See Also
Concepts
Unique Build Options
Smart Device Development

/GS - Enable Security Checks


When you build with the /GS build option on, the compiler attempts to detect any direct buffer overruns into the return
address. When a buffer overrun overwrites a return address, it provides an opportunity to exploit code that does not enforce
buffer size restrictions.
The following sample overruns a buffer. It displays a message box and terminates the process when built with /GS.

#include <cstring>

// Vulnerable function
void vulnerable(const char *str)
{
char buffer[10];
strcpy(buffer, str); // overrun buffer !!!
}

int main()
{
// declare buffer that is bigger than expected
char large_buffer[] = "This string is longer than 10 characters!!!";
vulnerable(large_buffer);
}

Remarks
Buffer overruns are more easily exploited on machines, such as x86, with calling conventions that pass the return address of
function calls on the stack.
To prevent buffer overrun exploitation when a function is compiled with /GS, the compiler identifies functions that might be
subject to buffer overrun problems, and inserts a security cookie on the stack before the associated return address. If, on
function exit, the security cookie has changed, then the compiler reports an error and terminates the process.
When working on smart devices, however, the security cookie can become an issue. If an EXE or DLL that does not use one of
the default CRT entry points, but instead calls _cinit through CRT startup code, the compiler will report an error because _cinit
resets the expected value of the security cookie. If _cinit changes the value of the security cookie, the compiler falsely detects a
buffer overrun, reports the error, and terminates the process.
To avoid this issue:
Do not use arrays or _alloca in any functions that call _cinit.
Initialize the CRT normally with a default entry point, such as WinMainCRTStartup or _DllMainCRTStartup.
/GS does not protect against all buffer overrun security attacks. For example, buffer overrun attacks are still possible by
overwriting into the parameters area.
Even if you use /GS, you should strive to write secure code. That is, make sure that your code has no buffer overruns. You can
inject security checks into compiled code by enforcing buffer size restrictions.
See Also
Other Resources
Differences Between Desktop and Device Compilers
Smart Device Development

Shared Build Options


The following table shows options that are supported by all supported compilers, including those that target desktop workstations and smart devices. For additional
documentation on these options, see the Visual C++ reference in Visual Studio .NET combined documentation.

/? /c (Compile Without Linking) /C (Preserve Comments During Preprocessing))

/D (Preprocessor Definitions) /E (Preprocess to stdout) /EH (Exception Handling Model)

/EP (Preprocess to stdout Without #line Directives) /F (Set Stack Size) /FA, /Fa (Listing File)

/Fd (Program Database File Name) /Fe (Name EXE File) /FI (Name Forced Include File)

/Fm (Name Mapfile) /Fo (Object File Name) /Fp (Name .pch File)

/FR, /Fr (Create .sbr File) /GF (Eliminate Duplicate Strings)) /GL (Whole Program Optimization)

/GR (Enable Run-Time Type Information) /GX (Enable Exception Handling) /Gy (Enable Function-Level Linking)

/GZ (Enable Stack Frame Run-Time Error Checking) /H (Restrict Length of External Names) /HELP (Compiler Command-Line Help)

/I (Additional Include Directories) /J (Default char Type Is unsigned) /link (Pass Options to Linker)

/MD, /MT, /LD (Use Run-Time Library) /nologo (Suppress Startup Banner) (C/C++) /O1, /O2 (Minimize Size, Maximize Speed)

/Ob (Inline Function Expansion) /Od (Disable (Debug)) /Og (Global Optimizations)

/Oi (Generate Intrinsic Functions) /Os, /Ot (Favor Small Code, Favor Fast Code) /Ox (Full Optimization)

/P (Preprocess to a File) /RTC (Run-Time Error Checks) /showIncludes (List Include Files)

/Tc, /Tp, /TC, /TP (Specify Source File Type) /U, /u (Undefine Symbols) /V (Version Number)

/vd (Disable Construction Displacements) /vmb, /vmg (Representation Method) /vmm, /vms, /vmv (General Purpose Representation)

/w, /Wn, /WX, /Wall, /wln, /wdn, /wen, /won (Warning Level) /WL (Enable One-Line Diagnostics) /Wp64 (Detect 64-Bit Portability Issues)

/X (Ignore Standard Include Paths) /Y (Precompiled Headers) /Yc (Create Precompiled Header File)

/Yd (Place Debug Information in Object File) /Yu (Use Precompiled Header File) /YX (Automatic Use of Precompiled Headers)

/Z7, /Zd, /Zi, /ZI (Debug Information Format) /Za, /Ze (Disable Language Extensions) /Zc (Conformance)

/Zg (Generate Function Prototypes) /Zl (Omit Default Library Name) /Zm (Specify Precompiled Header Memory Allocation Limit)

/Zp (Struct Member Alignment) /Zs (Syntax Check Only) ..


See Also
Reference
ARM Compiler Options
Renesas Compiler Options
MIPS Compiler Options
Smart Device Development

Intrinsic Functions for Device Compilers


The device compilers support a wide variety of intrinsic functions. Some intrinsic functions are supported by all device
compilers. In addition, the compilers for each microprocessor family support additional intrinsic functions.
Common intrinsic functions perform simple and useful operations that are difficult to express concisely in C or C++. They are
called common because all device compilers support them.
Using intrinsic functions to access assembly instructions instead of inline assembly results in code that can still be fully
optimized by the compiler. All of the intrinsic functions are permanent. Using them in #pragma function generates an error
message during compilation.
You can enable these functions by including Cmnintrin.h.
In This Section
Common Intrinsic Functions for Device Compilers
Provides reference information about intrinsic functions supported for device compilers.
Intrinsic Forms of CRT Functions

Provides reference information about CRT functions that are supported as intrinsic functions by the device compilers.
Unsupported Intrinsic Functions

Lists the intrinsic functions that are supported by desktop compilers, but not supported by device compilers.
Macros for Common Intrinsics
Provided detailed reference information about macros that assist with processor-specific requirements.
Related Sections
Intrinsic Functions for ARM Microprocessors
Provides reference materials about intrinsic functions specifically defined for the ARM microprocessor compiler.
Intrinsic Functions for MIPS Microprocessors
Provides reference materials about intrinsic functions specifically defined for the MIPS microprocessor compiler.
Intrinsic Functions for Renesas Microprocessors
Provides reference materials about intrinsic functions specifically defined for the SH microprocessor compiler.
Smart Device Development

Common Intrinsic Functions for Device Compilers


The following table shows intrinsic functions supported by all device compilers:

__assume _debugbreak __noop _CacheRelease

_CacheWriteBack _CopyFloatFromInt32 _CopyInt32FromFloat _CopyInt64FromDouble

_CountLeadingOnes, _CountLeadingOnes64 _CountLeadingSigns, _CountLeadingSigns64 _CountLeadingZeros, _CountLeadingZeros64 _CountOneBits, _CountOneBits64

_ICacheRefresh _isunordered, _isunorderedf _MulHigh, _MulUnsignedHigh _prefetch

_ReadWriteBarrier, _WriteBarrier _ReturnAddress __trap MulDiv


See Also
Reference
Unsupported Intrinsic Functions
Intrinsic Forms of CRT Functions
Smart Device Development

_debugbreak
This function causes a debug breakpoint exception to be inserted.

void __cdecl __debugbreak(void);

Parameters
None.
Return Values
None.
Remarks
The breakpoint transfers control to the exception handler.
Requirements
Routine Required header Architecture
_debugbreak <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_prefetch
This function loads the data cache from main memory, if possible.

void __cdecl __prefetch(


void *
);

Parameters
*
[in] Pointer to cache line.
Return Value
None.
Remarks
This function might do nothing if the requested functionality is not available on the target hardware platform.
Requirements
Routine Required header Architecture
_prefetch <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

__trap
This function inserts a trap instruction.

int __cdecl __trap(


arg1,
);

Parameters
arg1
[in] The trap number.
Return Value
The integer value provided by the trap handler. If the trap handler provides no return value, the return value is undefined.
Remarks
The compiler backend can enforce restrictions on the arguments, including the trap number, and can define a special calling
convention for the trap.
The interpretation of the trap number and the actions taken by the trap handler are not defined.
Requirements
Routine Required header Architecture
__trap <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CacheRelease
This function writes the cache line containing the address referenced by the pointer to main memory, and then marks the
cache line as empty.

void __cdecl __CacheRelease(


void *
);

Parameters
*
[in] Pointer to cache line.
Return Value
None.
Remarks
This function might do nothing if the requested functionality is not available on the target hardware platform.
Requirements
Routine Required header Architecture
_CacheRelease <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CacheWriteBack
This function writes the cache line containing the address referenced by the pointer to main memory.

void __cdecl __CacheWriteback(


void *
);

Parameters
*
[in] Pointer to cache line.
Return Value
None.
Remarks
This function might do nothing if the requested functionality is not available on the target hardware platform.
Requirements
Routine Required header Architecture
_CacheWriteBack <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_ICacheRefresh
This function releases the cache line containing the address referenced by the pointer from the instruction cache.

void __cdecl __ICacheRefresh(


void *
);

Parameters
*
[in] Pointer to cache line.
Return Value
None.
Remarks
The extent of the instruction cache refreshed is implementation-dependent. It is usually at least 16 bytes, but can be the entire
instruction cache. In addition, prefetch of the instructions referenced by the pointer is implementation-dependent.
This function is not supported for SH and MIPS microprocessors.
Requirements
Routine Required header Architecture
_ICacheRefresh <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_ReadWriteBarrier, _WriteBarrier
_ReadWriteBarrier forces all previous memory accesses to complete before subsequent memory access is started.
_WriteBarrier forces all previous memory write operations to complete before any subsequent write operation is started.

void __cdecl _ReadWriteBarrier(void);


void __cdecl _WriteBarrier(void);

Parameters
None.
Return Value
None.
Remarks
_WriteBarrier is usually used for writing device drivers to make sure that a set of commands has been sent to the device
before further commands are issued. The compiler does not reschedule memory writes across an invocation of _WriteBarrier,
even on hardware platforms without explicit synchronization instructions.
_ReadWriteBarrier is usually used for writing device drivers to make sure that commands have been sent to the device before
status is read.
The compiler does not reschedule memory reads and writes across an invocation of _ReadWriteBarrier, even on hardware
platforms without explicit synchronization instructions.
Requirements
Routine Required header Architecture
_WriteBarrier <cmnintrin.h> x86, ARM, SH-4, MIPS

_ReadWriteBarrier <cmnintrin.h> x86, ARM, SH-4, MIPS


See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_ReturnAddress
This function provides the return address of the instruction in the calling function that will be executed after control returns to
the caller.

void _ReturnAddress(void);

Parameters
None.
Return Value
None.
Remarks
Build the program in the Example section, and step through it in the debugger.
As you step through the program, note the address that is returned from _ReturnAddress.
Then, immediately after returning from the function where _ReturnAddress was used, open the Disassembly window and
note that the address of the next instruction to be executed matches the address returned from _ReturnAddress.
Optimizations such as inlining can affect the return address.
For example, if the following sample program is compiled with /Ob (Inline Function Expansion) with n=1, inline_func is
inlined into the calling function, main. Therefore, the calls to _ReturnAddress from inline_func and main each produce the
same value.
Example
// compiler_intrinsics__ReturnAddress.cpp
#include <stdio.h>
// _ReturnAddress should be prototyped before use
#ifdef __cplusplus
extern "C"
#endif
void * _ReturnAddress(void);
#pragma intrinsic(_ReturnAddress)

__declspec(noinline)
void noinline_func(void)
{
printf("Return address from %s: %p\n", __FUNCTION__, _ReturnAddress());
}
__forceinline
void inline_func(void)
{
printf("Return address from %s: %p\n", __FUNCTION__, _ReturnAddress());
}

int main(void)
{
noinline_func();
inline_func();
printf("Return address from %s: %p\n", __FUNCTION__, _ReturnAddress());
return 0;
}

Requirements
Routine Required header Architecture
_ReturnAddress <cmnintrin.h> x86, ARM, SH-4, MIPS

See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CopyDoubleFromInt64
This function copies a floating-point double long integer into a long integer register.

double _CopyInt64FromDouble(
__int64 arg1
);

Parameters
arg1
[in] The long integer argument that the function acts on.
Return Values
The floating-point double result of converting arg1.
Remarks
This function can be implemented by copying the source value using a temporary memory location.
Requirements
Routine Required header Architecture
_CopyDoubleFromInt64 <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CopyFloatFromInt32
This function copies an integer value to a floating-point register.

float _CopyFloatFromInt32(
___int32 arg1
);

Parameters
arg1
[in] The integer value acted upon by the function.
Return Values
The floating point conversion of arg1.
Remarks
This function can be implemented by copying the source value using a temporary memory location.
Requirements
Routine Required header Architecture
_CopyFloatFromInt32 <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CopyInt32FromFloat
This function copies a floating-point number into an integer register.

__int32 _CopyInt32FromFloat(
float arg1
);

Parameters
arg1
[in] The floating-point value acted upon by the function.
Return Values
The integer conversion of arg1.
Remarks
This function can be implemented by copying the source value using a temporary memory location.
Requirements
Routine Required header Architecture
_CopyInt32FromFloat <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CopyInt64FromDouble
This function copies a floating-point double to a long integer register.

__int64 _CopyInt64FromDouble(
double arg1
);

Parameters
arg1
[in] The floating-point double argument acted on by the function.
Return Values
The long integer result of the conversion.
Remarks
This function can be implemented by copying the source value using a temporary memory location.
Requirements
Routine Required header Architecture
_CopyInt64FromDouble <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CountLeadingOnes, _CountLeadingOnes64
This function returns the number of contiguous one bits starting with the most significant bit.

unsigned __cdecl _CountLeadingOnes(


long arg1
);

unsigned __cdecl _CountLeadingOnes64(


__int64 arg1
);

Parameters
arg1
[in] The long integer argument that the function examines to find one bits.
Return Values
The number of contiguous one bits in arg1. If all bits in arg1 are set, the return value of _CountLeadingOnes is 32, or the
value of _CountLeadingOnes64 is 64..
Remarks
This function can be implemented by calling a runtime function.
Requirements
Routine Required header Architecture
_CountLeadingOnes <cmnintrin.h> x86, ARM, SH-4, MIPS

_CountLeadingOnes64 <cmnintrin.h> x86, ARM, SH-4, MIPS


See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CountLeadingSigns, _CountLeadingSigns64
This function returns the number of contiguous bits that match the sign bit, starting with the next most significant bit.

unsigned __cdecl _CountLeadingSigns(


long arg1
);

unsigned __cdecl _CountLeadingSigns64(


__int64 arg1
);

Parameters
arg1
[in] The unsigned integer value that the function operates on.
Return Values
The number of contiguous bits in arg1 that match the sign bit.
Remarks
This function can be implemented by calling a runtime function.
Requirements
Routine Required header Architecture
_CountLeadingSigns <cmnintrin.h> x86, ARM, SH-4, MIPS

_CountLeadingSigns64 <cmnintrin.h> x86, ARM, SH-4, MIPS


See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CountLeadingZeros, _CountLeadingZeros64
This function returns the number of contiguous zero bits starting with the most significant bit in the argument.

unsigned __cdecl _CountLeadingZeros(


long arg1
);

unsigned __cdecl _CountLeadingZeros64(


__int64 arg1
);

Parameters
arg1
[in] The unsigned integer to be examined by the function.
Return Values
The number of contiguous zero bits in arg1. If none of the bits in arg1 are set, the return value is of _CountLeadingZeros is
32, or the value of _CountLeadingZeros64 is 64.
Remarks
This function can be implemented by calling a runtime function.
Requirements
Routine Required header Architecture
_CountLeadingZeros <cmnintrin.h> x86, ARM, SH-4, MIPS

_CountLeadingZeros <cmnintrin.h> x86, ARM, SH-4, MIPS


See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_CountOneBits, _CountOneBits64
This function returns the number of one bits in the argument.

unsigned __cdecl _CountOneBits(


long arg1
);

unsigned __cdecl _CountOneBits64(


__int64 arg1
);

Parameters
arg1
[in] The long integer value that the function examines for one bits.
Return Values
The number of one bits.
Remarks
This function can be implemented by calling a runtime function.
Requirements
Routine Required header Architecture
_CountOneBits <cmnintrin.h> x86, ARM, SH-4, MIPS

_CountOneBits64 <cmnintrin.h> x86, ARM, SH-4, MIPS


See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_isunordered, _isunorderedf
_isunordered compares two double precision numbers to determine if they are unordered.
_isunorderedf compares two floating-point numbers to determine if they are unordered.

int __cdecl _isunordered(


double arg1,
double arg2
);

int __cdecl _isunorderedf(


float arg1,
float arg2
);

Parameters
arg1
[in] The value to be compared to arg2.
arg2
[in] The value to be compared to arg1.
Return Values
Returns a Boolean value.
TRUE indicates that arg1 and arg2 are unordered.
Remarks
IEEE-754 floating-point comparison can have four separate result values: less-than, equal-to, greater-than or unordered.
The first three conditions can be tested using normal C operators, and this function is used to test for the last condition.
Two values are unordered if either is a NaN. This means that a NaN is not equal to any value, even itself.
The C++ compiler returns a bool value instead of an int.
Requirements
Routine Required header Architecture
_isunordered <cmnintrin.h> x86, ARM, SH-4, MIPS

_isunorderedf <cmnintrin.h> x86, ARM, SH-4, MIPS


See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

MulDiv
The MulDiv function multiplies two 32-bit values and then divides the 64-bit result by a third 32-bit value. The return value is
rounded up or down to the nearest integer.

int MulDiv(
int nNumber,
int nNumerator,
int nDenominator
);

Parameters
nNumber
[in] Multiplicand.
nNumerator
[in] Multiplier.
nDenominator
[in] Number by which the result of the multiplication (nNumber * nNumerator) is to be divided.
Return Values
If the function succeeds, the return value is the result of the multiplication and division. If either an overflow occurred or
nDenominator was 0, the return value is –1.
Requirements
Routine Required header Architecture
MulDiv <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_MulHigh, _MulUnsignedHigh
This function returns the high-order 32-bit result of multiplying two arguments.

long __cdecl _MulHigh(


long arg1,
long arg2
);

unsigned long __cdecl _MulUnsignedHigh(


unsigned long arg1,
unsigned long arg2
);

Parameters
arg1
[in] The first argument in the product.
arg2
[in] The second argument in the product.
Return Values
The long integer result of multiplying arg1 and arg2.
Remarks
This function can be useful for detecting overflow. _MulHigh is useful for multiplying integers scaled to represent [-0.5..0.5),
and _MulUnsignedHigh is useful for multiplying integers scaled to represent 0..1).
Requirements
Routine Required header Architecture
_MulHigh <cmnintrin.h> x86, ARM, SH-4, MIPS

_MulUnsignedHigh <cmnintrin.h> x86, ARM, SH-4, MIPS


See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

__assume
The __assume intrinsic function passes a hint to the optimizer.

__assume(expression)

Parameters
expression
Condition to be tested.
Return Value
None.
Remarks
The optimizer assumes that the condition represented by expression is true at the point where the keyword appears and
remains true until expression is altered (for example, by assignment to a variable). Selective use of hints passed to the
optimizer by __assume can improve optimization.
Example
//
// A common use of __assume tests the default case of a switch statement.
//
#ifdef DEGUG
# define ASSERT(e) ( ((e) || assert(__FILE__, __LINE__) )
#else
# define ASSERT(e) ( __assume(e) )
#endif

void gloo(int p)
{
switch(p){
case 1:
blah(1);
break;
case 2:
blah(-1);
break;
default:
__assume(0);
// This tells the optimizer that the default
// cannot be reached. Hence, no extra code
// is generated to check that 'p' has a value
// not represented by a case arm. This makes the switch
// run faster.
}
}

Requirements
Routine Required header Architecture
__assume <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

__noop
__noop gives you a function name to use when you want the function to be ignored and the argument list unevaluated.

__noop(functionname)

Parameters
Functionname
Name of function to be ignored
Return Value
None.
Example
// The following code shows how you could use __noop
// compile with or without /DDEBUG
#include <stdio.h>

#if DEBUG
#define PRINT printf
#else
#define PRINT __noop
#endif

void main() {
PRINT("\nhello\n");
}

Requirements
Routine Required header Architecture
__noop <cmnintrin.h> x86, ARM, SH-4, MIPS
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

Intrinsic Forms of CRT Functions


The following table lists intrinsic forms of CRT functions that are supported by device compilers:

abs, _abs64 _alloca

_byteswap_uint64, _byteswap_ulong, _byteswap_ushort labs

_lrotl, _lrotr memcmp, wmemcmp

memcpy, wmemcpy memset, wmemset

_rotl, _rotl64, _rotr_rotr64 strcat, wcscat, _mbscat

strcmp, wcscmp, _mbscmp strcpy, wcscpy, _mbscpy

strlen, strlen_l, wcslen, wcslen_l, _mbslen, _mbslen_l, _mbstrlen, _mbstrlen_l _strset, _wcsset, _mbsset, _mbsset_l
Intrinsic Forms of Math Library Functions
The following table lists intrinsic forms of math library functions that are supported by device compilers:

acos asin atan atan

ceil, ceilf cos, cosf, cosh, coshf fmod, fmodf exp, log, and log

floor, floorf pow sin, sinf, sinh, sinhf sqrt

tan, tanf, tanh, tanhf . . .


See Also
Reference
Unsupported Intrinsic Functions
Common Intrinsic Functions for Device Compilers
Smart Device Development

Unsupported Intrinsic Functions


Visual Studio desktop compilers for x86, AMD64, or Intel Itanium (IPF) architectures support the functions in the following list.
Device compilers do not support these intrinsic functions.

__break __cpuid

__dsrlz __faststorefence

__fc __fci

__fclrf __flushrs

__fsetc __fwb

__getCFS __getcx86, AMD64, IA64, IPFerseflags

__getPSP __getReg

__inbyte __inbytestring

__indword __indwordstring

__int2c __invalat

__invlpg __Inword, __inwordstring

__isNat __isrlz

__lfetch, __lfetch_excl, __lfetchfault, __lfetchfaultexcl __load128, __load128_acq

__movsb, __movsd,__movsq, __movsw __mul128

__mulh __outbyte

__outbytestring __outword

__outwordstring __ptcg, __ptcga

__ptcl __ptrcl, __ptri

__rdteb __rdtsc

__readcr0, __readcr2, __readcr3, __readcr4, __readcr8 __readfsbyte, __readfsdword, __readfsqword, __readfsword

__readgsbyte, __readgsdword, __readgsqword, __readgsword __readmsr

__readpmc __rsm

__rum __segmentlimit

__setReg __shiftleft128
__shiftright128 __ssm

__store128, __store128_rel __stosb, __stosd, __stosq, __stosw

__sum __synci

__writefsbyte, __writefsdword, __writefsqword, __writefsword __writegsbyte, __writegsdword, __writegsqword, __writegsword

__writemsr __yield

_AcquireSpinLock _AddressOfReturnAddress

_BitScanForward, _BitScanForward64 _BitScanReverse, _BitScanReverse64

_bittest, _bittest64 _bittestandcomplement,_bittestandcomplement64

_bittestandreset, _bittestandreset64 _bittestandset, _bittestandset64

_InterlockedAdd _InterlockedAddLargeStatistic

_InterlockedAnd _InterlockedAnd, _InterlockedAnd64

_interlockedbittestandreset, _interlockedbittestandreset64 _InterlockedCompare64Exchange

_InterlockedCompareExchange16 _InterlockedCompareExchange64

_InterlockedDecrement16 _InterlockedExchangePointer

_InterlockedIncrement16 _InterlockedOr

_InterlockedXor _ReadBarrier

_ReleaseSpinLock _thash

_ttag _umul128

_umulh _wbinvd

_writecr0, _writecr2, _writecr3, _writecr4, _writecr8, ..

The following table lists intrinsic forms of math library functions that are not supported by device compilers:

acosf acosl asinf

asinl atanf atanl

atan2f atan2l ceilf

ceill coshf coshl

cosf cosl expf

expl floorf floorl


fmodf fmodl logf

logl log10f log10l

powf powl sinf

sinl sinhf sinhl

sqrtf sqrtl tanf

tanl tanhf tanhl


See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

Macros for Common Intrinsics


All microprocessor families that support common intrinsic functions have a machine-dependent description of support in the
header file, cmnintr.h. The machine-dependent description does the following:
Declares the functions with the correct prototype
Enables the intrinsic version
Defines macros that classify how the function is supported
You can use the intrinsic function unconditionally or you can use one of the macros to classify the intrinsic support in your CPU
environment.
The following table shows descriptions of the macros for common intrinsic functions.
Macro Description
_INTRINSIC_IS_HELPER This macro determines if an intrinsic function is instantiated through a call to the C Run-time Libr
ary (CRT).

_INTRINSIC_IS_INLINE This macro tests to determine if the compiler can expand a specified intrinsic to one or more lines.

_INTRINSIC_IS_SAFE This macro determines if a specified intrinsic function is instantiated independent of the OS.

_INTRINSIC_IS_SUPPORTED This macro determines if a specified intrinsic function is supported.


See Also
Reference
Common Intrinsic Functions for Device Compilers
Smart Device Development

_INTRINSIC_IS_HELPER
This macro determines if a specified intrinsic function is supported.

_INTRINSIC_IS_SUPPORTED(arg)

Parameters
Arg
The name of the intrinsic function of interest.
Return Value
A nonzero return value indicates that the specified intrinsic is supported by the compiler.
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_INTRINSIC_IS_INLINE
This macro determines if a specified intrinsic function is supported.

_INTRINSIC_IS_SUPPORTED(arg)

Parameters
Arg
[in] The name of the intrinsic function of interest.
Return Value
A nonzero return value indicates that the specified intrinsic is supported by the compiler.
Example
// The followig example shows how to use the _INTRINSIC_IS_INLINE macro to determine if
the _rotl intrinsic will be expanded inline.
//
#include <cmnintrin.h>
#if _INTRINSIC_IS_INLINE(_rotl)
x = _rotl(y, 3);
#else
x = MY_ROTL(y, 3); // call my inline implementation, not the CRT helper
#endif

See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_INTRINSIC_IS_SAFE
This macro determines if a specified intrinsic function is instantiated independent of the OS.

_INTRINSIC_IS_SAFE(arg)

Parameters
Arg
[in] The name of the intrinsic function of interest.
Return Value
A nonzero return value indicates that the specified intrinsic does require invocation of an OS feature.
Remarks
An intrinsic function expansion sometimes requires the compiler to invoke an operating system feature because the compiler
itself cannot perform the particular task. Because the compiler cannot control whether the OS provides the required feature,
such an intrinsic is considered unsafe.
For example, the __trap intrinsic assumes that an OS handler is available to take an action. The compiler cannot guarantee that
such a handler is present, so the __trap intrinsic is considered unsafe.
See Also
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_INTRINSIC_IS_SUPPORTED
This macro determines if an intrinsic function is instantiated through a call to the Microsoft C Run-Time Library (CRT).

_INTRINSIC_IS_HELPER(arg)

Parameters
Arg
[in] The name of the intrinsic function of interest.
Return Value
A nonzero return value indicates that intrinsic named by arg is instantiated with a call to the CRT.
Example
//
// The following example shows how to use the
// _INTRINSIC_IS_SUPPORTED macro to determine
// support for the __trap intrinsic function.
//
#include <cmnintrin.h>
#if INTRINSIC_IS_SUPPORTED(__trap)
__trap(1); // __trap IS SUPPORTED
#else
// __trap IS NOT SUPPORTED
#endif
//

See Also
Reference
Common Intrinsic Functions for Device Compilers
Smart Device Development

Pre-defined Macros
The device compilers recognize seven predefined ANSI C macros and the Microsoft C++ implementation provides several
more.
These macros take no arguments and cannot be redefined. Their value, except for __LINE__ and __FILE__, must be constant
throughout compilation.
The following table provides additional information about predefined macros, some of which are defined with multiple values.
Macro Description
__DATE_ The compilation date of the current source file.
_
The date is a string literal of the form Mmm dd yyyy.

__FILE__ The name of the current source file. __FILE__ expands to a string surrounded by double quotation marks.

__FUNC Valid only within a function and returns the undecorated name of the enclosing function (as a string).
TION__
__FUNCTION__ is not expanded if you use /EP (Preprocess to stdout Without #line Directives) or /P (Preproce
ss to a File) compiler options.

__LINE_ The line number in the current source file.


_
The line number is a decimal integer constant. It can be altered with a #line directive.

__STDC_ Indicates full conformance with the ANSI C standard.


_
Defined as the integer constant 1 only if the /Za, /Ze (Disable Language Extensions) compiler option is given and
you are not compiling C++ code; otherwise is undefined.

__TIME_ The most recent compilation time of the current source file.
_
The time is a string literal of the form hh:mm:ss.

__TIMES The date and time of the last modification of the current source file, expressed as a string literal in the form Ddd Mm
TAMP__ m Date hh:mm:ss yyyy, where Ddd is the abbreviated day of the week and Date is an integer from 1 to 31.
Microsoft-specific Macros
The following table shows additional predefined macros that are Microsoft-specific.
_CHAR_UNSIGNED
Default char type is unsigned. Defined when /J (Default char Type Is unsigned) is specified.
__cplusplus
Defined for C++ programs only.
_CPPRTTI
Defined for code compiled with /GR (Enable Run-Time Type Information).
_CPPUNWIND
Defined for code compiled with /GX (Enable Exception Handling).
_MFC_VER
Defines the MFC version. Defined as 0x0600 for Microsoft Foundation Class Library 6.0 or later. Always defined.
_MSC_EXTENSIONS
This macro is defined when compiling with the /Za, /Ze (Disable Language Extensions) compiler option (the default). Its
value, when defined, is 1.
_MSC_VER
Defines the compiler version. Defined as 1200 for Microsoft Visual C++ 6.0 or later. Always defined.
_WIN32
Defined for applications for Win32. Always defined.
See Also
Other Resources
Differences Between Desktop and Device Compilers
Smart Device Development

RISC Processor Data Alignment


Alignment of data is an important issue when porting or writing code on some target architectures, especially architectures
other than x86.
Depending on the architecture, unaligned operations with primitive data types can cause poor application performance, or can
cause your application to fault and terminate abnormally.
This section provides information to help you avoid such pitfalls.
In This Section
About Data Alignment

Describes how data alignment issues impact device programming.


Avoiding Alignment Errors
Provides guidelines for keeping primitive types properly aligned.
Working with Packing Structures
Describes how structure packing interacts with alignment.
__unaligned keyword
Provides reference information about using the __unaligned modifier to deal with alignment issues.
Smart Device Development

About Data Alignment


Many CPUs, such as those based on Alpha, IA-64, MIPS, and SuperH architectures, refuse to read misaligned data. When a
program requests that one of these CPUs access data that is not aligned, the CPU enters an exception state and notifies the
software that it cannot continue. On ARM, MIPS, and SH device platforms, for example, the operating system default is to give
the application an exception notification when a misaligned access is requested.
Misaligned memory accesses can incur enormous performance losses on targets that do not support them in hardware.
Alignment
Alignment is a property of a memory address, expressed as the numeric address modulo a power of 2. For example, the
address 0x0001103F modulo 4 is 3; that address is said to be aligned to 4n+3, where 4 indicates the chosen power of 2. The
alignment of an address depends on the chosen power of two. The same address modulo 8 is 7.
An address is said to be aligned to X if its alignment is Xn+0.
CPUs execute instructions that operate on data stored in memory, and the data are identified by their addresses in memory. In
addition to its address, a single datum also has a size. A datum is called naturally aligned if its address is aligned to its size, and
misaligned otherwise. For example, an 8-byte floating-point datum is naturally aligned if the address used to identify it is
aligned to 8.
Compiler handling of data alignment
Device compilers attempt to allocate data in a way that prevents data misalignment.
For simple data types, the compiler assigns addresses that are multiples of the size in bytes of the data type. Thus, the compiler
assigns addresses to variables of type long that are multiples of four, setting the bottom two bits of the address to zero.
In addition, the compiler pads structures in a way that naturally aligns each element of the structure. Consider the structure
struct x_ in the following code example:

struct x_
{
char a; // 1 byte
int b; // 4 bytes
short c; // 2 bytes
char d; // 1 byte
} MyStruct;

The compiler pads this structure to enforce alignment naturally.


Example
The following code example shows how the compiler places the padded structure in memory:

// Shows the actual memory layout


struct x_
{
char a; // 1 byte
char _pad0[3]; // padding to put 'b' on 4-byte boundary
int b; // 4 bytes
short c; // 2 bytes
char d; // 1 byte
char _pad1[1]; // padding to make sizeof(x_) multiple of 4
}

Both declarations return sizeof(struct x_) as 12 bytes.


The second declaration includes two padding elements:
char _pad0[3] to align the int b member on a four-byte boundary
char _pad1[1] to align the array elements of the structure struct _x bar[3];
The padding aligns the elements of bar[3] in a way that allows natural access.
The following code example shows the bar[3] array layout:

adr
offset element
------ -------
0x0000 char a; // bar[0]
0x0001 char pad0[3];
0x0004 int b;
0x0008 short c;
0x000a char d;
0x000b char _pad1[1];

0x000c char a; // bar[1]


0x000d char _pad0[3];
0x0010 int b;
0x0014 short c;
0x0016 char d;
0x0017 char _pad1[1];

0x0018 char a; // bar[2]


0x0019 char _pad0[3];
0x001c int b;
0x0020 short c;
0x0022 char d;
0x0023 char _pad1[1];

See Also
Reference
__unaligned keyword
Concepts
Working with Packing Structures
Smart Device Development

Avoiding Alignment Errors


All data types are either primitive types, or complex types that consist of arrays, structures, or unions of simpler types.
Alignment of primitive types
In general, alignment errors can be avoided by following these rules:
Do not enable structure packing.
Do not access a small-aligned address by using a recast pointer of larger alignment.
For example, treating the address of a char data type as a pointer to a long can cause an alignment error because this might
mean executing a four-byte move from an address that is not a multiple of four.
The following example illustrates this style of coding:

char a[10];
char *p = &a[1];
long l = *(long *)p; // ERROR!; Attempt to move a long from
// the address of a char.

Accessing a large-aligned address


Accessing a large-aligned address with a recast pointer of smaller alignment is safe. For example, you could use a char * cast
to access the first byte, or any byte, of a long variable.
If you need to pack structures or move data to unaligned addresses, use the __unaligned keyword.
This keyword cannot resolve alignment problems of pre-existing classes such as in inherited code, or in the Microsoft
Foundation Class Library.
You might need to use structure packing in programs that use large arrays of structures, or to read a pre-existing data format.
In such cases, you can still use packed structures if you also carefully unpack members of a packed structure before using data
in the program. This technique might involve copying the data in a structure member-by-member, or element-by-element, or
field-by-field, into a temporary location that is correctly aligned.
Syntactically, __unaligned is a type qualifier like const and volatile; it controls the meaning of what the pointer points to.
__unaligned has meaning only when used in a pointer declaration.
The following code example shows the use of __unaligned pointer declarations:

int __unaligned *p1; // p1 is a pointer to unaligned int


struct {int i;} __unaligned *p2; // p2 is a pointer to unaligned struct

The following code example illustrates the correct and incorrect use of __unaligned and #pragma pack in conjunction with
integer operations. In the first section, a fault is generated because the __unaligned qualifier is not used, whereas in the
second section, the __unaligned qualifier is used correctly.

#pragma pack (1)


struct s {
char c; // offset 0
int i; // offset 1!
} ss;
#pragma pack ()

void f_improper(int *p)


{
*p = 23; // generates a fault
}
void g_proper(int __unaligned *p) // OK
{
*p = 42;
}

void main ()
{
f_improper(&ss.i);
g_proper(&ss.i);
}

The output from this example appears in the following machine code example. In the output, function f_improper shows the
code generated by the improper handling of unaligned data, and function g_proper shows the extra code generated when
__unaligned is used.
In function g_proper, more than double the number of instructions are generated to handle the unaligned data, but an
alignment fault cannot occur.

f_improper::
mov r3, #0x17
str r0, [r0] // This instruction gets an alignment fault.
mov pc, lr
g_proper::
mov r3, #0x2A
strb r3, [r0] // Four individual bytes are stored,
mov r3, #0 // avoiding an alignment fault.
strb r3, [r0, #1]
strb r3, [r0, #2]
strb r3, [r0, #2]
mov pc, lr

Because there is a performance penalty for accessing data through an __unaligned pointer, use the __unaligned keyword
only when needed.
To guarantee that there are no alignment errors, the compiler must access the de-referenced data as a series of smaller pieces.
If the data is already aligned, this technique for accessing data is not necessary.
Alignment of Complex Types
The following list summarizes the rules for alignment of complex types:
The alignment of an array is the same as the alignment of the base type.
The alignment of a structure or object is the maximum of the alignment factors of all members of the structure. Further,
as long as structure packing is turned off, the compiler pads the structure so each member is placed at the next available
properly aligned address for that member.
The alignment of a union is also the maximum of the alignment factors of all members. Each member's address is that of the
union itself, so there is no padding.
See Also
Reference
__unaligned keyword
Concepts
Working with Packing Structures
Smart Device Development

Working with Packing Structures


Problems can occur when a structure requires more bytes than the programmer intended, especially when space requirements
are paramount.
Structure Packing and Alignment
Structure packing interacts with compiler alignment behavior as follows.
If the packsize is set equal to or greater than the default alignment, the packsize is ignored.
If the packsize is set smaller than the default alignment, the compiler aligns according to the packsize value.
Thus, if the packsize is set to four, data types having a size of four, eight, or 16 bytes are aligned on addresses that are
multiples of four. However, there is no guarantee that data types eight bytes in size (64 bits) are aligned on addresses that are
a multiple of eight. The packsize has no effect on data types outside of a structure.
In addition, packing affects the alignment of the entire packed structure. For example, in a structure declared under #pragma
pack(1), the alignment of all members are forced to one, regardless of whether they would have been naturally aligned even
without packing.
The following techniques set a packsize, in bytes:
The command-line option /Zp (Struct Member Alignment) sets the packsize to n, in which n can be 1, 2, 4, 8, or 16,
and in which 8 is the default.
The compiler directive #pragma pack([n]) sets the packsize to n, in which n can be 1, 2, 4, 8, or 16. If n is not specified,
#pragma pack resets the packsize to its value at the beginning of compilation: either the value specified by /Zp (Struct
Member Alignment), or the default, which is 8 on most platforms.
The pragma applies only from the point at which it occurs in the source. For example, the /Zp1 option sets the packsize
to 1, which causes the compiler to use no padding within structures. To avoid this problem, turn off structure packing or
use the __unaligned keyword when accessing unaligned members of such structures through pointers.
Guidelines for packing structures
The following list shows possible solutions to the structure issue.
Reordering structure members
If space requirements are critical, reorder the members of the structure so the same-sized elements are next to each
other and pack tightly. Usually, you start with the largest members and work your way down to the smallest ones.
Note that reordering a structure assumes that the user has full control of the data structure, but the user might not have
the freedom to rearrange the members. For example, the data structure might represent the layout of fields in a file on
disk.
Consider the following code example:
struct x_
{
char a; // 1 byte
int b; // 4 bytes
short c; // 2 bytes
char d; // 1 byte
} MyStruct;

If you reorganize the members of this structure, as shown in the following code example, the reorganized structure aligns
all members on natural boundaries, and the size of the structure is eight bytes instead of 12.
struct x_
{
int b; // 4 bytes
short c; // 2 bytes
char d; // 1 byte
char a; // 1 byte
} MyStruct;
Padding the structure
A different kind of problem can arise when the structure size requires padding to make sure array elements have the
same alignment, but the user needs to ensure that there is no padding between the array elements. For example, the user
might need to restrict memory usage or read data from a fixed-format source.
If the structure requires padding, you can use the compiler directive #pragma pack. However, #pragma pack causes
elements of the structures to be unaligned, and it requires the use of the __unaligned keyword qualifier to generate the
code needed to access this data without causing alignment faults.
The following example code uses #pragma pack to tell the compiler that the pointer px points to data that is not
naturally aligned, and tells the compiler to generate the appropriate sequence of load, merge, and store operations to do
the assignment efficiently.
# pragma pack (1)
struct x_
{
char a; // 1 byte
int b; // 4 bytes
short c; // 2 bytes
} MyStruct;
# pragma pack ()

void bar()
{
struct x_ __unaligned *px = &MyStruct;
. . . .
px->b = 5;
}

The __unaligned keyword should only be used as a last resort, because the generated code is less efficient than accessing
naturally aligned data. However, the __unaligned keyword is clearly preferable to alignment faults.
If at all possible, arrange the members of a data structure to preserve alignment and minimize space at the same time.

See Also
Reference
__unaligned keyword
Smart Device Development

__unaligned keyword
The __unaligned keyword is a type modifier in pointer definitions. It indicates to the compiler that the data pointed to might
not be properly aligned on a correct address.
To be properly aligned, the address of an object must be a multiple of the size of the type. For example, two-byte objects must
be aligned on even addresses.
When data is accessed through a pointer declared __unaligned, the compiler generates the additional code necessary to load
or store, or read or write the data without causing alignment errors.
It is best to avoid using unaligned data, but in some cases the usage can be justified by the need to access packed structures
such as shared disk structures or I/O hardware.
Note: UNALIGNED is a Win32 macro that expands to __unaligned on hardware platforms that require it. UNALIGNED
expands to nothing on platforms that do not require __unaligned.
For portability, use UNALIGNED instead of the __unaligned keyword. When you use the UNALIGNED macro, include the
windef.h header, as in the following example:

#include <windef.h>
int UNALIGNED *p1; // p1 is a pointer to unaligned int
struct {int i;} UNALIGNED *p2; // p2 is a pointer to unaligned struct

See Also
Concepts
Working with Packing Structures
Smart Device Development

Exception Handling for Device Compilers


Exception handling works differently on RISC-based microprocessors (such ARM, SH-4, and MIPS) than on x86
microprocessors. Under many circumstances, the compiler hides the differences; however, the differences become critical
when your code contains assembly language segments.
In simplified terms, in an x86 environment, the data structures associated with exception handling are written onto the stack at
runtime. The OS looks at these structures to locate appropriate exception-handling routines.
In a RISC environment, many data structures associated with exception handling are calculated at compile time and are written
to the data sections of the module being built. RISC-based microprocessors support a table-based mechanism using
PDATA Structures to handle exception processing that depends on the context, the frame and stack pointers, and the program
counter. Because the compiler generates the code segments that set up the stack frame whose address limits are associated
with the function table entry, only code that the compiler handles can access the table entry automatically.
Therefore, in a RISC environment, you must write code that manages exception-related processing for any assembly code
functions you include.
In This Section
SEH in x86 Environments
Provides a brief description of how exception handling works in an x86 processor environment.
SEH in RISC Environments
Provides a brief description of how exception handling works in a RISC processor environment.
PDATA Structures
Provides reference information about data structures used in RISC exception handling.
Related Sections
ARM Prolog and Epilog
Provides guidelines and examples for creating prolog and epilog code sequences for ARM microprocessor compilers.
Renesas SH-4 Prolog and Epilog
Provides guidelines and examples for creating prolog and epilog code sequences for Renesas microprocessor compilers.
MIPS Prolog and Epilog
Provides guidelines and examples for creating prolog and epilog code sequences for MIPS microprocessor compilers.
Smart Device Development

SEH in x86 Environments


In simplified terms, data structures associated with exception handling in an x86 environment are written onto the stack at
runtime. The OS looks at these structures to locate approriate exception-handling routines.
Exception-handling structures
In an x86 environment, the FS register points to the current value of the Thread Information Block (TIB) structure. One element
in the TIB structure is a pointer to an EXCEPTION_RECORD structure, which in turn contains a pointer to an exception
handling callback function. Thus, each thread has its own exception callback function.
The x86 compiler builds exception-handling structures on the stack as it processes functions. The FS register always points to
the TIB, which in turn contains a pointer to an EXCEPTION_RECORD structure. The EXCEPTION_RECORD structure points to
the exception handler function.
EXCEPTION_RECORD structures form a linked list: the new EXCEPTION_RECORD structure contains a pointer to the previous
EXCEPTION_RECORD structure, and so on. On Intel-based machines, the head of the list is always pointed to by the first
DWORD in the thread information block, FS:[0] .
Unwinding
When an exception occurs, the system walks the list of EXCEPTION_RECORD structures until it finds a handler for the
exception. When a handler is found, the system walks the list again, up to the node that handles the exception. During this
second traversal, the system calls each handler function a second time with the exception flag set to EH_UNWINDING.
The API builds a dummy exception record structure containing the context and the exception callback function. After each
callback, the corresponding exception frame is removed and the API moves on to the next frame. The API stops unwinding
when it gets to the frame whose address was passed in as the first parameter.
After an exception is handled and all previous exception frames have been called to unwind, execution continues where the
handling callback function indicates.
The code where execution resumes expects that the stack and frame pointers, the ESP and EBP registers on Intel CPUs, are set
to their values within the stack frame that handled the exception.
Therefore, the handler that accepts an exception is responsible for setting the stack and frame pointers to values they had in
the stack frame that contains the SEH code that handled the exception.
See Also
Concepts
SEH in RISC Environments
Smart Device Development

SEH in RISC Environments


In a RISC environment, data structures associated with exception processing are calculated at compile time, and written to the
data sections of the module being built.
To locate appropriate handlers when an exception occurs in Win32 environments other than x86, the system first determines
the frames that reside on the callstack, along with their associated functions in code. Any function can have a handler
associated with it. If so, the system gives the handler associated with the function an opportunity to handle the exception.
As with x86, a RISC system invokes handlers in reverse order; that is, it first invokes the handler whose corresponding frames
were most recently pushed onto the stack.
To determine the frames on the stack, the system simulates the execution of a portion of each function's code in reverse. This
simulation creates a CPU context similar to the state the real CPU context held at the point of entry to that function.
This process of reverse execution is known as Virtual Unwinding, because the stack unwind is only being simulated, not
actually performed.
Code elements for unwinding
The portion of the code that is reversed is known as the Prolog of the function. It consists of instructions that modify the stack
pointer and set up the stack frame immediately upon entry to the function.
When a frame has been virtually unwound, the virtual context contains the stack pointer for the previous frame and the return
address for the current function. The return address is very near the place where control left the previous function, so it
corresponds to the program counter of the previous frame.
With each successive program counter and stack pointer, the unwind process can iterate until there are no frames left on the
stack.
To virtually unwind, the system needs a small amount of information about each function. This information is contained in data
structures called PDATA Structures.
A PDATA structure marks where a function begins and ends in the code stream, as well as the location of the function prolog.
Given a program counter associated with a specific stack frame, the Unwinder searches the table of PDATA for the entry
corresponding to the containing function. When found, the Unwinder can unwind the function frame.
The PDATA structure also locates an exception handling routine associated with the function, if one exists.
The compiler generates correct Prolog and Epilog sequences, and PDATA for functions that it compiles, but you must create
appropriate code and PDATA for functions you write in assembly language.
The prolog and epilog sequence must adhere to strict guidelines for Virtual Unwinding to work.
For details on acceptable prologs and epilogs, see the documentation for your target platform.
See Also
Reference
Prolog-Epilog Example
Concepts
Prolog
Virtual Unwinding
Other Resources
Prolog and Epilog
Smart Device Development

Prolog
A prolog has several immediately contiguous parts, with no intervening instructions.
Typically, a prolog segment contains separate sequences of instructions that perform the following tasks:
Allocate a stack frame.
Save incoming argument registers.
Set up the frame pointer, if one is to be established. The prolog copies the stack pointer to a designated register before
the initial register saves; then it uses this value to compute the value of the frame pointer.
Save the link register with return address.
Allocate space for compiler-generated temporaries, local variables, and an argument build area.
Indicate the end of the prolog code.
Be sure your prolog code is succinct and only performs the necessary operations.
See Also
Reference
Prolog-Epilog Example
Concepts
SEH in RISC Environments
Smart Device Development

Epilog
Although each procedure has only one prolog, a procedure can contain many epilogs if the procedure uses multiple exit points.
Each epilog is required to have certain specific parts. All parts are contiguous, with no intervening instructions.
Typically, an epilog segment contains separate sequences of instructions that perform the following tasks:
Restore the frame pointer register, if it was saved in the prolog
Restore nonvolatile registers, including the Program Counter and the stack
Restore the return address
Deallocate the local frame
Return to the calling function

See Also
Reference
Prolog-Epilog Example
Concepts
SEH in RISC Environments
Smart Device Development

Prolog-Epilog Example
The following code example allocates a stack frame that requires 64 KB of memory for an SH-4 microprocessor. The code
segment for an ARM or MIPS microprocessor is similar, except for the names of registers used.
The prolog segment in this example saves the argument register to the incoming argument save areas. No separate frame
pointer is required. The segment then saves the return address, saves the permanent register, and allocates the stack frame. It
declares an exception handler.
The epilog segment removes the stack frame and recovers the return address.

EXCEPTION_HANDLER RoutineHandler
NESTED_ENTRY Function
// Step 1.
//
mov.l R4, @R15 // Save argument to incoming argument save area.
mov.l R8, @-R15
sts.l PR, @-R15
mov.l @(0x0000001C,pc),r1 // Load constant -65528.
add r1,r15 // Allocate stack frame.
mov.l R5, R8 // Save argument to register.

PROLOG_END

// Routine body

mov.l @(0x0000000C,pc),r1 // Load constant 65528.


add r1,r15 // Remove stack frame.
lds.l @R15+, PR // Recover return address.
rts
mov.l @R15+, R8 // Restore R8.

ENTRY_END Function
Smart Device Development

Virtual Unwinding
To reconstruct the context that existed on entry to a routine, SEH for RISC processors uses a process called Virtual Unwinding
to emulate a small subset of instructions in prolog and epilog code.
Virtual unwinding provides a syntactically efficient way of transferring control from the kernel exception handler to user-mode
code.
In virtual unwinding, the kernel traverses the call stack to find an appropriate exception handler.
Starting with a CPU context record and an instruction address, the unwinding process interprets instructions in the prolog or
epilog to reconstruct the context, as it existed before the function call.
Code elements for unwinding
The Virtual Unwinder uses a PDATA Structures to determine the procedure start, the procedure end, and the prolog end. The
PDATA structure can also contain a pointer to an exception handler.
The subset of prolog and epilog code that the Virtual Unwinder emulates includes the following:
Adding or subtracting a value from a register
Loading or storing a register on the stack frame
Loading integer constants into registers
Moving between registers
The Virtual Unwinder ignores other instructions found in the prolog or epilog sequences.
Virtual Unwinder process
The following list shows the steps the Virtual Unwinder performs:
1. Search the prolog for an instruction that saves the frame pointer, the stack pointer, or the link register.
If the instruction is present, the instruction saves all permanent registers the Virtual Unwinder must restore.
If the instruction is not present, the link register contains the return address, and the Virtual Unwinder updates only the
program counter.
2. Search for an instruction in the prolog that writes the frame pointer. The unwinding process restores all registers from
this address down, starting from the lowest numbered register to the highest numbered register.
3. Search for an instruction that writes the stack. If such an instruction exists, the unwinding process must reverse-execute
the stack link. The right operand to this subtract is the stack size, which is a constant immediate value.
4. If execution stops inside a prolog, the Virtual Unwinder determines if an instruction that saves the permanent registers
executed, and if a stack link executed.
If the function has not saved the permanent registers, the Virtual Unwinder copies the value in the link register to
the program counter register.
If the function saved the register values, and if no stack link executed, the Virtual Unwinder updates the
permanent registers from the stack pointer.
If execution stopped in a prolog with a linked stack, the Virtual Unwinder reverse-executes the prolog.
Note:
All functions that move the stack pointer must have an associated PDATA structure for SEH to work. These include any functi
on that allocates stack space, calls other functions, saves permanent registers, or has an exception handler. A leaf function (th
at is, a function that calls no other functions) that does not modify a permanent register does not need PDATA. In this case, th
e Virtual Unwinder updates the program counter from the link register and continues to the next frame.

See Also
Reference
Prolog-Epilog Example
PDATA Structures
Concepts
SEH in RISC Environments
Smart Device Development

PDATA Structures
ARM, MIPS, and SHx device compilers use PDATA structures to aid in stack walking at run-time. This structure aids in
debugging and exception processing.
The compilers associate one PDATA structure with each procedure.
The data structure is a table stored in a COFF .pdata section. The .pdata section contains an array of function table entries for
exception handling, and is pointed to by the exception table entry in the image data directory.
The MIPS calling standard supports an uncompressed PDATA format, _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY. In most
cases, MIPSII currently uses an uncompressed 20 bytes for each function for the _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY
entry.
Leaf functions that do not have associated exception-handling routines do not have an associated pdata entry.
The following table shows the function table entry format for MIPSII images.
Offset Size Field Description
0 4 Begin Address Virtual address of the corresponding function.

4 4 End Address Virtual address of the end of the function.

8 4 Exception Handler Pointer to the exception handler to be executed.

12 4 Handler Data Pointer to additional information to be passed to the handler.

16 4 Prolog End Address Virtual address of the end of the function prolog.

ARM and SH-4 Device compilers support a compressed PDATA structure, _IMAGE_CE_RUNTIME_FUNCTION_ENTRY.
The following table shows the COFF-specified function-table entry format used for the ARM and SH-4 hardware platforms.
Offset Size Field Description
0 4 Begin Address Virtual address of the corresponding function.

4 8 bits Prolog Length Number of instructions in the function's prolog.

4 22 bits Function Length Number of instructions in the function.

4 1 bit 32-bit Flag Set if the function is comprised of 32-bit instructions, cleared for a 16-bit function.

4 1 bit Exception Flag Set if an exception handler exists for the function.

If an exception handler exists or the function length is zero, an additional PDATA_EH structure precedes the function in the .text
section. The function uses PDATA_EH when the function has an associated exception handler or handler data.
In most cases, PDATA structure occupies only eight bytes per function. For functions that have an exception handler, the
PDATA_EHstructure requires an additional eight bytes.
The exception-handling data record and the prolog and function length record are guaranteed to be 4-byte aligned. This
implies that any function associated with one or more of these records is 4-byte aligned.
See Also
Concepts
Virtual Unwinding
Smart Device Development

_IMAGE_CE_RUNTIME_FUNCTION_ENTRY
This structure contains detailed information about runtime exception processing.
_IMAGE_CE_RUNTIME_FUNCTION_ENTRY is used only by ARM and Renesas microprocessor families. It does not apply to
MIPS microprocessors.

typedef struct _IMAGE_CE_RUNTIME_FUNCTION_ENTRY {


unsigned int FuncStart : 32;
unsigned int PrologLen : 8;
unsigned int FuncLen : 22;
unsigned int ThirtyTwoBit : 1;
unsigned int ExceptionFlag : 1;
} IMAGE_CE_RUNTIME_FUNCTION_ENTRY,
*PIMAGE_CE_RUNTIME_FUNCTION_ENTRY;

Parameters
FuncStart
Address of the first instruction in the function. It is the function's entry address.
PrologLen
Length of the prolog in instructions, based on the instruction size indicated in the ThirtyTwoBit flag. PrologLen is set to 1 for
ARM functions, and to 0 for THUMB and SH-4 functions.
FuncLen
Total function length in instructions; see PrologLen, above. A function with 200 ARM instructions would have a FuncLen of
200, or 800 bytes.
ThirtyTwoBit
Size of instructions in a function. ThirtyTwoBit can hold one of the following values: 1Represents ARM functions, each of
which consists of 32-bit instructions, or 4 bytes. 0Represents THUMB functions, each of which consists of 16-bit instructions,
or 2 bytes.
ExceptionFlag
Associated exception handler or handler data. When its value is 1, the PDATA_EH is present in the .text section. When the
ExceptionFlag is 0, no PDATA_EH is present.
Remarks
The IMAGE_CE_RUNTIME_FUNCTION_ENTRY data structure is also called as PDATA. A table containing these records is
stored in a section called .pdata. The .pdata section aids in debugging and exception processing.
If the ExceptionFlag is set, or if the FuncLen is set to 0, an additional PDATA_EH structure exists that precedes the function in the
.text section.
The data record containing this information appears in the .text section, immediately preceding the function, if and only if the
ExceptionFlag bit is set.
This record is used when the function has an associated exception handler or handler data.
See Also
Reference
PDATA Structures
PDATA_EH
Smart Device Development

_IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY
This structure contains detailed information about runtime exception processing.
This structure has an uncompressed 20-byte format.

typedef struct_IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY { ULONG BeginAddress; ULONG EndAddress;


PVOID ExceptionHandler; PVOID HandlerData; ULONG PrologEndAddress;} IMAGE_ALPHA_RUNTIME_F
UNCTION_ENTRY,*PIMAGE_ALPHA_RUNTIME_FUNCTIONG_ENTRY;

Parameters
BeginAddress
Address of the first instruction in the function. It is the function's entry address.
EndAddress

Address of the last instruction in the function. It is the function's end address.
ExceptionHandler
Address of the exception handler for the function.
HandlerData
Address of the exception handler data record for the function.
PrologEndAddress

Address of the last instruction in the prolog.


See Also
Reference
PDATA Structures
Smart Device Development

PDATA_EH
This structure holds detailed information about an associated exception handler function. This is an internal data structure used
in OS exception processing.

struct PDATA_EH { unsigned int* pHandler; unsigned int* pHandlerData;};

Parameters
pHandler
Address of the exception handler for the function.
pHandlerData
Address of the exception handler data record for the function.
See Also
Reference
PDATA Structures
_IMAGE_CE_RUNTIME_FUNCTION_ENTRY
Smart Device Development

Device Compiler Error Message


The following table describes unique error messages for device compilers.
Error Description
Compiler Error C2729 Indicates an intrinsic function not supported in Thumb mode.

Compiler Error C2759 Indicates an error in inline assembly.

Compiler Error C2822 Indicates premature exit from guarded section.

Compiler Error C2880 Indicates an attempt to create a namespace alias failed because the namespace already exis
ts.

Compiler Error C2887 Indicates too many arguments for a __swi intrinsic.

Compiler Warning (level 2) C4720 Indicates one of a variety of SH-specific issues.

Compiler Warning (level 1) C4721 Indicates an unknown intrinsic function.

Compiler Warning (level 1) C4732 Indicates an intrinsic function not supported in the target architecture.

Compiler Warning (Level 1) C4567 Indicates that the linker encountered incompatible object files from different versions of th
e compiler.
See Also
Other Resources
Compilers for Smart Devices
Smart Device Development

Compiler Error C2729


intrinsic not allowed in Thumb mode

This error indicates that the compiler attempted to compile an intrinsic function not supported in Thumb mode, such as
_prefetch.
Note that if source is compiled with the /GL (Whole Program Optimization) switch, this error will not be output until the
referenced object is linked.
Smart Device Development

Compiler Error C2759


in-line assembler reports: "various"

An error occurred in inline assembly code that prevented compilation.


Smart Device Development

Compiler Error C2822


local unwind is not supported on this platform

The implementation of Structured Exception Handling on this platform does not support a local unwind operation, which is
required when prematurely leaving either the guarded section or the termination handler of a try-finally statement. If you
need to leave the guarded section, use the __leave keyword. Leaving the termination handler prematurely can have undefined
behavior and should be avoided.
The following code demonstrates two ways this error message can be generated.

int g;

int main(void)
{
__try {
if (g) return g; // requires local unwind
g = 1;
} __finally {
if (g) return g; // undefined; requires local unwind
g = 2;
}

return 0;
}
Smart Device Development

Compiler Error C2880


__swi requires a valid constant as first argument (SWI number)

The _swi intrinsic function did not receive an integer constant as expected for the first argument. The integer constant must be
in the range [0 - 16777215] for ARM, or [0 - 255] for Thumb microprocessors.
Example

int test_intrinsic(int x)
{

return __swi(x, 12, 14, 13, 12); // error C2880


}
Smart Device Development

Compiler Error C2887


__swi cannot have more than five arguments (SWI number r0 - r3)

__swi intrinsic must have five or fewer arguments.


Example
#pragma intrinsic(__swi)
int test_intrinsic()
{
return __swi(10, 12, 14, 13, 15, 12);
// error cannot have more than 5 args
}
Smart Device Development

Compiler Warning (Level 2) C4720


in-line assembler reports: 'message'

This SH-specific warning applies to multiple situations that might occur for SH inline assembly.
This warning is not visible when compiling with the -GL Whole Program Optimization option.
In the following example code, the compiler issues this warning to indicate a branch in a delay slot.
Example
/* C4720.c */
#ifdef __cplusplus
extern "C" void __asm(const char *, ...);
#else
extern void __asm(const char *,...);
#endif

int main()
{
int ValA = 10;
int ValB = 0;
__asm(
"mov.l @r4, r2\n"
"mov #0, r6\n"
"add r2, r6\n"
"bf/s lala\n"
"bf la\n"
"lala: add r2, r6\n"
"la: mov.l r6, @r5\n",
&ValA,&ValB); /* delay slot branch */
return 0;
}
Smart Device Development

Compiler Warning (Level 1) C4721


'function' : not available as an intrinsic

The compiler encountered an unknown intrinsic function. The use of #pragma intrinsic('function') will be ignored.
Smart Device Development

Compiler Warning (Level 1) C4732


instrinsic ' %s' is not supported in this architecture

The compiler encountered an intrinsic function that is not supported in the target architecture.
The __trap intrinsic is not supported under the MIPS 16 ISA. As a result, the following code example causes the compiler to
generate compiler warning C4732.
Example
#include <cmnintrin.h>

int main()
{
int returnCode = 1;
#if (_INTRINSIC_IS_SUPPORTED(__trap))
__trap(1);
#else
return 1;
#endif
return 0;
}
Smart Device Development

Compiler Warning (Level 1) C4567

'function' : behavior change due to parameter 'parameter': calling convention incompatible


with previous compiler versions

This warning indicates that the compiler encountered code that may not execute correctly if it is linked with code compiled by
an earlier compiler version.
This warning is specific to the C++ compiler for the ARM(R) Architecture. Versions of the compiler older than 14.00 use a
different calling convention than newer compilers when passing certain function parameters by value. The two calling
conventions are not compatible, and linking object files from an older compiler with newer object files can result in
unpredictable behavior and crashes if such a parameter is passed by value between the old and new object files.
An object of class, struct, or union type with a user-defined copy constructor is subject to this calling convention change if it is
passed by value. Objects passed by reference are not affected.
If you are linking to object files from older compilers, use this warning to find places in your code where the calling convention
has changed. If objects with user-defined copy constructors are passed by value between old and new object files, the old
object files must be recompiled with a compiler version 14.00 or later.
This warning is off by default.
Example
// The following sample generates C4567:

// C4567.cpp
// (optional) compile with: -w14567
#pragma warning(default : 4567)
#pragma inline_depth(0) // disable function inlining

#include <cstdio>

struct S {
S () { self = this; }
S (S& that) { self = this; }
~S() { // older compilers will fail this test
if ( self != this ) {
printf ("s passed incorrectly\n");
}
}
S* self;
};

void func ( S s ) // C4567 at definition


{
// s destructor is called here
}

int main()
{
S s;
func (s); // C4567 at call site
return 0;
}

See Also
Other Resources
Differences Between Desktop and Device Compilers
Smart Device Development

ARM Family Processors


The ARM microprocessor range provides solutions for the following applications:
Open hardware platforms running complex operating systems with wireless, consumer, and imaging applications.
Embedded, real-time systems for mass storage, automotive, industrial, and networking applications.
Secure applications, including smart cards and Single Inline Memory (SIM) modules.
The ARM Instruction Set Architecture (ISA) includes several technology extensions, such as THUMB technology, that enable
optimum functionality and performance.
In This Section
Intrinsic Functions for ARM Microprocessors
Provides tables and detailed reference information about intrinsic functions supported by key ARM microprocessor families.
ARM Compiler Options
Provides reference information about compiler options specific to ARM microprocessors and compilers.
ARM Calling Sequence Specification
Provides information about ARM register and stack frame layout, ARM prologs and epilogs for SEH, and reference information
about the ARM assembler.
Related Sections
Intrinsic Functions for Device Compilers
Provides reference information about intrinsic functions supported by all device compilers.
RISC Processor Data Alignment
Provides guidelines for data alignment for RISC microprocessors.
SEH in RISC Environments
Describes the key differences between Structured Exception Handling in RISC environments.
Smart Device Development

Intrinsic Functions for ARM Microprocessors


The ARM device compiler supports a set of intrinsic functions that are defined for specific ARM microprocessors.
Different sets of intrinsic functions are available for the ARM10, the ARM DSP, the ARM XSCALE, and the Intel PXA270
architectures.
The ARM compiler uses the /QR compiler option to determine which set of intrinsic functions to chose for a particular
compilation. For example, the /QRxscale enables the XScale MAC intrinsic functions. For more information about the /QR flag,
see ARM Compiler Options.
If appropriate target architecture is not defined, some intrinsic functions, such as XScale MAC functions, will fail.
To guard an intrinsic function, or to ensure that an intrinsic function is called only if a specific target architecture is defined, use
the system management function IsProcessorFeaturePresent.
In This Section
ARM10 Intrinsic Functions
ARM DSP-enhanced Intrinsic Functions
ARM XSCALE Intrinsic Functions
WMMX Intrinsic Functions
Smart Device Development

ARM10 Intrinsic Functions


The following ARM10 instructions are supported through intrinsic functions.
Instruction Description
CLZ Counts leading zeroes before first 1-bit.
The common intrinsic _CountLeadingZeros, _CountLeadingZeros64access
es the CLZ instruction.

BKPT Creates soft breakpoint.


The common intrinsic __trap accesses the BKPT instruction.

_swi Generates a call to the OS using the SWI software interrupt instruction.

__emit Inserts a specified instruction into the instruction stream.

_MoveFromCoProcessor, _MoveFromCoProcessor2 Reads data from the ARM coprocessor.

_MoveToCoProcessor, MoveToCoprocessor2 Writes data to the ARM coprocessor.


See Also
Reference
ARM Compiler Options
Smart Device Development

CLZ
This ARM10 instruction counts the number of binary zero bits before the first binary one bit in a register value. The common
_CountLeadingZeros, _CountLeadingZeros64intrinsic supports CLZ.

unsigned cdecl _CountLeadingZeros(


long Arg1
);

Parameters
Arg1
[in] The value for which the leading zero bits should be determined.
Return Values
Number of binary zero bits.
Remarks
To generate the CLZ instruction for the _CountLeadingZeros intrinsic, use the -QRarch5 or -QRarch5T flag.
If you are compiling on an ARM4 microprocessor, the compiler generates a call to a library name, or to some other sequence
of ARM 4 code.
Requirements
Routine Required header Architecture
CLZ <armintr.h> ARM
See Also
Reference
ARM10 Intrinsic Functions
/QRArch - Specify Target Architecture
Other Resources
Common Intrinsic Function Reference
Smart Device Development

BKPT
This ARM10 instruction causes a software breakpoint to occur. The common __trap intrinsic supports BKPT.

int __trap(
int Arg1
);

Parameters
Arg1
[in] Address of breakpointed instruction.
Return Values
None.
Requirements
Routine Required header Architecture
BKPT <armintr.h> ARM
See Also
Reference
ARM10 Intrinsic Functions
Other Resources
Common Intrinsic Function Reference
Smart Device Development

__emit
This intrinsic function inserts a specified instruction into the stream of instructions output by the compiler.

void __emit(
const unsigned __int32 opcode
);

Parameters
opcode
Instruction word to be inserted.
Return Values
None
Remarks
The value of opcode must be a constant expression known at compile time.
The compiler makes no attempt to interpret the contents of opcode and does not guarantee a CPU or memory state before the
inserted instruction is executed.
The compiler assumes that the CPU and memory states are unchanged after the inserted instruction is executed. Therefore,
instructions that do change state can have a detrimental impact on normal code generated by the compiler.
For this reason, use __emit only to insert instructions that affect a CPU state that the compiler does not normally process, such
as coprocessor state, or to implement functions declared with __declspec(naked).
When generating ARM instructions, the size of an instruction word is 32 bits. When generating Thumb instructions, as when
/QRthumb is specified, the size of an instruction word is 16 bits and the most significant 16 bits of opcode are ignored.
Requirements
Routine Required header Architecture
__emit <armintr.h> ARM
See Also
Reference
ARM10 Intrinsic Functions
/QRthumb
Smart Device Development

_MoveFromCoProcessor, _MoveFromCoProcessor2
These intrinsic functions read data from ARM coprocessors via the coprocessor data transfer instructions.

int _MoveFromCoprocessor(
unsigned int coproc,
unsigned int opcode1,
unsigned int crn,
unsigned int crm,
unsigned int opcode2
);

int _MoveFromCoprocessor2(
unsigned int coproc,
unsigned int opcode1,
unsigned int crn,
unsigned int crm,
unsigned int opcode2
);

Parameters
coproc
Coprocessor number in the range 0 to 15.
opcode1
Coprocessor-specific opcode in the range 0 to 7.
crn
Coprocessor register number in the range 0 to 15, which specifies the first operand to the instruction.
crm
Coprocessor register number in the range 0 to 15, which specifies an additional source or destination operand.
opcode2
Additional coprocessor-specific opcode in the range 0 to 7.
Return Values
The value read from the coprocessor.
Remarks
The values of all five parameters to this intrinsic must be constant expressions known at compile time.
_MoveFromCoprocessor uses the MRC instruction; _MoveFromCoprocessor2 uses MRC2. The parameters correspond to
bitfields encoded directly into the instruction word. The interpretation of the parameters is coprocessor-dependent. For more
information, see the manual for the coprocessor in question.
These intrinsics are not available when generating Thumb instructions, such as when /QRthumb is specified.
Requirements
Routine Required header Architecture
_MoveFromCoprocessor <armintr.h> ARM
Routine Required header Architecture
_MoveFromCoprocessor2 <armintr.h> ARM
See Also
Reference
ARM10 Intrinsic Functions
/QRthumb
Smart Device Development

_MoveToCoProcessor, MoveToCoprocessor2
These intrinsic functions write data to ARM coprocessors via the coprocessor data transfer instructions.

Void _MoveToCoprocessor(
unsigned int value,
unsigned int coproc,
unsigned int opcode1,
unsigned int crn,
unsigned int crm,
unsigned int opcode2
);

Void _MoveToCoprocessor2(
unsigned int value,
unsigned int coproc,
unsigned int opcode1,
unsigned int crn,
unsigned int crm,
unsigned int opcode2
);

Parameters
value
Value to be written to the coprocessor.
coproc
Coprocessor number in the range 0 to 15.
opcode1

Coprocessor-specific opcode in the range 0 to 7.


crn
Coprocessor register number in the range 0 to 15, which specifies the first operand to the instruction.
crm
Coprocessor register number in the range 0 to 15, which specifies and additional source or destination operand.
opcode2
Additional coprocessor-specific opcode in the range 0 to 7.
Return Values
None
Remarks
The values of coproc, opcode1, crn, crm, and opcode2 must be constant expressions known at compile time.
_MoveToCoprocessor uses the MCR instruction; _MoveToCoprocessor2 uses MCR2.
The parameters correspond to bitfields encoded directly into the instruction word. The interpretation of the parameters is
coprocessor-dependent. For more information, see the manual for the coprocessor in question.
These intrinsics are not available when generating Thumb instructions, such as when /QRthumb is specified.
Requirements
Routine Required header Architecture
_MoveToCoprocessor , <armintr.h> ARM
_MoveToCoprocessor2
See Also
Reference
ARM10 Intrinsic Functions
/QRthumb
Smart Device Development

_swi
This intrinsic function generates a call to an OS routine using the software interrupt instruction SWI.

unsigned int __swi(


unsigned swi_number,
arg2,
arg3,
arg4
);

Parameters
swi_number
Software Interrupt number
arg2-arg4
Additional arguments for passing
Return Values
The _swi intrinsic function returns the value left in register R0 when control is returned to the instruction following the SWI.
Remarks
The _swi intrinsic applies to the ARM or the Thumb instruction set, depending on whether the compiler is generating 32-bit or
16-bit code.
The first parameter, swi_number, is encoded directly into the immediate field of the instruction. It must be an integer constant
in the range [0 - 16777215] for ARM or [0 - 255] for Thumb.
If additional arguments are included, the function passes the values according to the standard ARM calling convention with
one exception: no arguments or parts of arguments may be passed in memory, that is, on the stack.
Therefore, all arguments must be able to be passed using only registers R0, R1, R2, and R3.
Requirements
Routine Required header Architecture
_swi <armintr.h> ARM
See Also
Reference
/QRArch - Specify Target Architecture
/QRthumb
Smart Device Development

ARM DSP-enhanced Intrinsic Functions


All ARM DSP instructions are supported as intrinsic functions. To use the ARM DSP intrinsics, include the armintr.h header.
The following ARM DSP Instructions have intrinsic functions defined for them.
Function Corresponding ARM DSP Description
instruction
_SmulAddLo_SW_SL SMLAxy A signed-integer multiply and accumulate operation: 16x16-bit multiply f
ollowed by a 32-bit add.
_SmulAddHi_SW_SL
_SmulAddHiLo_SW_SL
_SmulAddLoHi_SW_SL

_SmulAddWLo_SW_SL SMLAWy A 32x16-bit multiply operation, followed by a 32-bit add of the upper 32
bits of the 48 bit product.
_SmulAddWHi_SW_SL

_SmulAddHi_SW_SQ SMLALxy A 16x16-bit multiply operation, followed by a 64-bit add of the product,
with a 64-bit integer.
_SmulAddLo_SW_SQ
_SmulAddHiLo_SW_SQ
_SmulAddLoHi_SW_SQ

_SmulLo_SW_SL SMULxy A signed-integer 16x16-bit multiply operation.


_SmulHi_SW_SL
_SmulHiLo_SW_SL
_SmulLoHi_SW_SL

_SmulWLo_SW_SL SMULWy A signed-integer 32x16-bit multiply operation, returning the upper 32-bit
s.
_SmulWHi_SW_SL

_AddSatInt QADD A saturating add instruction.

_DSubSatInt QSUB A saturating subtract instruction.

_DAddSatInt QDADD An instruction to double an integer and saturate, and then add to a secon
d integer and saturate.

_DSubSatInt QDSUB An instruction to double an integer and saturate, and then subtract from
a second integer and saturate.

_ReadCoProcessor MRRC, An operation to transfer values from a coprocessor to two ARM registers.
_WriteCoProcessor MCRR
See Also
Reference
ARM XSCALE Intrinsic Functions
Other Resources
Intrinsic Functions for Device Compilers
Smart Device Development

_SmulAddLo_SW_SL
This ARM DSP-enhanced, signed-integer multiply-accumulate operation multiplies the bottom half of register Rm and the
bottom half of register Rs, producing a 32-bit product. The operation then performs a 32-bit accumulation with Rn.

int _SmulAddLo_SW_SL(
int Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1
Contents of Rn, the value added to the product of Arg2 and Arg3.
Arg2
[in] The contents of Rm, the first term multiplied.
Arg3
[in] The contents of Rs, the second term multiplied.
Return Values
The result of multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlabb assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddLo_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddHi_SW_SL
_SmulAddHiLo_SW_SL
_SmulAddLoHi_SW_SL
Smart Device Development

_SmulAddHi_SW_SL
This ARM DSP-enhanced, signed-integer multiply-accumulate operation multiplies the top half of register Rm and the top half
of register Rs, producing a 32-bit product. The operation then performs a 32-bit accumulation with Rn.

int _SmulAddHi_SW_SL(
int Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1
The contents of Rn, the value added to the product of Arg2 and Arg3.
Arg2
[in] The contents of Rm, the first term multiplied.
Arg3
[in] The contents of Rs, the second term multiplied.
Return Values
The result of the multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlatt assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddHi_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddLo_SW_SL
_SmulAddHiLo_SW_SL
_SmulAddLoHi_SW_SL
Smart Device Development

_SmulAddHiLo_SW_SL
This ARM DSP-enhanced, signed-integer multiply-accumulate operation multiplies the top half of register Rm and the bottom
half of register Rs to produce a 32-bit product. The operation then performs a 32-bit accumulation with Rn.

int _SmulAddHiLo_SW_SL(
int Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1
The contents of Rn, the value added to the product of Arg2 and Arg3.
Arg2
[in] The contents of Rm, the first term multiplied.
Arg3
[in] The contents of Rs, the second term multiplied.
Return Values
The result of multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlatb assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddHiLo_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddHi_SW_SL
_SmulAddLo_SW_SL
_SmulAddLoHi_SW_SL
Smart Device Development

_SmulAddLoHi_SW_SL
This ARM DSP-enhanced, signed-integer multiply-accumulate operation multiplies the bottom half of register Rm and the top
half of register Rs, producing a 32-bit product. The operation then performs a 32-bit accumulation with Rn.

int _SmulAddLoHi_SW_SL(
int Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1
The contents of Rn, the value added to the product of Arg2 and Arg3.
Arg2
[in] The contents of Rm, the first term multiplied.
Arg3
[in] The contents of Rs, the second term multiplied.
Return Values
The integer result of multiplication.
Remarks
The compiler translates this instruction into the smlabt assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddLoHi_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddLo_SW_SL
_SmulAddHiLo_SW_SL
_SmulAddHi_SW_SL
Smart Device Development

_SmulAddWLo_SW_SL
This ARM DSP-enhanced, signed integer multiply-accumulate operation multiplies Rm with the bottom 16 bits of Rs; then it
accumulates in Rn. The operation adds the upper 32 bits of the 48-bit product to the 32-bit Rn.

int _SmulAddWLo_SW_SL(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The contents of Rm, the first term in the product.
Arg2
[in] The contents of Rs, the second term in the product.
Return Values
The integer result of the multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlawb assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddW_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddWHi_SW_SL
Smart Device Development

_SmulAddWHi_SW_SL
This ARM DSP-enhanced, signed integer multiply-accumulate operation multiplies Rm with the top 16 bits of Rs then
accumulates in Rn. The operation adds the upper 32 bits of the 48-bit product to the 32-bit Rn.

int _SmulAddWHi_SW_SL(
int Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1
[in] The contents of Rn, the value added to the product of Arg2 and Arg3.
Arg2
[in] The contents of Rm, the first term in the product.
Arg3
[in] The contents of Rs, the second term in the product.
Return Values
The integer result of the multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlawt assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddWHi_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddWLo_SW_SL
Smart Device Development

_SmulAddHi_SW_SQ
This ARM DSP-enhanced, signed integer multiply-accumulate operation first performs a multiply on two 16-bit source
operands from the top half of register Rm and the top half of Rs. This is followed with a 64 bit accumulate with the 32-bit
registers RdLo and RdHi.

__int64 _SmulAddHi_SW_SQ(
__int64 Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1

Pointers to a 64-bit accumulate that contains RdHi and RdLo.


Arg2
[in] The contents of Rm, the first term in the product.
Arg3
[in] The contents of Rs, the second term in the product.
Return Values
The long integer result of the multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlaltt assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddHi_SW_SQ <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddLo_SW_SQ
_SmulAddHiLo_SW_SQ
_SmulAddLoHi_SW_SQ
Smart Device Development

_SmulAddLo_SW_SQ
This ARM DSP-enhanced, signed integer multiply-accumulate operation first performs a multiply on two 16-bit source
operands from the bottom half of register Rm and the bottom half of Rs. This is followed with a 64 bit accumulate with the 32-
bit registers RdLo and RdHi.

__int64 _SmulAddLo_SW_SQ(
__int64 Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1

A pointer to a 64-bit variable used to accumulate the contents of RdHi and RdLo.
Arg2
[in] The contents of Rm, the first term in the product.
Arg3
[in] The contents of Rs, the second term in the product.
Return Values
The result of multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlalbb assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddLo_SW_SQ <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddHi_SW_SQ
_SmulAddHiLo_SW_SQ
_SmulAddLoHi_SW_SQ
Smart Device Development

_SmulAddHiLo_SW_SQ
This ARM DSP-enhanced, signed integer multiply-accumulate operation multiplies the top half of register Rm and the bottom
half of Rs. This is followed with a 64 bit accumulate with the 32-bit registers RdLo and RdHi.

__int64 _SmulAddHiLo_SW_SQ(
__int64 Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1
Pointer to a 64-bit variable used to accumulate the contents of RdHi and RdLo.
Arg2
[in] The contents of Rm, the first term in the product.
Arg3
[in] The contents of Rs, the second term in the product.
Return Values
The long integer result of multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlaltb assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddHiLo_SW_SQ <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddLo_SW_SQ
_SmulAddLoHi_SW_SQ
_SmulAddHi_SW_SQ
Smart Device Development

_SmulAddLoHi_SW_SQ
This ARM DSP-enhanced, signed integer multiply-accumulate operation multiplies the bottom half of register Rm and the top
half of Rs. This is followed with a 64 bit accumulate with the 32-bit registers RdLo and RdHi.

__int64 _SmulAddLoHi_SW_SQ(
__int64 Arg1,
int Arg2,
int Arg3
);

Parameters
Arg1
A pointer to a 64-bit variable used to accumulate the contents of RdHi and RdLo.
Arg2
[in] The contents of Rm, the first term in the product.
Arg3
[in] The contents of Rs, the second term in the product.
Return Values
The long integer result of the multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlalbt assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddLoHi_SW_SQ <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddLo_SW_SQ
_SmulAddHiLo_SW_SQ
_SmulAddHi_SW_SQ
Smart Device Development

_SmulHi_SW_SL
This ARM DSP-enhanced, signed integer multiply operation multiplies the top half of register Rm times the top half of register
Rs, producing a 32-bit result in Rd.

int _SmulHi_SW_SL(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The contents of Rm, the first term in the product.
Arg2
[in] The contents of Rs, the second term in the product.
Return Values
The integer result of the multiplication.
Remarks
The compiler translates this instruction into the smultt assembly instruction.
Requirements
Routine Required header Architecture
_SmulHi_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulLo_SW_SL
_SmulLoHi_SW_SL
_SmulHiLo_SW_SL
Smart Device Development

_SmulLo_SW_SL
This ARM DSP-enhanced, signed integer multiply operation multiplies the bottom half of register Rm times the bottom half of
register Rs, producing a 32-bit result in Rd.

int _SmulLo_SW_SL(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The contents of Rm, the first term in the product.
Arg2
[in] The contents of Rs, the second term in the product.
Return Values
The integer result of the multiplication.
Remarks
The compiler translates this instruction into the smulbb assembly instruction.
Requirements
Routine Required header Architecture
_SmulLo_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulLoHi_SW_SL
_SmulHiLo_SW_SL
_SmulHi_SW_SL
Smart Device Development

_SmulHiLo_SW_SL
This ARM DSP-enhanced, signed integer multiply operation multiplies the top half of register Rm times the bottom half of
register Rs, producing a 32-bit result in Rd.

int _SmulHiLo_SW_SL(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The contents of Rm, the first term in the product.
Arg2
[in] The contents of Rs, the second term in the product.
Return Values
The integer result of the multiplication.
Remarks
The compiler translates this instruction into the smultb assembly instruction.
Requirements
Routine Required header Architecture
_SmulHiLo_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulLo_SW_SL
_SmulLoHi_SW_SL
_SmulHi_SW_SL
Smart Device Development

_SmulLoHi_SW_SL
This ARM DSP-enhanced, signed integer multiply operation multiplies the bottom half of register Rm times the top half of
register Rs, producing a 32-bit result in Rd.

int _SmulLoHi_SW_SL(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The contents of Rm, the first term in the product.
Arg2
[in] The contents of Rs, the second term in the product.
Return Values
The integer result of the multiplication.
Remarks
The compiler translates this instruction into the smulbt assembly instruction.
Requirements
Routine Required header Architecture
_SmulLoHi_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulLo_SW_SL
_SmulHiLo_SW_SL
_SmulHi_SW_SL
Smart Device Development

_SmulWHi_SW_SL
This ARM DSP-enhanced, signed-integer multiplication operation performs a 32x16 bit multiply on the 32-bit operand in Rm
and the 16-bit source operand from the top half of register Rs. It then takes the upper 32 bits of the 48-bit product.

int _SmulWHi_SW_SL(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The first term in the product, the contents of Rm.
Arg2
[in] The second term in the product | the contents of Rs.
Return Values
The integer result of the multiplication.
Remarks
The compiler translates this instruction into the smulwt assembly instruction.
Requirements
Routine Required header Architecture
_SmulWHi_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulWLo_SW_SL
Smart Device Development

_SmulWLo_SW_SL
This ARM DSP-enhanced, signed-integer multiplication operation performs a 32x16 bit multiply on the 32-bit operand in Rm
and the 16-bit source operand from the bottom half of register Rs. It then takes the upper 32 bits of the 48-bit product.

int _SmulWLo_SW_SL(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The contents of Rm, the first term in the product.
Arg2
[in] The contents of Rs, the second term in the product.
Return Values
The integer result of the multiplication and accumulation.
Remarks
The compiler translates this instruction into the smlawb assembly instruction.
Requirements
Routine Required header Architecture
_SmulWLo_SW_SL <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SmulAddWHi_SW_SL
Smart Device Development

_AddSatInt
This ARM DSP-enhanced operation performs a saturating add instruction. It adds registers Rm and Rn, and places the result in
register Rd. It affects the sticky-overflow bit 'Q' if overflow occurs in the addition.

int _AddSatInt(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The contents of Rm, the first term in the sum.
Arg2
[in] The contents of Rn, the second term in the sum.
Return Values
The result of the binary arithmetic.
Remarks
The compiler translates this instruction into the qadd assembly instruction.
Requirements
Routine Required header Architecture
_AddSatInt <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_SubSatInt
Smart Device Development

_DAddSatInt
This operation calculates SAT(Rm + SAT(Rn*2)); that is, the operation first saturates the double of Rn, adds the result to Rm,
then saturates the sum.

int _DAddSatInt(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] This integer is added to the doubled Arg2. It is analogous to the value in Rm.
Arg2
[in] This integer is the term that is doubled. It is analogous to the value in Rn.
Return Values
The result of the binary arithmetic.
Remarks
The compiler translates this instruction into the qdadd assembly instruction.
Saturation can occur on the doubling operation, on the addition, or both. If saturation occurs on the doubling operation, but
not on the addition, the Q flag is set and the the final result is unsaturated.
Requirements
Routine Required header Architecture
_DAddSatInt <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_DSubSatInt
Smart Device Development

_SubSatInt
This ARM DSP-enhanced operation performs a saturating subtract instruction. It subtracts the value in Rn from the value in
Rm, and places the result in register Rd. This operation affects the sticky-overflow bit 'Q' if overflow occurs in the subtraction.

int _SubSatInt(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The first term in the difference, the contents of Rm.
Arg2
[in] The second term in the difference, the contents of Rn.
Return Values
The result of the binary arithmetic.
Remarks
The compiler translates this intrinsic into the qsub assembly instruction.
Requirements
Routine Required header Architecture
_SubSatInt <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_AddSatInt
Smart Device Development

_DSubSatInt
This operation doubles Rn and saturates, then subtracts the result from Rm and saturates. This operation affects the sticky-
overflow bit 'Q' if overflow occurs in the subtraction.

int _DSubSatInt(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] The doubled Arg2 is subtracted from this integer. It is the contents of the value in Rm.
Arg2
[in] This integer is doubled. It is the contents of the value in Rn.
Return Values
The value that results from the arithmetic performed.
Remarks
The compiler translates this instruction into the qdsub assembly instruction.
Requirements
Routine Required header Architecture
_DSubSatInt <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
_DAddSatInt
Smart Device Development

_ReadCoProcessor
This instruction causes the specified coprocessor registers to transfer values to two ARM registers.

__int64 _ReadCoProcessor(
int Arg1
);

Parameters
Arg1
[in] Coprocessor number, equivalent to cp_num.
Return Values
Value held in coprocessor register.
Remarks
The compiler translates this instruction into the MRRC assembly instruction for ARM DSP-enhanced processors, and into the
MRA assembly instruction for ARM XScale processors. MRA is disassembled as the MRCC instruction.
The XScale and the DSP-enhanced ARM microprocessors each implement this instruction in a different way:
For the ARM XScale implementation, this instruction does the following:
Moves 64 bits of data to ARM registers from Coprocessor registers
Moves the 40-bit accumulator value (acc0) into two registers
Moves bits [31:0] of the value in acc0 into the register RdLo
Sign-extends bits [39:32] of the value in acc0 to 32 bits and moves them into the register RdHi
For the ARM DSP-enhanced implementation, this instruction causes the coprocessor to transfer values to the two
general-purpose registers Rd and Rn.
Requirements
Routine Required header Architecture
_ReadCoProcessor <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
ARM XSCALE Intrinsic Functions
_WriteCoProcessor
Smart Device Development

_WriteCoProcessor
This instruction causes the specified ARM registers to transfer values to coprocessor registers.

void _WriteCoProcessor(
__int64 Arg1,
int Arg2
);

Parameters
Arg1
[in] Values to be written to coprocessor.
Arg2
[in] Coprocessor number. This should be zero.
Return Values
None.
Remarks
For the ARM XScale processor, the compiler translates this intrinsic into the MAR assembly instruction. MAR is disassembled
as the MCRR instruction.
For the ARM DSP-enhanced processor, the compiler translates this intrinsic into the MCRR assembly instruction.
The XScale and the DSP-enhanced ARM microprocessors implement this instruction in two slightly different ways.
ARM XScale implementation
This instruction moves the value in register RdLo to bits [31:0] of the 40-bit accumulator (acc0), and moves bits [7:0] of
the value in register RdHi into bits [39:32] of acc0.
ARM DSP-enhanced implementation
This instruction causes the two general-purpose registers Rd and Rn to transfer values to the coprocessor.
Requirements
Routine Required header Architecture
_WriteCoProcessor <armintr.h> ARM10, ARM-DSP
See Also
Reference
ARM XSCALE Intrinsic Functions
ARM DSP-enhanced Intrinsic Functions
_ReadCoProcessor
Smart Device Development

ARM XSCALE Intrinsic Functions


To increase the performance and precision of the audio processing algorithms, the Intel 80200(XScale) microprocessor
implementation of ARM adds a Digital Signal Processing (DSP) coprocessor.
This coprocessor contains a 40-bit accumulator and new instructions.
To implement the intrinsic functions for the ARM XScale instruction set, use the /QRxscale - Specify XSCALE Target compiler
option when compiling your code.
The following XScale instructions are implemented through intrinsic functions.
Function ARM XScale in Description
struction
_SmulAdd_SL_ACC MIA Multiplies the signed value in register Rs by the signed value in register Rm, and th
en adds the result to the 40-bit accumulator.

_SmulAddPack_2SW_ACC MIAPH Performs two 16x16 signed multiplications on packed half-word data and accumul
ates these to a single 40-bit accumulator.

_SmulAddLo_SW_ACC MIAxy Performs one 16-bit signed multiplication and accumulates the result to a single 4
0-bit accumulator.
_SmulAddHi_SW_ACC
_SmulAddLoHi_SW_ACC
_SmulAddHiLo_SW_ACC

_ReadCoProcessor MAR Moves 64 bits of data from ARM registers to coprocessor registers.

_WriteCoProcessor MRA Moves 64 bits of data to ARM registers from coprocessor registers.

_PreLoad PLD This instruction is used as a hint to the memory system that a memory access from
the specified address will occur shortly.
See Also
Reference
ARM10 Intrinsic Functions
ARM XSCALE Intrinsic Functions
Smart Device Development

_PreLoad
This instruction is a soft preload instruction; that is, this instruction indicates to the memory system that a memory access from
the specified address will occur shortly.

void _PreLoad(
unsigned long* addr
);

Parameters
addr
Location of memory access.
Return Values
None.
Remarks
The compiler translates this instruction into the PLD assembly instruction.
Requirements
Routine Required header Architecture
_PreLoad <armintr.h> ARM10, ARM-DSP, ARM XSCALE
See Also
Reference
ARM XSCALE Intrinsic Functions
Smart Device Development

_SmulAdd_SL_ACC
This operation multiplies the signed value in register Rs by the signed value in register Rm and then adds the result to the 40-
bit accumulator, acc0.

void _SmulAdd_SL_ACC(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] Values in Rs to be written to coprocessor.
Arg2
[in] Values in Rm to be written to coprocessor.
Return Values
None.
Remarks
The compiler translates this instruction into the mia assembly instruction.
Requirements
Routine Required header Architecture
_SmulAdd_SL_ACC <armintr.h> ARM10, ARM-DSP, ARM XSCALE
See Also
Reference
ARM XSCALE Intrinsic Functions
Smart Device Development

_SmulAddHi_SW_ACC
This instruction multiplies the top half of Rm and the top half of Rs and accumulates the result to a single 40-bit accumulator.
The instruction does not support unsigned multiplication, but interprets all arguments as signed data values.

void _SmulAddHi_SW_ACC(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] Value in Rm.
Arg2
[in] Value in Rs.
Return Values
None.
Remarks
The compiler translates this instruction into the miatt assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddHi_SW_ACC <armintr.h> ARM10, ARM-DSP, ARM XSCALE
See Also
Reference
ARM XSCALE Intrinsic Functions
_SmulAddLo_SW_ACC
_SmulAddHiLo_SW_ACC
_SmulAddLoHi_SW_ACC
Smart Device Development

_SmulAddHiLo_SW_ACC
This ARM XScale instruction multiplies the top half of Rm and the bottom half of Rs and accumulates the result to a single 40-
bit accumulator.
The instruction does not support unsigned multiplication, but interprets all arguments as signed data values.

void _SmulAddHiLo_SW_ACC(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] Value in Rm.
Arg2
[in] Value in Rs.
Return Values
None.
Remarks
The compiler translates this instruction into the miatb assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddHiLo_SW_ACC <armintr.h> ARM10, ARM-DSP, ARM XSCALE
See Also
Reference
ARM XSCALE Intrinsic Functions
_SmulAddLo_SW_ACC
_SmulAddHi_SW_ACC
_SmulAddLoHi_SW_ACC
Smart Device Development

_SmulAddLo_SW_ACC
This ARM XScale instruction multiplies the bottom half of Rm and the bottom half of Rs and accumulates the result to a single
40-bit accumulator.
The instruction does not support unsigned multiplication, but interprets all arguments as signed data values.

void _SmulAddLo_SW_ACC(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] Value in Rm.
Arg2
[in] Value in Rs.
Return Values
None.
Remarks
The compiler translates this instruction into the miabb assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddLo_SW_ACC <armintr.h> ARM10, ARM-DSP, ARM XSCALE
See Also
Reference
ARM XSCALE Intrinsic Functions
_SmulAddHi_SW_ACC
_SmulAddHiLo_SW_ACC
_SmulAddLoHi_SW_ACC
Smart Device Development

_SmulAddLoHi_SW_ACC
This ARM XScale instruction multiplies the bottom half of Rm and the top half of Rs and accumulates the result to a single 40-
bit accumulator.
The instruction does not support unsigned multiplication, but interprets all arguments as signed data values.

void _SmulAddLoHi_SW_ACC(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] Value in Rm.
Arg2
[in] Value in Rs.
Return Values
None.
Remarks
The compiler translates this instruction into the miabt assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddLoHi_SW_ACC <armintr.h> ARM10, ARM-DSP, ARM XSCALE
See Also
Reference
ARM DSP-enhanced Intrinsic Functions
ARM XSCALE Intrinsic Functions
_SmulAddLo_SW_ACC
_SmulAddHi_SW_ACC
_SmulAddHiLo_SW_ACC
Smart Device Development

_SmulAddPack_2SW_ACC
This ARM XScale instruction performs two 16x16 signed multiplication on packed half word data and accumulates these to a
single 40-bit accumulator.

void _SmulAddPack_2SW_ACC(
int Arg1,
int Arg2
);

Parameters
Arg1
[in] Value in Rm.
Arg2
[in] Value in Rs.
Return Values
None.
Remarks
First, this instruction multiplies the lower 16 bits of the value in Rm with the lower 16 bits of the value in Rs.
It then performs a multiplication with the upper 16 bits of Rs and Rm.
The instruction sign-extends both signed 32-bit products and then adds them to the value in the 40-bit accumulator (acc0).
The compiler translates this instruction into the miaph assembly instruction.
Requirements
Routine Required header Architecture
_SmulAddPack_2SW_ACC <armintr.h> ARM10, ARM-DSP, ARM XSCALE
See Also
Reference
ARM XSCALE Intrinsic Functions
Smart Device Development

WMMX Intrinsic Functions


The ARM-compliant Intel processors such as the PXA270 processor with Wireless MMX (WMMX) technology have instructions
to enable development of optimized multimedia applications. The instructions are implemented as co-processor instructions.
This technology uses the single-instruction, multiple-data (SIMD) technique. By processing data elements in parallel,
applications with media-rich bit streams can significantly improve performance by using SIMD instructions.
For complete details of the hardware instructions and intrinsic functions, data types, and registers can be found in the Intel
Wireless MMX Technology Developer Guide, number 251793-001
http://www.intel.com/design/pca/prodbref/251669_devguide.pdf.
In This Section
WMMX Technology Overview
Provides a brief overview of the WMMX technology
WMMX Arithmetic Intrinsics

Provides a reference table of packed arithmetic intrinsics.


WMMX Shift Intrinsics
Provides a reference table of shift intrinsics.
WMMX Logical Intrinsics
Provides a reference table of logical intrinsics.
WMMX Compare Intrinsics
Provides a reference table of compare intrinsics.
WMMX Pack/Unpack Intrinsics
Provides a reference table of pack/unpack intrinsics.
WMMX Set Intrinsics
Provides a reference table of set intrinsics.
WMMX General Support Intrinsics

Provides a reference table of general support intrinsics.


External Resources
Intel Wireless MMX Technology Developer Guide, number 251793-001
Smart Device Development

WMMX Technology Overview


Intel's wireless MMX (WMMX) technology is an extended implementation of the Intel architecture (IA) MMX instruction set. The
technology uses a single-instruction, multiple-data (SIMD) technique to speed up multimedia and communications software by
processing data elements in parallel.
The WMMX instruction set adds 57 opcodes and a 64-bit data type. In addition, there are sixteen 64-bit MMX technology
registers, each of which can be directly addressed using the register names wR0 to wR15.
Additional information and details about the MMX instructions, data types, and registers can be found in the Intel Wireless
MMX Technology Developer Guide, number 251793-001. This guide is available online at Intel hardware design.
New Registers
The WMMX technology intrinsic functions provide sixteen registers (wR0 to wR15) that are 64 bits long (0 to 63).
These new data registers enable the processing of data elements in parallel. Because each register can hold more than one data
element, the processor can process more than one data element simultaneously. This processing capability is also known as
SIMD processing. To enable SIMD processing with the C/C++ compiler, new data types are defined to exploit the expanded
size of the new registers.
Using intrinsic functions allows you to code with the syntax of C function calls and variables instead of with the assembly
language. For each computational and data manipulation instruction in the new extension sets, there is a corresponding C
intrinsic that directly implements that instruction. This frees you from managing registers and assembly programming. Further,
the compiler optimizes the instruction scheduling so that your executable runs faster.
__m64 data type
The __m64 data type is used to represent the contents of a WMMX register, which is the register used by the WMMX
technology intrinsic functions. The __m64 data type can hold eight 8-bit values, four 16-bit values, two 32-bit values, or one
64-bit value.
New Data Types Usage Guidelines
The new __m64 data type is not a basic ANSI C data type, and therefore you must observe the following usage restrictions:
Use __m64 only on the left side of an assignment as a return value or as a parameter. You cannot use it with other
arithmetic expressions (" + ", " ", and so on).
Use __m64 as objects in aggregates, such as unions, to access the byte elements and structures.
Use __m64 only with the WMMX intrinsic functions.
Data Alignment
Many of the WMMX intrinsic functions have data alignment requirements. If these intrinsic functions are used and data is not
appropriately aligned, the program will throw an exception that must be handled by the program; otherwise, the program will
fault. To support the use of WMMX intrinsic functions, the user must take a more active role to guarantee that alignment issues
are appropriately addressed.
For more information, see RISC Processor Data Alignment.
See Also
Other Resources
WMMX Intrinsic Functions
Smart Device Development

WMMX Arithmetic Intrinsics


The intrinsics listed in the following table perform packed arithmetic operations.
Intrinsic name Operation WMMX Instruction Argument and result values/bits
_mm_add_pi16 Adds WADDH 4/16, 4/16

_mm_add_pi32 Adds WADDW 2/32, 2/32

_mm_add_pi8 Adds WADDB 8/8, 8/8

_mm_adds_pi16 Adds, signed WADDHSS 4/16, 4/16

_mm_adds_pi32 Adds, signed WADDWSS 2/32, 2/32

_mm_adds_pi8 Adds, signed WADDBSS 8/8, 8/8

_mm_adds_pu16 Adds WADDHUS 4/16, 4/16

_mm_adds_pu32 Adds WADDWUS 2/32, 2/32

_mm_adds_pu8 Adds WADDBUS 8/8, 8/8

_mm_sub_pi16 Subtracts WSUBH 4/16, 4/16

_mm_sub_pi32 Subtracts WSUBW 2/32, 2/32

_mm_sub_pi8 Subtracts WSUBB 8/8, 8/8

_mm_subs_pi16 Subtracts, signed WSUBHSS 4/16, 4/16

_mm_subs_pi32 Subtracts, signed WSUBWSS 2/32, 2/32

_mm_subs_pi8 Subtracts, signed WSUBBSS 8/8, 8/8

_mm_subs_pu16 Subtracts WSUBHS 4/16, 4/16

_mm_subs_pu32 Subtracts WSUBWSS 2/32, 2/32

_mm_subs_pu8 Subtracts WSUBBUS 8/8, 8/8

_mm_madd_pi16 Multiplies WMADDS 4/16, 2/32

_mm_madd_pu16 Multiplies WMADDU 4/16, 2/32

_mm_mulhi_pi16 Multiplies, signed WMULSH 4/16, 4/16 (high)

_mm_mulhi_pu16 Multiplies, signed WMULUH 4/16, 4/16 (high)

_mm_mullo_pi16 Multiplies WMULSL/WMULUL 4/16, 4/16 (low)

_mm_mac_pi16 Multiply-accumulate, signed WMACS 4/16, 4/16


_mm_mac_pu16 Multiply-accumulate WMACU 4/16, 4/16

_mm_macz_pi16 Multiply-accumulate, signed WMACSZ 4/16, 4/16

_mm_macz_pu16 Multiply-accumulate WMACUZ 4/16, 4/16

_mm_acc_pu16 Accumulate WACCH 4/16, 1/16

_mm_acc_pu32 Accumulate WACCW 2/32. 2/32

_mm_acc_pu8 Accumulate WACCB 8/8, 1/8

_mm_mia_si64 Multiply-accumulate, signed TMIA 1/64

_mm_miabb_si64 Multiply-accumulate, signed TMIABB 1/64

_mm_miabt_si64 Multiply-accumulate, signed TMIABT 1/64

_mm_miaph_si64 Multiply-accumulate, signed TMIAPH 1/64

_mm_miatb_si64 Multiply-accumulate, signed TMIATB 1/64

_mm_miatt_si64 Multiply-accumulate, signed TMIATT 1/64


See Also
Other Resources
WMMX Intrinsic Functions
Smart Device Development

WMMX Shift Intrinsics


The intrinsics listed in the following table perform shift operations.
Intrinsic name Shift direction Shift type WMMX instruction
_mm_sll_pi16 Left Logical WSLLH

_mm_slli_pi16 Left Logical Composite

_mm_sll_pi32 Left Logical WSLLW

_mm_slli_pi32 Left Logical Composite

_mm_sll_si64 Left Logical WSLLD

_mm_slli_si64 Left Logical Composite

_mm_sra_pi16 Right Arithmetic WSRAH

_mm_srai_pi16 Right Arithmetic Composite

_mm_sra_pi32 Right Arithmetic WSRAW

_mm_srai_pi32 Right Arithmetic Composite

_mm_sra_pi64 Right Arithmetic WSRAD

_mm_srai_pi64 Right Arithmetic Composite

_mm_srl_pi16 Right Logical WSRLH

_mm_srli_pi16 Right Logical Composite

_mm_srl_pi32 Right Logical WSRLW

_mm_srli_pi32 Right Logical Composite

_mm_srl_si64 Right Logical WSRLD

_mm_srli_si64 Right Logical Composite

_mm_ror_pi16 Rotate right Logical WRORH

_mm_rori_pi16 Rotate right Logical WRORW

_mm_ror_pi32 Rotate right Logical WRORD

_mm_rori_pi32 Rotate right Logical Composite

_mm_ror_si64 Rotate right Logical Composite

_mm_rori_si64 Rotate right Logical Composite


See Also
Other Resources
WMMX Intrinsic Functions
Smart Device Development

WMMX Logical Intrinsics


The intrinsics listed in the following table perform logical operations.
Intrinsic name Operation WMMX instruction
_mm_and_si64 Bitwise AND WAND

_mm_andnot_si64 Logical NOT WANDN

_mm_or_si64 Bitwise OR WOR

_mm_xor_si64 Bitwise exclusive OR WXOR


See Also
Other Resources
WMMX Intrinsic Functions
Smart Device Development

WMMX Compare Intrinsics


The intrinsics listed in the following table perform comparisons.
Intrinsic name Comparison Number of elements Element bit size WMMX instruction
_mm_cmpeq_pi8 Equals 8 8 WCMPEQB

_mm_cmpeq_pi16 Equals 4 16 WCMPEQH

_mm_cmpeq_pi32 Equals 2 32 WCMPEQW

_mm_cmpgt_pi8 Greater than, signed 8 8 WCMPGTSB

_mm_cmpgt_pu8 Greater than, unsigned 8 8 WCMPGTUB

_mm_cmpgt_pi16 Greater than, signed 4 16 WCMPGTSH

_mm_cmpgt_pu16 Greater than, unsigned 4 16 WCMPGTUH

_mm_cmpgt_pi32 Greater than, signed 2 32 WCMPGTSW

_mm_cmpgt_pu32 Greater than, unsigned 2 32 WCMPGTUW


See Also
Other Resources
WMMX Intrinsic Functions
Smart Device Development

WMMX Pack/Unpack Intrinsics


The intrinsic functions listed in the following table provide pack and unpack operations.
Intrinsic name Operation WMMX Instruction
_mm_packs_pi16 Packs, signed and saturated WPACKHSS

_mm_packs_pi32 Packs, signed and saturated WPACKWSS

_mm_packs_pu16 Packs, saturated WPACKHUS

_mm_unpackhi_pi8 Interleaves WUNPCKIHB

_mm_unpackhi_pi16 Interleaves WUNPCKIHH

_mm_unpackhi_pi32 Interleaves WUNPCKIHW

_mm_unpacklo_pi8 Interleaves WUNPCKILB

_mm_unpacklo_pi16 Interleaves WUNPCKILH

_mm_unpacklo_pi32 Interleaves WUNPCKILW

_mm_packs_si64 Packs, signed and saturated WPACKDSS

_mm_packs_su64 Packs, saturated WPACKDUS

_mm_packs_pu32 Packs, saturated WPACKWUS

_mm_unpackeh_pi8 Interleaves, signed and extended WUNPCKEHSB

_mm_unpackeh_pi16 Interleaves, signed and extended WUNPCKEHSH

_mm_unpackeh_pi32 Interleaves, signed and extended WUNPCKEHSW

_mm_unpackeh_pu8 Interleaves, unsigned and extended WUNPCKEHUB

_mm_unpackeh_pu16 Interleaves, unsigned and extended WUNPCKEHUH

_mm_unpackeh_pu32 Interleaves, unsigned and extended WUNPCKEHUW

_mm_unpackel_pi8 Interleaves, signed and extended WUNPCKELSB

_mm_unpackel_pi16 Interleaves, signed and extended WUNPCKELSH

_mm_unpackel_pi32 Interleaves, signed and extended WUNPCKELSW

_mm_unpackel_pu8 Interleaves, extended WUNPCKELUB

_mm_unpackel_pu16 Interleaves, extended WUNPCKELUH

_mm_unpackel_pu32 Interleaves, extended WUNPCKELUW


See Also
Other Resources
WMMX Intrinsic Functions
Smart Device Development

WMMX Set Intrinsics


The intrinsics listed in the following table are made up of composite instructions.
Intrinsic name Operation Number of elements Signed Reverse order WMMX Instruction
_mm_setzero_si64 Sets to zero 1 No No WZERO

_mm_set_pi32 Sets integer values 2 No No Composite

_mm_set_pi16 Sets integer values 4 No No Composite

_mm_set_pi8 Sets integer values 8 No No Composite

_mm_set1_pi32 Sets integer values 2 Yes No TBCSTW

_mm_set1_pi16 Sets integer values 4 Yes No TBCSTH

_mm_set1_pi8 Sets integer values 8 Yes No TBCSTB

_mm_setr_pi32 Sets integer values 2 No Yes Composite

_mm_setr_pi16 Sets integer values 4 No Yes Composite

_mm_setr_pi8 Sets integer values 8 No Yes Composite

_mm_setwcx Set control register -- -- -- TMCR

_mm_getwcx Get control register -- -- -- TMRC


See Also
Other Resources
WMMX Intrinsic Functions
Smart Device Development

WMMX General Support Intrinsics


The intrinsic functions listed in the following table provide general support operations.

Intrinsic name Operation WMMX Instruction

_mm_extract_pi8 Extracts on 8 bytes TEXTRMSB

_mm_extract_pi16 Extracts on 4 half words TEXTRMSH

_mm_extract_pi32 Extracts on two words TEXTRMSW

_mm_extract_pu8 Extracts on 8 bytes TEXTRMUB

_mm_extract_pu16 Extracts on 4 half words TEXTRMUL

_mm_extract_pu32 Extracts on two words TEXTRMUW

_mm_insert_pi8 Inserts a byte. TINSRB

_mm_insert_pi16 Inserts a half word TINSRH

_mm_insert_pi32 Inserts a word TINSRW

_mm_max_pi8 Computes maximum WMAXSB

_mm_max_pi16 Computes maximum WMAXSH

_mm_max_pi32 Computes maximum WMAXUB

_mm_max_pu8 Computes maximum, unsigned WMAXUB

_mm_max_pu16 Computes maximum, unsigned WMAXUH

_mm_max_pu32 Computes maximum, unsigned WMAXUW

_mm_min_pi8 Computes minimum WMINXSB

_mm_min_pi16 Computes minimum WMINSH

_mm_min_pi32 Computes minimum WMINUB

_mm_min_pu8 Computes minimum, unsigned WMINUB

_mm_min_pu16 Computes minimum, unsigned WMINUH

_mm_min_pu32 Computes minimum, unsigned WMINUW

_mm_movemask_pi8 Creates an 8-bit mask TMOVMSKB

_mm_movemask_pi16 Creates a 4 half-word mask TMOVMSKH


_mm_movemask_pi32 Creates a two word mask TMOVMSKW

_mm_shuffle_pi8 Returns a combination of 4 words WSHUFH

_mm_avg_pu8 Computes rounded average WAV2BR

_mmavg_pu16 Computes rounded average WAV2HR

_mmavg2_pu8 Computes average WAVG2B

_mmavg2_pu16 Computes average WAVG2H

_mm_sada_pu8 Computes absolute sum of differences WSADB

_mm_sada_pu16 Computes absolute sum of differences WSADH

_mm_align_si64 Extracts a 64-bit value WALIGN/WALIGNR

_mm_cvtsi32_si64 Converts from int to a 64-bit __m64 object TMCRR

_mm_cvtsi64_si32 Converts from__m64 object to int TMRRC

_mm_empty Empties MM state ---


See Also
Other Resources
WMMX Intrinsic Functions
Smart Device Development

ARM Compiler Options


The following table shows compiler options for ARM microprocessors.
Option Description
/QRArch - Specify Target Architecture Specifies target ARM microprocessors.

/QRimplicit-import - Disable Importing of Helpers Statically links compiler helper functions.

/QRinterwork-return - Enable Interworking Generates code that can interwork between ARM and Thumb mode.

/QRxscale - Specify XSCALE Target Generates code for Intel XScale microprocessors.

/QRxscalesched Generates code that enables internal scheduler optimizations for the XScale
pipeline.

/QRthumb Generates code for Thumb mode.


See Also
Other Resources
ARM Family Processors
Smart Device Development

/QRArch - Specify Target Architecture


This option specifies which ARM architecture the compiler will target. The following line shows the usage of this option:

/Qrarch{4|5} [T]

The following options are available for this switch.


4
Indicates the ARM4 architecture.
5
Indicates the ARM5 architecture.
T
Indicates that the architecture supports the ARM/Thumb interworking instructions.
See Also
Other Resources
ARM Family Processors
Smart Device Development

/QRimplicit-import - Disable Importing of Helpers


This option forces the compiler to use statically linked helper functions.
Compiler helper functions are typically located in a DLL. To reduce the thunk overhead when calling these functions, the
compiler uses the dllimport calling mechanism. If OS or driver code is linked statically with the helper functions, the
/QRimplicit-import- flag is used to force the compiler to use typical calling mechanisms.
See Also
Other Resources
ARM Calling Sequence Specification
Smart Device Development

/QRinterwork-return - Enable Interworking


This option instructs the compiler to generate code that enables programs to call functions from ARM or Thumb mode and
return correctly.
See Also
Concepts
THUMB-enabled ARM Implementation
Smart Device Development

/QRxscale - Specify XSCALE Target


This option specifies that the compiler should generate code that runs on an Intel XScale processor. This enables the XScale
MAC intrinsics and causes the scheduler to optimize for the XScale pipeline.
See Also
Reference
ARM XSCALE Intrinsic Functions
Smart Device Development

/QRxscalesched
This option enables a re-ordering of instructions in the generated code to take advantage of XScale-specific optimizations for
internal scheduling of instruction execution.
The functionality offered by this option is a proper subset of the functionality of the /QRxscale - Specify XSCALE Target option.
See Also
Reference
ARM XSCALE Intrinsic Functions
Smart Device Development

/QRthumb
This option enables the ARM Thumb instruction set.
See Also
Concepts
THUMB-enabled ARM Implementation
Smart Device Development

ARM Calling Sequence Specification


The ARM Calling Sequence Specification for the ARM device compiler provides direction for the development of compilers and
assembly language programs for the Arm family of microprocessors.
In This Section
ARM Registers
Shows the assigned register roles.
ARM Stack Frame Layout
Describes how ARM microprocessors specify the stack layout.
ARM Prolog and Epilog
Describes the prolog and epilog code segments required for Structured Exception Handling.
THUMB-enabled ARM Implementation
Describes how to implement ARM-Thumb interworking.
ARM Assembler
Describes ARM Assembler macros for prolog and epilog, directives, and command-line options.
Related Sections
ARM Compiler Options
Provides reference information about compiler options for ARM compilers.
Intrinsic Functions for ARM Microprocessors
Provides reference information about intrinsic functions supported only by ARM compilers
Differences Between Desktop and Device Compilers
Describes critical differences in implementation between desktop and device compilers.
Smart Device Development

ARM Registers
The ARM microprocessor has 16 general-purpose registers.
THUMB has eight general-purpose registers, R0-R7, and access to the high registers, R8-R15.
The following table shows the assigned register roles.
Register Description
R0 Argument1, Return Value
Temporary register

R1 Argument2, Second 32-bits if double/int Return Value


Temporary register

R2-R3 Arguments
Temporary registers

R4-R10 R7 is THUMB frame pointer


Permanent registers.

R11 ARM frame pointer


Permanent register

R12 Temporary register

R13 Stack pointer


Permanent register

R14 Link register


Permanent register

R15 Program Counter

Note that registers R0 through R3 hold the first four words of incoming arguments. The microprocessor constructs remaining
arguments in the calling function's argument build area, which does not provide space into which R0 through R3 can be
spilled.
The following table shows additional predefined registers for Vector Floating Point and for WMMX.
Register Description
s0-s32 VFP single-precision registers

d0-d16 VFP double-precision registers

fpsid VFP system ID register

fpscr VFP status and control register

fpexc VFP exception register

wr0-wr16 WMMX SIMD data registers


wc0-wc16 WMMX status and control registers

wcid WMMX coprocessor ID register, synonymous with wc0

wcon WMMX control register, synonymous with wc1

wcssf WMMX saturation SIMD flags, synonymous with wc2

wcasf WMMX arithmetic SIMD flags, synonymous with wc3

wcgr0-wcgr3 WMMX control general-purpose registers, synonymous with wc8-wc11

See Also
Reference
ARM Assembler Macros
Concepts
ARM Stack Frame Layout
Smart Device Development

ARM Stack Frame Layout


The following list gives more information about ARM microprocessor stack frame layout.
The Register Save Area (RSA) holds the preserved values of permanent registers used by the function. It also contains
the function return address.
The Locals and Temporaries area represents the stack space allocated for local variables and compiler-generated
temporaries.
The first four words at the top of the stack can contain the values passed in R0-R3. Any of these values could be missing.
The values should be stored in the R0-R3 if registers cannot hold the arguments for the entire function, or if the
addresses for the arguments are in use.
If a routine needs storage space for the first four words of arguments, it creates and initializes the storage at the top of
the called function stack.
If a register keeps an argument for the argument live range, the argument has no associated storage in the stack frame.

ARM Frame and Stack Pointers


A frame pointer helps mitigate problems with the limited size of the bit field that specifies register-displacement-addressing
offset. The frame pointer typically points to a fixed frame offset in the RSA or Local and Temporaries areas of the stack frame,
but the pointer can point to other offsets within the frame. To more efficiently access data in large stack frames, a routine can
establish another frame pointer.
A routine does not need to set up a stack frame unless it needs to save permanent registers, or to allocate space for locals
or outgoing argument areas that are bigger than four words. The stack pointer and frame pointer addresses align on 4-
byte boundaries.
If a routine has alloca() locals, the ARM specification requires a separate frame pointer register to access incoming
arguments and locals.
R11 is the assigned frame pointer for ARM, and R7 is the assigned frame pointer for THUMB.
A leaf routine can use any free integer register as the frame pointer. A nonleaf routine must use a permanent register.
The routine must not modify the frame pointer register between the prolog and epilog.
If a routine uses alloca(), everything in the frame at a lower address than the alloca() area is referenced relative to R13
and never contains a defined value at the time of an alloca() call. Thus, the alloca() operation never needs to copy this
part of the stack frame, and no data relocation problems arise.
Everything in the frame at an address higher than the alloca() area is referenced relative to the frame pointer, R11 for
ARM or R7 for THUMB.

See Also
Concepts
ARM Registers
Smart Device Development

ARM Prolog and Epilog


ARM prolog and epilog code segments are required to implement Structured Exception Handling (SEH) for ARM
microprocessors. The ARM prolog is a code segment that sets up the stack frame for a routine. The epilog removes the routine
frame and returns from the routine.
In This Section
ARM Prolog

Describes the requirements of an ARM prolog, and provides an example.


ARM Epilog
Describes the requirements of an ARM epilog, and provides an example.
THUMB Prolog
Describes the requirements of an THUMB prolog, and provides an example.
THUMB Epilog
Describes the requirements of an THUMB epilog, and provides an example.
ARM Assembler Macros
Provides reference information about the ARM Assembler macros used to define the ARM and THUMB prolog and epilog
sequences.
Related Sections
ARM Calling Sequence Specification
Provides links to reference information about the ARM calling sequence specification.
SEH in RISC Environments
Describes the implementation of Structured Exception Handling in RISC environments such as ARM.
Smart Device Development

ARM Prolog
The ARM prolog has three constituent parts. All parts are immediately contiguous, with no intervening instructions. When the
prolog follows this guideline, the Virtual Unwinder can reverse-execute the prolog.
The following list shows the three required parts of an ARM prolog.
1. A sequence of zero or one instructions that push the incoming argument values from R0, R1, R2, and R3 to the
argument home locations, and updates R13 to the new stack top.
This sequence saves all permanent registers in descending order at the top of the stack frame, following any saved
argument registers.
2. A sequence of one or more instructions that set up the frame pointer, if one is to be established.
The prolog copies stack pointer R13 to R12 before the initial register saves and uses R12 to compute the value of the
frame pointer, R11.
3. A sequence of zero or more instructions that allocate the remaining stack frame space for local variables, compiler-
generated temporaries, and the argument build area by subtracting a 4-byte aligned offset from R13.
If an offset is too wide to represent in the immediate field, the prolog uses the scratch register R12 to hold the offset. In
this case, it sets the value in R12 with a different instruction.

Examples
The following examples show how to construct several ARM prologs.
ARM Prolog with frame in R11.
MOV r12, r13 ; Save stack on entry if needed.
STMDB r13!, {r0-r3} ; As needed
STMDB r13!, {r4-r12, r14} ; As needed
SUB r11, r12, #16 ; Sets frame past args
<stack link if needed>

ARM Prolog with no frame.


MOV r12, r13
STMDB r13!, {r0-r3} ; As needed
STMDB r13! {[r4-r12,]|[r13,]r14} ; As needed
<stack link if needed>
<note: r12 is not used if the stack (r13) is the first register saved>

See Also
Concepts
SEH in RISC Environments
ARM Epilog
Smart Device Development

ARM Epilog
The ARM epilog is a contiguous sequence of instructions that does the following:
Restores the saved permanent registers
Resets the stack pointer to its value on function entry
Returns to the function's calling function
The following list shows the guidelines for implementing an epilog:
All parts are immediately contiguous, with no intervening instructions.
If a frame pointer is set up, the epilog is a single instruction that uses the frame as the base and updates all nonvolatile
registers, including the Program Counter and the stack.
If no frame is set up, the epilog consists of a stack unlink, if needed, followed by an instruction to restore multiple
registers or to copy the link register R14 to the program counter.
If the function establishes a frame pointer (which has the value of R11 for an ARM epilog), the function must not modify
the pointer value during the interval between the completion of the prolog's last instruction and the beginning of the
execution of the first instruction of the epilog.
If the function does not establish a frame pointer (which has the value of R13), the function must not modify the stack
pointer during the interval between the completion of the prolog's last instruction and the beginning of the execution of
the first instruction of the epilog.
In a routine that does not modify nonvolatile registers and is not interworking, the epilog contains only a copy of the link
register to the program counter.
A routine whose last instruction is a branch to another routine can have an empty epilog if it does not modify nonvolatile
registers.
The address contained in the stack pointer, which always has the value of R13, must never be greater than the lowest
address of any unrestored register value in the Register Save Area.
This prevents the preserved values of the permanent registers from being corrupted by a context switch or any other
asynchronous event that might occur during the execution of a prolog or epilog.
Example
The following examples show a variety of ARM epilogs.
ARM Epilog with frame in R11.
<no stack unlink>
LDMDB r11, {r4-r11, r13, r15}

ARM Epilog with no frame.


<stack unlink if needed>
LDMIA r13, {r4-R11, r13, r15}

ARM Epilog with interworking return.


<stack unlink if needed>
LDMIA r13, {r4-r11, r13, LR}
BX LR

See Also
Concepts
SEH in RISC Environments
ARM Prolog
Smart Device Development

THUMB Prolog
A THUMB prolog has the following specific parts. All parts are immediately contiguous with no intervening instructions.
A sequence of zero or one instructions that push the incoming argument values in R0, R1, R2, and R3 to the argument
home locations, and updates R13 to the new stack top.
If the function does not use high registers such as R8, R9, R10, and R11, a sequence of instructions pushes R4-R7 or the
link register R14 to the stack.
The function does not push the link register if the routine is a leaf with no high registers saved.
A sequence of zero or more instructions that allocate the remaining stack frame space for local variables, compiler-
generated temporaries, and the argument build area by subtracting an aligned offset from R13.
A single instruction that sets the frame pointer if one is to be established.
Immediately after it links the stack, the function copies the value of the stack pointer in R13 to R7.
Example
The following examples show a variety of THUMB prologs.
THUMB Prolog with no frame.
PUSH {r0-r3} ; As needed
PUSH {r4-r7, LR} ; As needed
SUB SP, SP, #4 ; Stack link (as needed)

THUMB Prolog with frame in R7.


PUSH {r0-r3} ; As needed
PUSH {r4-r7, LR} ; As needed
SUB SP, SP, #4 ; Stack link (as needed)
MOV r7, SP ; Set frame

THUMB Prolog with interworking return.


PUSH {r4-r7, LR}

THUMB Prolog saving high registers.


PUSH {r0-r3} ; Save r0-r3 as needed
PUSH {LR}
BL __savegpr_9 ; Routine for saving {r4-r11}
SUB SP, SP, #4 ; Stack link (as needed)

THUMB Prolog with a large stack frame.


PUSH {r7}
LDR r7, [PC, #20]
NEG r7, r7
ADD SP, r7

See Also
Concepts
SEH in RISC Environments
THUMB Epilog
Smart Device Development

THUMB Epilog
The THUMB epilog is a contiguous sequence of instructions that does the following:
Restores the saved permanent registers
Resets the stack pointer to its value on function entry
Returns to the function's calling function
The following list shows important information about an epilog.
If a frame pointer has been set up by the prolog, the epilog restores the stack pointer from the frame pointer. It uses a
single mov instruction to copy R7 to R13. This copy restores R13 to the value it had just after the prolog linked the
stack.Unlinking the stack restores R13.
If {R4-R7} are to be restored, and if high registers are not to be restored, the epilog must contain an instruction to pop
{R4-R7}. This instruction updates the stack pointer. If the Unwinder restores high registers, it also restores R4-R7.
The epilog contains a sequence of zero or two instructions that pop the link register from the stack into R3.
If the routine is a leaf or if the routine restores high registers, the epilog omits this sequence.
If the epilog restores high registers, it uses a branch and link to call a restore-register routine that restores R4 through R7
and the link register. It also restores the stack pointer to the value it held just after the prolog saved {R0-R3}, or to the
value the stack pointer held on entry of the function if { R0-R3} were saved.
In a non-interworking routine that does not need to save registers other than { R4-R7,LR}, the epilog ends with pop {R4-
R7, PC} or pop { PC } if { R4-R7} do not need to be saved. If a noninterworking routine needs to save other registers, the
epilog ends with a copy of R3 to the PC.
In an interworking routine, the epilog ends with a branch and exchange (BX) to R3.
Example
The following examples show a variety of THUMB epilogs.
THUMB Epilog with no frame.
ADD SP, SP, #4 ; Stack link (as needed)
POP {r4-r7}
POP {r3} ; POP link register into r3
ADD SP, SP, #16 ; POP r0-r3 as needed
MOV PC, r3

THUMB Epilog with frame in R7.


MOV r13, r7
ADD SP, SP, #4 ; Stack unlink (as needed)
POP {r4-r7}
POP {r3} ; POP link register into r3
ADD SP, SP, #16 ; POP r0-r3 as needed
MOV PC, r3

THUMB Epilog restoring high registers.


ADD SP, SP, #4 ; Stack link (as needed)
BL __restgpr_9
ADD SP, SP, #16 ; POP r0-r3 as needed
BX LR

THUMB Epilog with a large stack frame.


LDR r7, [PC, #4]
ADD SP, r7
POP {r7}
MOV PC, LR
See Also
Concepts
SEH in RISC Environments
THUMB Prolog
Smart Device Development

ARM Assembler Macros


ARM assembler-level macros are required to implement prolog and epilog code segments.
The following assembler level macros are available for ARM microprocessors.
Macro Description
ALTERNATE_ENTRY (ARM) Declares an alternate entry to a routine.

END_REGION (ARM) Marks the end of a contiguous range of text or data.

ENTRY_END (ARM) Ends the routine that was specified by a prior NESTED_ENTRY (ARM).

EXCEPTION_HANDLER (ARM) Associates a named exception handler with the subsequent NESTED_ENTRY (ARM).

EXCEPTION_HANDLER_DATA (ARM) Associates a named exception handler and the handler data with the subsequent
NESTED_ENTRY (ARM).

LEAF_ENTRY (ARM) Declares the beginning of a routine that does not require prolog code.

NESTED_ENTRY (ARM) Declares the beginning of a routine that either has an existing stack frame or that creates
a stack frame.

PROLOG_END (ARM) Marks the end of the prolog area.

START_REGION (ARM) Marks the beginning of a contiguous range of text or data.


See Also
Concepts
ARM Registers
ARM Stack Frame Layout
Other Resources
ARM Prolog and Epilog
Smart Device Development

ALTERNATE_ENTRY (ARM)
This macro declares an alternate entry to a routine of type NESTED_ENTRY (ARM) or LEAF_ENTRY (ARM).

ALTERNATE_ENTRY Name[,[Section=]SectionName]

Parameters
Name
The entry point.
SectionName
The name of the section where the entry appears; see Remarks.
Return Value
None.
Remarks
Name is in the global name space.
The ALTERNATE_ENTRY macro does not use the SectionName parameter. The parameter is accepted and ignored for
consistency with NESTED_ENTRY (ARM) and LEAF_ENTRY (ARM).
If used, an ALTERNATE_ENTRY call must appear in the body of a routine.
See Also
Reference
NESTED_ENTRY (ARM)
LEAF_ENTRY (ARM)
Smart Device Development

END_REGION (ARM)
This macro marks the end of a contiguous range of text or data.

END_REGION NameEnd

Parameters
NameEnd
NameEnd labels the end of the range.
Return Values
None.
Remarks
NameEnd is in the global name space.
See Also
Reference
START_REGION (ARM)
Smart Device Development

ENTRY_END (ARM)
This macro ends the current routine specified by NESTED_ENTRY (ARM) or LEAF_ENTRY (ARM).

ENTRY_END [Name]

Parameters
Name
See Remarks.
Return Values
None.
Remarks
Name should be the same name used in the NESTED_ENTRY or LEAF_ENTRY macros.
The ENTRY_END macro ignores Name.
See Also
Reference
NESTED_ENTRY (ARM)
LEAF_ENTRY (ARM)
Smart Device Development

EXCEPTION_HANDLER (ARM)
This macro associates an exception handler Handler with a subsequent NESTED_ENTRY (ARM) or LEAF_ENTRY (ARM) routine.

EXCEPTION_HANDLER Handler

Parameters
Handler
Name of the exception handler.
Return Values
None.
Remarks
This association is in effect until the compiler encounters a matching ENTRY_END (ARM) macro.
See Also
Reference
NESTED_ENTRY (ARM)
LEAF_ENTRY (ARM)
ENTRY_END (ARM)
EXCEPTION_HANDLER_DATA (ARM)
Smart Device Development

EXCEPTION_HANDLER_DATA (ARM)
This macro associates an exception handler Handler and HandlerData with a subsequent NESTED_ENTRY (ARM) or
LEAF_ENTRY (ARM) routine.

EXCEPTION_HANDLER_DATA Handler, HandlerData

Parameters
Handler
Name of the exception handler.
HandlerData
String associated with the exception handler.
Return Values
None.
Remarks
This association is in effect until compiler encounters a matching ENTRY_END (ARM) macro.
See Also
Reference
NESTED_ENTRY (ARM)
LEAF_ENTRY (ARM)
ENTRY_END (ARM)
EXCEPTION_HANDLER (ARM)
Smart Device Development

LEAF_ENTRY (ARM)
This macro declares the beginning of a routine that does not require prolog code.

LEAF_ENTRY Name[,[Section=]SectionName]

Parameters
Name
The routine name.
SectionName
Optional. The name of the section where the entry appears.Defaults to .text.
Return Values
None.
Remarks
Name is in the global name space.
A LEAF_ENTRY must have an associated ENTRY_END (ARM).
See Also
Reference
ENTRY_END (ARM)
PROLOG_END (ARM)
Smart Device Development

NESTED_ENTRY (ARM)
This macro declares the beginning of a routine that either has an existing frame or creates a stack frame.

NESTED_ENTRY Name[,[Section=]SectionName]

Parameters
Name
The routine name.
SectionName
Optional. The name of the section where the entry appears.Defaults to text.
Return Values
None.
Remarks
Name is in the global name space.
A NESTED_ENTRY must have an associated PROLOG_END (ARM) and ENTRY_END (ARM).
See Also
Reference
ENTRY_END (ARM)
PROLOG_END (ARM)
Smart Device Development

PROLOG_END (ARM)
This macro marks the end of the prolog area.

PROLOG_END

Parameters
None.
Return Values
None.
Remarks
This macro must appear following a NESTED_ENTRY (ARM) or LEAF_ENTRY (ARM) macro.
It appears after the prolog area and before the matching ENTRY_END (ARM) macro.
See Also
Reference
NESTED_ENTRY (ARM)
LEAF_ENTRY (ARM)
ENTRY_END (ARM)
Smart Device Development

START_REGION (ARM)
This macro marks the beginning of a contiguous range of text or data.

START_REGION NameBegin

Parameters
NameBegin
NameBegin labels the beginning of the range. NameBegin is in the global name space.
Return Values
None.
See Also
Reference
END_REGION (ARM)
Smart Device Development

THUMB-enabled ARM Implementation


THUMB-enabled ARM microprocessors can execute 16-bit THUMB instructions in addition to the usual 32-bit ARM
instructions.
To execute THUMB instructions, switch the microprocessor into THUMB mode. To resume executing ARM instructions, switch
the microprocessor back into ARM mode. The instruction that accomplishes the mode switch is the branch and exchange (BX)
instruction.
To call a function compiled by the THUMB compiler from within a function compiled by the ARM compiler, the code sequence
must include a BX instruction on the caller side and on the callee side.
The BX instruction is of the form BX Rx, where Rx,is a register containing an address.
If the low bit of the BX target address is set, BX causes a switch into THUMB mode.
If the low bit of the BX target address is not set, BX causes a switch into ARM mode.
The linker sets the low bit of THUMB function addresses at link time.
The ARM C/C++ compiler supports function calls and returns for ARM/THUMB interworking. The following mechanisms
support interworking.
Compiler flags
Language extensions by way of interworking declspec modifiers
Link-time generation of thunking routines
The use of an interworking calling sequence allows but does not require a mode switch to occur.
In addition, a THUMB function can call another THUMB function and an ARM function can call another ARM function through
an interworking calling sequence.
See Also
Reference
Compiler Flags for Interworking
Concepts
Modifiers
Linker-Generated Thunking Routines
Code Size Considerations
Smart Device Development

Compiler Flags for Interworking


The following compiler flags apply to the creation of interworking programs.
The /QRinterwork-return - Enable Interworking flag causes all function returns in a file to be made interworking.
This flag has no effect on function calls.
The /QRArch - Specify Target Architecture flag allows the compiler to generate instructions that are only available on
THUMB-enabled microprocessors, such as BX.
For THUMB, this flag is on by default.
For ARM, this flag is off by default.
The /QRinterwork-return flag enables the /QRarch flag.
See Also
Concepts
THUMB-enabled ARM Implementation
Smart Device Development

Modifiers
ARM and THUMB support Microsoft-specific modifiers for interworking. The iwcall, iw16, and iw32 declspecs allow you to
select which function calls are interworking.
Compared to a linker-generated thunking routine, the iwcall or iw16 declspecs always result in faster code for interworking
calls. The declspecs add only a single MOV instruction to the execution path, while a linker-generated thunking routine adds
two instructions: a load from memory, and a branch.
See Also
Concepts
THUMB-enabled ARM Implementation
Linker-Generated Thunking Routines
Smart Device Development

iw16
When compiled by the ARM compiler, the iw16 declspec has the same effect as the iwcall declspec; that is, it makes an
interworking call.
When compiled by the THUMB compiler, the iw16 declspec has no effect.
Use the iw16 declspec only when you know which compiler, ARM or THUMB, will compile the designated function.
iw16 declspec has no effect on the ARM compiler unless you also use the /QRArch - Specify Target Architecture flag.
Using the /QRinterwork-return - Enable Interworking flag automatically enables the /QRarch flag.
See Also
Reference
iwcall
iw32
/QRinterwork-return - Enable Interworking
/QRArch - Specify Target Architecture
Concepts
Modifiers
Smart Device Development

iw32
When compiled by the THUMB compiler, the iw32 declspec has the same effect as the iwcall declspec; that is, it makes an
interworking call.
When compiled by the ARM compiler, the iw32 declspec has no effect.
Use the iw32 declspec only when you know which compiler, ARM or THUMB, will compile the designated function.
See Also
Reference
iwcall
iw16
Concepts
Modifiers
Smart Device Development

iwcall
The iwcall declspec allows the programmer to select which function calls are interworking, regardless of whether the ARM or
THUMB compiler is used.
Using iwcall allows you to avoid link-time generation of interworking thunking routines.
Note that iwcall has no effect unless it is used on a function prototype visible to the caller.
The iwcall declspec does not cause the associated function to have an interworking return. To make an interworking return,
use the -/QRinterwork-return - Enable Interworking flag.
You can use __declspec(iwcall) on the prototype of the user-supplied function to enable the library to handle either case.
The following code example shows how to use of iwcall declspec to enable a user-supplied function myfunction().

__declspec(iwcall) int myfunction();


int main()
{
return myfunction();
}

The following listing shows the code generated from this declspec when compiled with /QRArch - Specify Target Architecture.

str lr, [sp, #4]!


ldr r3, [pc, #8]
mov lr, pc
bx r3
ldmia sp!, {pc}
DCD |myfunction|

The following listing shows the code generated with the ARM compiler using the /QRthumboption.

push {lr}
ldr r3, [pc, #0x2]
mov r12, r3
bl __r12_indirect
pop {pc}
DCD |myfunction|

See Also
Reference
/QRinterwork-return - Enable Interworking
/QRArch - Specify Target Architecture
Concepts
Modifiers
Smart Device Development

Linker-Generated Thunking Routines


If no declspec call enables interworking function calls, the linker generates a thunking routine to perform necessary caller-side
mode changes from ARM to THUMB or vice versa. The linker generates a thunking routine for each unique function called
from an object that requires the opposite mode.
For the required mode switch to occur on the return from the function, the programmer must use the
/QRinterwork-return - Enable Interworking flag at compile time.
The following code example shows a linker-generated thunking routine generated when switching from ARM to THUMB mode.

0xe59fc000 ldr r12, [pc]


0xe12fff1c bx r12
0x00000000 DCD |destination|

The following code example shows the linker-generated thunking routine generated when switching from THUMB to ARM
mode.

0xb408 push {r3}


0x4b02 ldr r3, [pc, #8]
0x469c mov r12, r3
0xbc08 pop {r3}
0x4760 bx r12
0x0000 pad
0x00000000 DCD |destination|

See Also
Reference
/QRinterwork-return - Enable Interworking
/QRArch - Specify Target Architecture
Smart Device Development

Code Size Considerations


Both declspec modifiers and linker-generated thunking routines add additional 32-bit words of text-space instruction.
In general, if a program contains only a few interworking functions, but the interworking functions are called from many
places; a linker-generated thunking routine probably results in smaller overall code size.
If a program contains many different interworking functions, but the interworking functions are called from only a few places,
using iwcall or iw16 results in code size similar to that required by a linker-generated thunking routine.
If code size efficiency is important, keep in mind the following additional word requirements:
The iwcall and iw16 declspecs require an additional 32-bit word of text-space instruction per interworking call.
Because the function address must be placed into and loaded from the literal pool, the function address can add up to
two 32-bit words of text space instruction to the space required by the linker-generated thunking routine.
Because different load instructions can share a given literal pool entry, some function calls do not add words for a
declspec. The literal pool entry can be loaded into a register that different BX instructions use without reloading the
register.
Allowing the linker to generate a thunking routine for the ARM compiler requires three additional 32-bit words per called
function but no additional words at the call sites. A linker-generated thunking routine for the THUMB compiler requires
four words instead of three.
Note:
Regardless of how many different callers call a function, the linker generates only one interworking thunking routine p
er function call.

See Also
Concepts
Linker-Generated Thunking Routines
Modifiers
Smart Device Development

ARM Assembler
The ARM assembler (armasm) is a two-pass assembler, processing its source files twice to reduce the amount of internal state
that it needs to keep.
The ARM assembler compiles both ARM and Thumb assembly language into the Microsoft implementation of the Common
Object File Format (COFF).
In This Section
ARM Assembler Command-Line Options
Describes the command-line syntax for invoking the ARM Assembler, and describes the command-line options.
Predeclared ARM Register Names
Provides reference information about register names that the ARM Assembler pre-declares.
Built-In ARM Assembler Variables
Provides reference information about variables that have built-in definitions for the ARM Assembler.
ARM Assembler Directives
Describes the assembler directives.
Related Sections
ARM Family Processors
Smart Device Development

ARM Assembler Command-Line Options


The syntax of a command to invoke the ARM assembler is as follows:

armasm {options} sourcefile objectfile

The following table shows command-line options for the ARM assembler.
Option Description
-archarchitecture Sets the target architecture. Legitimate values are 4, 4T, 5, and 5T.
Some microprocessor-specific instructions produce errors or warnings if assembled for the wrong tar
get architecture.

-checkreglist Checks LDM and STM register lists to ensure that register number order is increasing.
If not, a warning is given.
You can use -checkreglist to detect misuse of symbolic register names.

-cpu ARMcore Sets the target ARM core.


Legitimate values include the following:
ARM7TM
ARM720t
ARM920t
ARM8
ARM10
ARM10T
ARM10200
StrongARM or StrongARM1
XSCALE
PXA270
Some microprocessor-specific instructions produce warnings if assembled for the wrong ARM core.

-errors errorfile Outputs error messages to errorfile.

-help Displays a summary of the command-line options.

-i dir{,dir} Specifies directories to include.


Directories can also be specified by using the INCLUDE environment variable.

-ignore 0241 -archarch Instructs the build process to ignore warning message 0241 for an instruction not implemented on th
itecture e specified target architecture.

-list listingfile-noterse Turns the terse flag off.


When the terse flag is on, lines skipped due to conditional assembly do not appear in the listing.
When the terse flag is off, these lines appear in the listing.
The default is on.
-list listingfile-width n Sets the listing page width.
The default is 79 characters.

-list listingfile-length n Sets the listing page length.


Length 0 means an unpaged listing.
The default is 66 lines.

-list listingfile-xref Lists cross-referencing information on symbols.


Provides definition location and usage location inside and outside of macros.
The default is off.

-noesc Ignores C-style special characters (\n, \t, and so on).

-noregs Tells the assembler not to predefine implicit register names r0–r15, a1–a4, v1–v6, c0–c15, p0–p15, s
l, fp, ip, sp, lr, pc.

-nowarn Turns off warning messages.

-predefine "directive" Pre-executes a SETx directive.


This implicitly executes a corresponding GBLx directive.
Because it contains spaces, place the full SETx argument in quotation marks. For example:
-predefine "Version SETA 44"

-Via file Opens file and reads in more armasm command-line arguments.
See Also
Reference
Predeclared ARM Register Names
Built-In ARM Assembler Variables
Other Resources
ARM Assembler
Smart Device Development

Predeclared ARM Register Names


By default, the assembler predeclares the following register names:
R0–R15 and r0–r15
c0–c15 coprocessor registers
p0–p15 coprocessor registers
a1-a4 scratch registers, synonymous with r0-r3
v1-v8 variable registers, synonymous with r4-r11
sb and SB stack base, synonymous with r9
sl and SL stack base, synonymous with r10
fp and FP frame pointer, synonymous with r11
ip and IP intra-procedure call scratch register, synonymous with r12
sp and SP stack pointer, synonymous with r13
lr and LR link register, synonymous with r14
pc and PC program counter, synonymous with r15
s0-s32 VFP single precision registers
d0-d16 VFP double precision registers
fpsid VFP system ID register
fpscr VFP status and control register
fpexc VFP exception register
wr0-wr16 WMMX SIMD data registers
wc0-wc16 WMMX status and control registers
wcid WMMX coprocessor ID register, synonymous with wc0
wcon WMMX control register, synonymous with wc1
wcssf WMMX saturation SIMD flags, synonymous with wc2
wcasf WMMX arithmetic SIMD flags, synonymous with wc3
wcgr0-wcgr3 WMMX control general purpose registers, synonymous with wc8-wc11
See Also
Reference
Built-In ARM Assembler Variables
Other Resources
ARM Assembler
Smart Device Development

Built-In ARM Assembler Variables


The ARM assembler contains built-in variables for programmer convenience.
The following table shows the built-in variable definitions.
Variable Description
{PC} or . Contains the current value of the program location counter.

{VAR} or @ Contains the current value of the storage area location counter.

{TRUE} Contains the logical constant true.

{FALSE} Contains the logical constant false.

{OPT} Contains the value of the currently set listing option.


The OPT directive can be used to save the current listing option, force a change in it, or restore its original val
ue.

{CONFIG} Has the value 32 if the assembler is in 32-bit program counter mode, and the value 26 if it is in 26-bit mode.

{ENDIAN} Has the value "big" if the assembler is in big-endian mode and the value "little" if it is in little-endian mode.

{CODESIZE} Has the value 16 if compiling Thumb code. Otherwise, it is 32.

{CPU} Has the name of the selected CPU or generic ARM if no CPU is specified.

{ARCHITECTURE Has the value of the selected ARM architecture: 4 or 4T.


}
See Also
Reference
Predeclared ARM Register Names
Other Resources
ARM Assembler
Smart Device Development

ARM Assembler Directives


The ARM assembler supports a full array of assembler directives that allow you to control and direct source file assembly.
In This Section
ARM Initialization and Layout Directives
ARM Linking Directives
ARM Diagnostic Directives
ARM Directives for Conditional Assembly
ARM Dynamic Listing Directive Options
ARM-Thumb Interworking Directives
ARM Constant and Variable Declarations
ARM Assembler Directives for Macro Definition
Miscellaneous ARM Directives
Related Sections
ARM Assembler Command-Line Options
Predeclared ARM Register Names
Built-In ARM Assembler Variables
ARM Assembler Error Messages
Smart Device Development

ARM Initialization and Layout Directives


The AREA directive instructs the assembler to assemble a new code or data sections, used in an expression of the following
form:
AREA sectionname{,attr}{,attr}...

The AREA sectionname expression is modified by one or more comma-delimited attributes.


The following table shows the valid attributes for an AREA directive.
Attrib Description
ute
ALIGN Defines the section boundary, where the section is aligned on a 2expression -byte boundary.
expression can have any integer value from 0 to 31. Do not use ALIGN=0 or ALIGN=1 for code sections.
Note that the ALIGN attribute is not the same as the ALIGN directive.

CODE Contains machine instructions. READONLY is the default.

DATA Contains data, not instructions. READWRITE is the default.

NOINI Indicates that the data section is uninitialized, or initialized to zero. It contains only space reservation directives SPACE
T or DCB, DCD< DCDU, DCQ, DCQU, or DCWU with initialized values of zero.

READO Indicates that this section should not be written to. This is the default for CODE areas.
NLY

READ Indicates that this section can be read from and written to. This is the default for DATA areas.
WRITE
See Also
Reference
ARM Initialization and Layout Directives
Smart Device Development

ARM Linking Directives


The following ARM assembly directives link other files to the current assembly.
Direc Syntax Description
tive
EXPO EXPORT symbol{[FPREGA Declares a symbol for use at link time by other, separate object files.
RT RGS,DATA,LEAF]}
FPPREGARGS defines a function that expects fp arguments passed in fp registers.
DATA defines a code-segment datum rather than a function or procedure.
LEAF causes asserts that call other functions.
Identical to the GLOBAL directive.

GET GET filename Includes an additional file named filename within the current file assembly.
The included file can in turn use GET directives to include more files.
When assembly of the included file is complete, assembly continues at the line foll
owing the GET directive.

GLOB GLOBAL symbol{ Declares a symbol for use at link time by other, separate object files.
AL [FPREGARGS,DATA,LEAF]
} FPPREGARGS defines a function that expects fp arguments passed in fp registers.
DATA defines a code-segment datum rather than a function or procedure.
LEAF causes asserts that call other functions.
Identical to the EXPORT directive.

IMPO IMPORT symbol{ Provides the assembler with a name, symbol.


RT WEAK=weak-symbol, {ty
pe=n}} The assembly does not contain a definition for symbol, but resolves it at link time t
o a symbol defined in a separate object file.
The routine treats symbol as a program address.

INCL INCLUDE filename Specifies a synonym for GET.


UDE
See Also
Other Resources
ARM Assembler Directives
Smart Device Development

ARM Diagnostic Directives


The following ARM assembly directives generate diagnostic information.
Dire Syntax Description
ctive
ASSE ASSERT logical-expressi Supports diagnostic generation.
RT on
If logical-expression returns FALSE, the assembler generates a diagnostic messag
e during the second pass of the assembly.
ASSERT can be used inside and outside macros.

! ! arithmetic-expression Related to ASSERT, but is inspected on both passes of the assembly, providing a
, string-expression more flexible means for creating custom error messages.
If arithmetic-expression equals 0, the assembler takes no action during pass one,
but prints string-expression as a warning during pass two.
If arithmetic-expression does not equal 0, the assembler prints string-expression
as a diagnostic message. The assembly halts after pass one.
This directive is identical to the INFO directive.

INFO INFO arithmetic-express If arithmetic-expression equals 0, the assembler takes no action during pass one.
ion, string-expression
It adds source file and line number as a prefix to string-expression, and prints the
result as a warning during pass two.
If arithmetic-expression does not equal 0, the assembler prints string-expression
as a diagnostic message. The assembly halts after pass one.
This directive is identical to the ! directive.
See Also
Other Resources
ARM Assembler Directives
Smart Device Development

ARM Directives for Conditional Assembly


The ARM assembler supports conditional assemblies for sections of a source file; that is, it assembles the specified sections if
certain conditions are true.
In addition, the assembler supports WHILE...WEND directives for conditional looping that are useful for generating repetitive
tables.
Conditional looping produces an assembly-time loop, not a run-time loop. Because the test for the WHILE condition is made at
the top of the loop, it is possible that no code is generated during assembly; lines are listed as for conditional assembly.
The following ARM assembler directives are required for conditional and repetitive assembly.
[ or IF
Marks the start of the condition.
] or ENDIF
Marks the end of the condition.
| or ELSE
Provides an else construct.
WHILE
Marks the start of the repetitive condition.
WEND
Marks the end of the repetitive condition.
Note that the characters [, |, and ] cannot be the first character in a line. These characters must be preceded by a space or a tab.
The following code shows the syntax for conditional assembly.

[ logical-expression
...code...
|
...code...
]

The following code shows the syntax for repetitive assembly.

WHILE logical-expression
...code...
WEND

See Also
Other Resources
ARM Assembler Directives
Smart Device Development

ARM Dynamic Listing Directive Options


The OPT directive is used to set listing options from within the source code, if listing is turned on.
The default setting is to produce a normal listing, including the declaration of variables, macro expansions, call-conditioned
directives, and MEND directives, but without producing a listing during the first pass.
These settings can be altered by adding the appropriate values from the list and using them with the OPT directive, as shown
in the following table.
1
Turns on normal listing.
2
Turns off normal listing.
4
Page throw: issues an immediate form feed and starts a new page.
8
Resets the line number counter to 0.
16
Turns on the listing of SET, GBL, and LCL directives.
32
Turns off the listing of SET, GBL, and LCL directives.
64
Turns on the listing of macro expansions.
128
Turns off the listing of macro expansions.
256
Turns on the listing of macro calls.
512
Turns off the listing of macro calls.
1024
Turns on the first pass listing.
2048
Turns off the first pass listing.
4096
Turns on the listing of conditional directives.
8192
Turns off the listing of conditional directives.
16384
Turns on the listing of MEND directives.
32768
Turns off the listing of MEND directives.
See Also
Other Resources
ARM Assembler Directives
Smart Device Development

ARM-Thumb Interworking Directives


The following table shows the ARM-THUMB interworking directives.
CODE16

Tells the assembler that subsequent instructions are to be interpreted as 16-bit (Thumb) instructions.
CODE32
Tells the assembler that subsequent instructions are to be interpreted as 32-bit (ARM) instructions.
DATA
Tells the assembler that the label is a "data-in-code" label; that is, that it defines an area of data within a code segment. You
must specify this directive if you are defining data in a Thumb code area.
See Also
Other Resources
ARM Assembler Directives
Smart Device Development

ARM Constant and Variable Declarations


The following ARM Assembly directives are for setting constants.
Directi Syntax Description
ve
* label *expression Identical to EQU.
Gives a symbolic label to a fixed or program-relative expression.

CN label CN numeric-expr Names a coprocessor register number; c0 to c15 are predefined and cannot be u
ession sed as labels.

CP label CP numeric-expr Gives a name to a coprocessor number, if available, that must be within the rang
ession e 0 to 15.
The names p0 - p15 are predefined and cannot be used as labels.

EQU label EQU expression Gives a symbolic label to a fixed or program-relative expression.

FN label FN numeric-expr Defines the names of floating-point registers, if available.


ession
The names F0-F7 and f0-f7 are predefined.
The predefined register names cannot be used as labels but can be used as nume
ric expressions.

RN label RN numeric-expr Defines register names. Refer to registers by name only.


ession
The names R0-R15, r0-r15, PC, pc, LR, and lr are predefined.
The predefined register names cannot be used as labels but can be used as nume
ric expressions.

The assembler supports global and local variables. The scope of global variables extends across the entire source file, while that
of local variables is restricted to a particular instantiation of a macro.
The following table ARM assembly directives are for setting local and global variables.
Directive Syntax Description
GBLA GBLA variable-name Defines a global arithmetic variable.
Values of arithmetic variables are 32-bit unsigned integers.

GBLL GBLL variable-name Defines a global logical variable.

GBLS GBLS variable-name Defines a global string variable.

LCLA LCLA variable-name Defines a local arithmetic variable with an initial state of 0.

LCLL LCLL variable-name Defines a local logical variable with an initial state of FALSE.

LCLS LCLS variable-name Defines a local string variable with an initial state of NULL string.
SETA variable-name SETA expression Sets the value of an arithmetic variable.

SETL variable-name SETL expression Sets the value of a logical variable.

SETS variable-name SETS expression Sets the value of a string variable.

Note that when you set the value of a string variable, you must use quotes.
You can declare local variables only from within a macro. In addition, after you declare a variable, you cannot use its name for
any other purpose.
The assembler substitutes values for some variables:
If a variable name has a $ character prefix, the assembler substitutes the variable value before it checks the line syntax.
If the variable is a logical or arithmetic variable, the assembler performs an .STR operation on the variable, and replaces
the variable with the result of the operation.
See Also
Other Resources
ARM Assembler Directives
Smart Device Development

ARM Assembler Directives for Macro Definition


Macros are useful when you need a group of instructions or directives frequently.
The ARM assembler replaces the macro name with its definition.
Macros can contain calls to other macros, nested up to 255 levels.
Two directives define a macro, MACRO and MEND.

MACRO
{$label} macroname {$parameter1}{,$parameter2}{,$parameter3}..
...code...
MEND

Remarks
A macro prototype statement must appear on the first line following the MACRO directive. The prototype tells the assembler
the name of the macro, macroname, and its parameters.
A label is optional, but is useful if the macro defines internal labels.
Any number of parameters can be used. Each must begin with $ to distinguish it from ordinary program symbols.
Within the macro body, $label, $parameter, and so on, can be used in the same way as other variables.
The $label parameter is treated as another parameter to the macro. The macro describes which labels are defined where. The
label does not represent the first instruction in the macro expansion.
For example, it is useful in a macro that uses several internal labels, such as a loop, to define each internal label as the base
label with a different suffix.
Sometimes, a value appends a macro parameter or label. Separate the appended value by a dot. After the assembler
recognizes the end of the parameter and label, the assembler ignores the dot. For example:

$label.1
$label.loop
$label.$count

Default values can be set for parameters by following them with an equal sign and the default value. If the default has a leading
or trailing space, the whole value should appear in quotes, as shown in the following code example.

...{$parameter="default value"}

The MEND directive signifies the end of the macro definition. If the macro contains WHILE/WEND loops, or contains
conditional assembly, the WHILE/WEND loop must close before execution reaches the MEND directive.
You can also terminate macro expansion with the MEXIT directive.
See Also
Other Resources
ARM Assembler Directives
Smart Device Development

Miscellaneous ARM Directives


The following table describes miscellaneous directives for the ARM assembler.
Dir Syntax Description
ecti
ve
ALI ALIGN {power-of- Sets the instruction location to the next word boundary.
GN two {,offset-exp
ression}} The optional power-of-two parameter can be used to align with a coarser byte boundary an
d the offset-expression parameter to define a byte offset from that boundary.

EN END Stops the processing of a source file.


D
If a GET directive invoked assembly of the file, the assembler returns and continues after the
GET directive.
If the assembler reaches an END directive in the top-level source file during the first pass an
d there are no errors, the second pass begins.
Absence of an END directive causes an error.

KEE KEEP {symbol} Retains a local symbol in the assembler's symbol table.
P
By default, the assembler does not describe local symbols in its output object file.
If the KEEP directive appears without a symbol parameter, the assembler keeps all symbols.
To keep a specific symbol, specify it by name.

LTO LTORG Directs the assembler to assemble the current literal pool that immediately follows the asse
RG mbly.
A default LTORG is executed at every END directive that is not part of a nested assembly.
Large programs might need several literal pools, each closer to the location of their literals t
o avoid violating LDR's 4-KB offset limit.

NO NOFP Disables floating point instructions.


FP
In some circumstances, there is no support in the target hardware or software for floating-p
oint instructions.

RLI label RLIST list Assigns a name to a set of registers to be transferred by LDM or STM.
ST -of-registers
List-of-registers is a comma-separated list of register names or ranges enclosed in braces.
If you select the -CheckReglist option, you must also supply a List-of-registers list, in increasi
ng order of register number.

RO {name}ROUT Marks the boundaries of the scope of local labels.


UT
name indicates the name to be assigned to the scope.
Use ROUT to limit the scope of local labels. This makes it easier for you to avoid referring to
a wrong label by accident. The scope of local labels is the whole area if there are no ROUT di
rectives in it.

SUB SUBT title Specifies a subtitle to be inserted on all pages until a new subtitle appears.
T
TTL TTL title Specifies a title to be inserted on all pages until a new title appears.

See Also
Other Resources
ARM Assembler Directives
Smart Device Development

ARM Assembler Error Messages


This section contains descriptions of the ARM Assembler error messages.
In This Section
ARM Error Messages 1-50
ARM Error Messages 51-100
ARM Error Messages 101-150
ARM Error Messages 151-200
ARM Error Messages 201-250
Smart Device Development

ARM Error Messages 1-50


The following table shows ARM error messages 1-150.
N Error Message Warning/Er Arguments
o. ror
1 Error None

2 :CHR: operator: truncation applied to a char Warning None

3 missing substitution operator $ for assembler variable Warning None


%s

4 reserved symbol used in an expression: %s Warning Symbol name

5 improper line syntax: %s Error Line with improper syntax

6 improper program syntax: %s Error Description of error

7 unimplemented class of instructions Error None

8 ARM register expected: %s Error String where the assembler tried to read a register

9 coprocessor number expected: %s Error String where the assembler tried to read a coprocess
or number

10 ARM coprocessor register expected: %s Error String where the assembler tried to read a coprocess
or register

11 ARM floating point register expected: %s Error String where the assembler tried to read a floating-p
oint register

12 wrong operand type for %s Error String with operand

13 divide by zero Error None

14 %s cannot be applied; different sections or different bas Error Text of operand


e registers

15 illegal symbol %s; AREA name expected Error None

15 illegal symbol %s; AREA name expected Error Symbol name

16 illegal flag(s) %s Error Token

17 illegal $ substitution, non assembler variable Error None

18 wrong character constant Error None

19 malformed string constant; missing closing Error None

19 malformed string constant; missing closing Error None


20 wrong escape constant; null value not permitted inside Error None
a string

20 wrong escape constant; null value not permitted inside Error None
a string

21 unexpected char Error None

22 wrong :: operator Error None

23 special bar id not closed Error None

24 wrong built-in variable Error None

25 wrong shift name Error None

26 unimplemented instruction set Error None

27 unaligned absolute value Warning None

28 truncation applied, absolute value should be word align Warning Offset value
ed: 0x%x

29 truncation applied, absolute value should be half-word Warning Offset value


aligned: 0x%x

30 address 0x%x is too large to represent in %d bits Error Address

31 address out of range in a different section Error None

32 immediate value %d cannot be represented in %d bits Error Offset

33 floating value %e cannot be represented in single precis Error Floating-point value


ion

34 undefined symbol: %s Error Symbol text

35 illegal expression type: %s Error Expression value

36 <%s> mnemonic qualifier is ignored Warning Instruction suffix

37 operand restriction violation (undefined behavior): %s Warning Instruction operand

38 multiple use of the same register in a register list Warning None

39 unsafe use of R15 as base register Warning None

40 unsafe use of write-back operator Warning None

41 unknown LDM/STM operation Error None

42 thumb register expected; %s Error Unexpected text


43 multiple symbol definition or incompatibility: %s Error Symbol name

44 cannot open file: %s Error File name

45 possible infinite loop due to recursive file inclusion: %s Warning File name

46 unknown command-line argument or argument value Warning Unknown argument


%s

47 command-line option not implemented; %s ignored Warning Command-line argument

48 multiple use of the same option: %s Warning Command-line argument

49 only one source file can be assembled: %s Error Source file name

50 missing input source file Error None


See Also
Other Resources
ARM Assembler Error Messages
Smart Device Development

ARM Error Messages 51-100


The following table shows ARM error messages 51-100.
N Error Message Warning/ Arguments
o. Error
51 unknown opcode: %s Error String for OPCODE

52 minimum requested width of 34 assumed Warning None

53 wrong page length: %d, 0 (non paged) assumed Warning Page length

54 failed to close file %s Error File name

55 illegal line start symbol: %s for directive: %s Error Start symbol, directive

56 unimplemented directive %s Warning Directive name

57 %s attribute does not pertain to a relocatable module; ignored Warning Directive name

58 %s directive does not pertain to a relocatable module; ignored Warning Directive name

59 unknown section flag: %s Error Area name

60 illegal combination of section flags: %s Warning Section name and flags

61 redefinition of section flags ignored Warning None

62 ignored lines after END directive Warning None

63 missing END directive Warning None

64 code inside data section Error None

65 unknown or bad symbol type: %s Error Symbol

66 out of memory: section data: no object file will be generated Error None

66 out of memory: section data: no object file will be generated Error None

67 initialized data in an uninitialized data section %s Error None

68 assembler internal error; sync. error on local labels Error None

68 assembler internal error; sync. error on local labels Error None

69 error while generating object file: seek error Error None

69 error while generating object file: seek error Error None

70 input error: line is too long after expanding an assembler variable; truncated Error None
70 input error: line is too long after expanding an assembler variable; truncated Error None

71 macro error: END directive cannot appear inside a macro Error None
71 macro error: END directive cannot appear inside a macro Error None

72 wrong directive usage: local assembler variables can only be defined within Error None
a macro

73 wrong local label reference; reference expected after %% (usage: %%{x}{y}n{ Error None
name})

74 improper argument for <-predefine> command-line option: %s; %s Error None

75 non increasing order in the register list Warning None

76 the selected architecture and CPU (or mode) are conflicting: %s versus %s Warning Architecture, CPU

77 could not delete %s file Error File name

78 missing ENDP directive in section %s Error Section name

79 %s Error Internal use

80 %s %s Error Internal use

81 error Error None

82 warning Warning None

83 illegal expression type; expected absolute numeric Error None

84 illegal expression type; expected absolute numeric or program relative Error None

85 illegal expression type; expected absolute numeric, program relative or regis Error None
ter relative

86 illegal expression type; expected program relative or register relative Error None

87 illegal expression type; expected program relative Error None

88 illegal expression type; expected absolute numeric or string Error None

89 illegal expression type; expected absolute numeric or Boolean Error None

90 illegal expression type; expected bool Error None

91 illegal expression type; expected string Error None

92 no immediate rotate operand can be created: %d Error Values to rotate

93 immediate value %d out of range; expected values: %s Warning Immediate value, string contain ex
pected values
94 improper alignment value %d; expected: [1, 2, 4, 8, ... 32768] Error Value

95 improper alignment value %d; alignment offset should be positive and smal Warning Value
ler than alignment; truncated

96 immediate value %d out of range; positive value expected Error Immediate value

97 immediate value %d out of range; truncated to 16 bits Warning Immediate value

98 immediate value %d out of range; truncated to 8 bits Warning Immediate value

99 literal pool too far, or too close: %d; address is 8 bit offset; use LTORG Error None

10 literal pool too far, or too close: %d; address is 12 bit offset; use LTORG Error None
0
See Also
Other Resources
ARM Assembler Error Messages
Smart Device Development

ARM Error Messages 101-150


The following table shows ARM error messages 101-150.
N Error Message Warning/E Arguments
o. rror
10 improper shift amount: %d; must fit in 5 bits Error Immediate value
1

10 improper rotate amount: %d; rotate amount shifted right by 1 must fit 4bits Error Immediate value
2

10 improper rotate amount: %d; only even rotate amounts can be specified Error Immediate value
3

10 immediate value out of range: %d; coprocessor information must fit in 3 bits Error Immediate value
4

10 immediate value out of range: %d; coprocessor opcode must fit in 4 bits Error Immediate value
5

10 internal assembler error: unused error code Error None


6

10 improper line syntax, only <ldr> can be used to generate literals Error None
7

10 improper line syntax Error None


8

10 improper line syntax; EOL or comma expected Error None


9

11 improper line syntax; wrong offset Error None


0

11 improper line syntax; expected: %s Error Expected tokens for prope


1 r syntax

11 improper line syntax; SP or PC required as second register in this format Error None
2

11 improper line syntax; high registers are not accepted for SUB instruction Error None
3

11 improper line syntax; only SP register accepted for this format Error None
4

11 improper line syntax; unexpected comma Error None


5

11 improper line syntax; high registers not allowed in this context Error None
6
11 improper line syntax; wrong combination of mnemonic and operands Error None
7

11 improper line syntax; write back '!', expected (assumed) Error None
8

11 improper line syntax; opcode, directive or macro call expected Error None
9

12 improper line syntax; wrong use of a local label Error None


0

12 improper line syntax; %s directive cannot define a starting line symbol Error Directive name
1

12 improper line syntax; symbol expected Error None


2

12 improper line syntax; missing weak alias; symbol defined as external Warning None
3

12 improper line syntax; include file name expected Error None


4

12 improper line syntax; string expected Warning None


5

12 improper line syntax; %s option requires %s section name Warning Option, section name
6

12 improper line syntax; usage: %s Warning Line


7

12 improper line syntax; selection must be 5 if <assoc= ..> option is used Warning None
8

12 improper line syntax; bad macro call; macro definition does not have a label parame Warning None
9 ter

13 improper line syntax; macro call with too many actual parameters Warning None
0

13 improper line syntax; malformed macro call Warning None


1

13 improper line syntax; register list symbol or proper register list ({ .. }) expected Error None
2

13 improper line syntax; malformed register list construction Error None


3

13 improper line syntax; Error None


4
13 improper line syntax; Error None
5

13 improper line syntax; Error None


6

13 unexpected end of file in an include file/macro or missing END directive Error None
7

13 improper program syntax; missing ENDP directive or nested function definition Warning None
8

13 improper program syntax; unexpected ENDP directive Warning None


9

14 improper program syntax; unexpected MEND/MEXIT directive Warning None


0

14 improper program syntax; conditional if structure crosses file (include) structure Warning None
1

14 improper program syntax; (malformed/not closed) conditional if structure appears Error None
2

14 improper program syntax; end of file or macro in WHILE loop, or missing WEND Error None
3

14 improper program syntax; a WEND directive without a preceding WHILE Error None
4

14 improper program syntax; unbalanced WHILE-WEND construction, possibly due to Warning None
5 conditionals and includes

14 improper program syntax; an ENDIF directive without a corresponding IF Error None


6

14 improper program syntax; an ELSE directive without a corresponding IF Error None


7

14 improper program syntax; malformed conditional structure, possibly two ELSE key Error None
8 words in an IF construct

14 improper program syntax; nested macro definitions are not supported Error None
9

15 improper program syntax; read error or missing macro definition line Error None
0
See Also
Other Resources
ARM Assembler Error Messages
Smart Device Development

ARM Error Messages 151-200


The following table shows ARM error messages 151-200.
N Error Message Warning/E Arguments
o. rror
15 improper program syntax; MEND, MEXIT directives do not have any label or prefixing text Warning None
1

15 improper program syntax; read error, missing MEND directive or end of file inside a macro d Error None
2 efinition

15 improper program syntax; malformed macro definition (unrecoverable) Error None


3

15 improper program syntax; associated COMDAT section not found Error None
4

15 improper program syntax; attempt to redefine the associated COMDAT section; ignored Error None
5

15 routine name does not match the enclosing routine structure Error None
6

15 improper argument for <-predefine> command-line option: name expected Error None
7

15 improper argument for <-predefine> command-line option: %s; symbol name expected Error Command-line o
8 ption

15 improper argument for <-predefine> command-line option: SETx expected Error None
9

16 improper argument for <-predefine> command-line option; undefined symbol in expression Error None
0

16 improper argument for <-predefine> command-line option: malformed or unrecognized ex Error None
1 pression

16 improper argument for <-predefine> command-line option: expression type mismatch Error None
2

16 assembler internal error; Sync. error on ROUT areas Error None


3

16 assembler internal error; symbol sync. error in function symbol line numbers Error None
4

16 assembler internal error; address sync. error in function symbol line numbers Error None
5

16 assembler internal error; INCLUDE path cannot be created, check INCLUDE env. variable and Warning None
6 <-i> command-line option
16 assembler internal error; source input sync. error; bad use of include or macros Error None
7

16 assembler internal error; bad input stack Error None


8

16 assembler internal error; bad macro structure in token input Error None
9

17 assembler internal error; section raw data area exceeded Error None
0

17 assembler internal error; PC sync error while generating literal pool Error None
1

17 ROUT tag of a local label does not match the enclosed ROUT name Error None
2

17 unknown command-line argument or argument value; error file name expected Error None
3

17 unknown command-line argument or argument value; include path expected Error None
4

17 unknown command-line argument or argument value; list file name expected Error None
5

17 unknown command-line argument or argument value; obj file name expected Error None
6

17 unknown command-line argument or argument value; width value expected Error None
7

17 unknown command-line argument or argument value; length value expected Error None
8

17 unknown command-line argument or argument value; SET directive expected Error None
9

18 unknown command-line argument or argument value; <-via> file name expected Error None
0

18 wrong string constant; $ character must be doubled Error None


1

18 attribute does not pertain to a relocatable module; ignored, weak expected Error None
2

18 multiple symbol definition or incompatibility; weak alias must be external Error None
3

18 multiple symbol definition or incompatibility; procedure name must have address 0 if it is an Error None
4 area COMDAT symbol
18 multiple symbol definition or incompatibility; multiple definitions of section COMDAT symbo Error None
5 l as function name

18 multiple symbol definition or incompatibility; an assembler variable cannot be exported; exp Error None
6 ort attribute deleted

18 multiple symbol definition or incompatibility; a register relative symbol cannot be exported; Error None
7 export attribute deleted

18 multiple symbol definition or incompatibility; program counter symbol cannot be exported; e Error None
8 xport attribute deleted

18 multiple symbol definition or incompatibility; a string symbol cannot be exported; export attr Error None
9 ibute deleted

19 multiple symbol definition or incompatibility; truncation possible on a float absolute exporte Error None
0 d symbol

19 illegal symbol %s; a built-in variable cannot be used as a COMDAT symbol; ignored Error Symbol
1

19 illegal symbol %s; COMDAT symbol name expected Warning Symbol


2

19 illegal symbol %s; AREA attribute expected Error Symbol


3

19 illegal symbol %s; expected : '=' Error Symbol


4

19 illegal symbol %s; has no type Error Symbol


5

19 illegal symbol %s; wrong type Error Symbol


6

19 illegal symbol %s; absolute value expected Error Symbol


7

19 MEND directive before a proper macro definition Error None


8

19 illegal symbol %s; bad macro name Error Symbol


9

20 illegal symbol %s; < argument > expected Error Symbol


0
See Also
Other Resources
ARM Assembler Error Messages
Smart Device Development

ARM Error Messages 201-250


The following table shows ARM error messages 201-242.

N Error Message Warnin Arguments


o. g/Error

2 illegal symbol %s; null macro formal parameter Error Symbol


0
1

2 illegal symbol %s; initialization string expected Error Symbol


0
2

2 illegal macro syntax: %s; comma or end of line expected Error Line
0
3

2 illegal macro syntax: %s; improper component of a macro definition Error Line
0
4

2 illegal symbol %s; macro name multiply defined Error Symbol


0
5

2 illegal symbol %s; unknown token Error Symbol


0
6

2 illegal symbol %s; duplicate formal parameter; ignored Warnin Symbol


0 g
7

2 wrong expression operand: %d; positive value expected Error Value in expression
0
8

2 built-in variable not implemented yet Error None


0
9

2 error while reading input file: input stack overflow, possible infinite recursion o Error None
1 n file include or macro calls
0

2 error while reading input file: seek error Error None


1
1

2 error while reading input file: line too long on input file Error None
1
2
2 error while reading input file: macro expanded line too long Error None
1
3

2 error while reading input file: input stack overflow, possible infinite recursion o Error None
1 n file include or macro calls
4

2 malformed escape constant; too many characters Error None


1
5

2 malformed constant; unknown escape sequence Error None


1
6

2 error while generating object file: write error Error None


1
7

2 assertion failed Error None


1
8

2 the selected architecture and CPU (or mode) are conflicting %s; BX instruction Error None
1 not defined for this architecture
9

2 the selected architecture and CPU (or mode) are conflicting; <Thumb Area opti Warnin None
2 on> and <command-line arch: not 4T> g
0

2 illegal flag(s); only <cpsr_f> or <spsr_f> can be used with immediate value Warnin None
2 g
1

2 operand restriction violation (undefined behavior): same source and dest reg Warnin None
2 g
2

2 operand restriction violation (undefined behavior): same base and offset reg Warnin None
2 g
3

2 mnemonic qualifier is ignored; suffix following <ldr> Warnin None


2 g
4

2 command-line option not implemented; %s assumed; %s ignored Warnin Command-line argument that is ass
2 g umed, or that is not implemented
5

2 illegal combination of section flags: section flags cannot be inferred, code and Warnin None
2 data/uninitialized, readonly/readwrite g
6
2 syntax error in expression Error None
2
7

2 assembler internal error: stack overflow in expression Error None


2
8

2 expression; %s Error Expression string


2
9

2 condition codes are not accepted for this form of blx instruction; cc ignored Warnin None
3 g
0

2 unknown floating point system register: %s; expected: FPSID, FPSCR or FPEXC Error String with floating register
3
1

2 wrong floating point register list; a compact group of registers is expected Error None
3
2

2 the maximum amount of transfer is 16 words Warnin None


3 g
3

2 improper line syntax; expected comma Error None


3
4

2 Improper syntax: s must follow condition code Error None


3
5

2 fldmdb|fstmdb require increment flag on first register Error None


3
6

2 The destination register must be even Warnin None


3 g
7

2 The use of r15 (pc) has unpredictable results Warnin None


3 g
8

2 Accumulator values greater than zero not supported Warnin None


3 g
9

2 cpu argument (%s) not supported Error Argument


4
0
2 Instruction %s not supported for -cpu %s Error None
4
1

2 -cpu option overriding -arch option Warnin None


4 g
2

2 The following usage is no longer supported : armasm [<options>] sourcefile Warnin None
4 objectfile\n g
3 Please use the ""-o"" option:
armasm [<options>] -o objectfile sourcefile\n

2 Use of undefined symbol %s in EQU expression Warnin Symbol


4 g
4

2 Literal pool entry could not be found in second pass. Check to make sure the e Error None
4 xpression and all dependent symbols are fully defined before their use.
5
See Also
Other Resources
ARM Assembler Error Messages
Smart Device Development

Renesas Family Processors


Renesas Technology designs and manufactures high-performance, power-efficient RISC microprocessors.
The Renesas SuperH SH-4 RISC core uses a fixed 16-bit instruction length for improved efficiency, load-store architecture with
16 32-bit general-purpose registers, and a 5-stage pipeline that executes one instruction per clock cycle.
Renesas optimizes each processor family for specific applications.
In This Section
Intrinsic Functions for Renesas Microprocessors

Provides reference information about intrinsic functions.


Renesas Compiler Options
Provides reference information about compiler and linker options available only to Renesas microprocessors.
Renesas SH-4 Calling Sequence Specification
Provides information about assemblers, register assignments, and stack layout.
Related Sections
Differences Between Desktop and Device Compilers
Provides a comparative reference for compiler options and intrinsic functions.
Smart Device Development

Intrinsic Functions for Renesas Microprocessors


The Renesas SH-4 microprocessor includes a number of functions that you can use intrinsically for faster programs. These
functions aid mathematical computations.
Programs that use intrinsic functions do not have the overhead of function calls, but they can be larger because of the
additional code created.
To replace functions with their intrinsic (inline) forms, use the /Oi (Generate Intrinsic Functions) option or the #pragma
intrinsic.
The following table shows SH-4 microprocessor assembly language functions implemented as intrinsic functions.
SH-4 instructio Description
n
_Convolve Computes the summation of two vectors.

_Dot3dVW0 Computes the inner product of a pair of three- or four-dimensional vectors with the "w" coordinate forced to
0.

_Dot3dVW1 Computes the inner product of a pair of three- or four-dimensional vectors with the "w" coordinate forced to
1.

_Dot4dV Computes the inner product of a pair of four-dimensional vectors.

__fmac Multiplies two float values and adds to a third float value.

_LoadMatrix Loads a 4x4 matrix into the extended floating-point register bank.

__movca Moves with cache block allocation.

_Multiply4dM Multiplies a 4x4 matrix by a 4x4 matrix.

_SaveMatrix Stores the extended floating-point register bank into a 4x4 matrix.

_XDMultMatrix Multiplies a 4x4 matrix by a 4x4 matrix.

_XDXform3dV Multiplies a three-dimensional vector by a 3x3 matrix.

_XDXform4dV Multiplies a four-dimensional vector by a 4x4 matrix.

_Xform3dV Multiplies a three-dimensional vector by a 3x3 matrix.

_Xform4dV Multiplies a four-dimensional vector by a 4x4 matrix.


See Also
Other Resources
Renesas Family Processors
Smart Device Development

__fmac
Multiplies two float values and add to a third float value.

Float __fmac(
float Arg1,
float Arg1,
float Arg1
);

Parameters
Arg1
[in] First operand of the multiplication operation.
Arg2
[in] Second operand of the multiplication operation.
Arg3
[in] Value to which the product of Arg1and Arg2 is added.
Return Values
The sum of the product of Arg1 and Arg2 with Arg3.
Remarks
The following code example shows how to use _fmac.

/***********************************************************/
#include <stdio.h>
#include <shintr.h>
void main()
{
int i;
float sum=0;
float v1[4] = {2.0, 2.0, 2.0, 2.0};
float v2[4] = {8.0, 8.0, 8.0, 8.0};
for (i = 0; i < 4; i++)
sum = __fmac(v1[i], v2[i], sum);
printf("sum = %f\n", sum);
}

This example results in the following output.

sum = 64.000000

Requirements
Routine Required header Architecture
__fmac <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
Smart Device Development

__movca
Move with cache block allocation.

void __movca(
unsigned long value,
unsigned long* addr
);

Parameters
value
[in] Specifies longword to store in memory.
addr
[in] Address in memory to be accessed.
Return Values
None.
Remarks
The following code example shows how to use _prefetch with _moveca.

#include <stdio.h>
#include <shintr.h>

#pragma intrinsic(__prefetch, __movca)


void main()
{
unsigned long addr[1]={0xffff};
unsigned long value = 0x100;
//
printf("before prefetch addr value = %x\n", addr[0]);
//
__prefetch(addr);
printf("after prefetch addr value = %x\n", addr[0]);
if (addr[0] != 0xffff)
printf("error\n");
__movca(value, addr);
printf("after movca addr value = %x\n", addr[0]);

if (addr[0] != value)
printf("error\n");
}

This example results in the following output.

before prefetch addr value = ffff


after prefetch addr value = ffff
after movca addr value = 100

Requirements
Routine Required header Architecture
__movca <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_prefetch
Smart Device Development

_Convolve
Computes the summation of two vectors.

Float _Convolve(
int nelement,
float* pstart,
float* pend,
float* pdata,
float* pfilter
);

Parameters
nelement
[in] Number of elements to be processed.
pstart
[in] Pointer to the beginning of data buffer.
pend
[in] Pointer to the end of data buffer.
pdata
[in] Pointer to the current data buffer.
pfilter
[in] Pointer to the filter buffer.
Return Values
The summation of two vectors.
Remarks
The pdata parameter can point to any position in the data buffer. The pfilter parameter can point to any position in the filter
buffer. The nelement parameter must not exceed pfilter+nelement buffer size.
To implement this function, use the -Qsh4 -Oi flag when compiling.
The following code example shows how to use _Convolve.

/*****************************************************************
_Convolve: summation of two vector

pstart | A0 | pfilter | X0 |
| A1 | | X1 |
| .. | | .. |
pdata | Ai | | .. |
| .. | | .. |
pend | An | | Xn |

For example:

nelement = 4;
result = (Ai * X3) + (Ai+1 * X2) + (Ai+2 * x1) + (Ai+3 * x0)
nelement = n+i;
result = (Ai * Xn) + (Ai+1 * Xn-1) + .. + (Ai-1 * X0)

*****************************************************************/
#include <stdio.h>
#include <shintr.h>
#include <stdio.h>

void main()
{
float pdata[5] = {1.0,2.0,3.0,4.0,5.0};
float filter[5] = {1.0,2.0,3.0,4.0,5.0};
float output;
float *pstart = pdata;
float *pend = pdata+4;
output = _Convolve(5, pstart, pend, pdata, filter);
printf("output = %f\n", output);
output = _Convolve(5, pstart, pend, pdata+1, filter);
printf("output = %f\n", output);

output = _Convolve(5, pstart, pend, pdata+2, filter);


printf("output = %f\n", output);
output = _Convolve(5, pstart, pend, pdata+3, filter);
printf("output = %f\n", output);

output = _Convolve(5, pstart, pend, pdata+4, filter);


printf("output = %f\n", output);

Output

output = 35.000000
output = 45.000000
output = 50.000000
output = 50.000000
output = 45.000000

Requirements
Routine Required header Architecture
_Convolve <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
Smart Device Development

_Dot3dVW0
Computes the inner product of a pair of three or four-dimensional vectors with the "w" coordinate forced to 0.

float _Dot3dVW0(
float* vector1,
float* vector2
);

Parameters
Vector1
[in] Pointer to a three or four-dimensional source vector.
Vector2
[in] Pointer to a three or four-dimensional destination vector.
Return Values
The scalar resulting from the inner product.
Remarks
The fourth coordinate of a source vector will always force to 0.
To implement this function, use the /Qsh4 /Oi (Generate Intrinsic Functions) flag when compiling.
The following code example shows how to use Dot3dVW0 to compute the inner products of three or four dimensional
vectors.

/***********************************************************/
#include <stdio.h>
#include <shintr.h>
void main()
{
float result;
float v1[4]={1.0,2.0,3.0,4.0};
float v2[4]={2.0,3.0,4.0,5.0};
result = _Dot3dVW0(v1,v2);
/***********************************************************/
printf("result=%f\n", result);
}

This example results in the following output.

retval=20.000000

Requirements
Routine Required header Architecture
_Dot3dVW0 <shintr.h> SH-4
See Also
Reference
_Dot4dV
_Dot3dVW1
Intrinsic Functions for Renesas Microprocessors
Smart Device Development

_Dot3dVW1
Computes the inner product of a pair of three or four-dimensional vectors with the "w" coordinate forced to 1.

float _Dot3dVW1(
float* vector1,
float* vector2
);

Parameters
vector1
[in] Pointer to a three or four-dimensional source vector.
vector2
[in] Pointer to a three or four-dimensional destination vector.
Return Values
The scalar resulting from the inner product.
Remarks
The fourth coordinate of the source vector will always force to 1.
To implement this function, use the -QSh4 /Oi (Generate Intrinsic Functions) flag when compiling.
The following code example shows how to compute the inner products of three or four dimensional vectors.

/***********************************************************/
#include <stdio.h>
#include <shintr.h>
void main()
{
float retval;
float v1[3] = {1.0, 2.0, 3.0};
float v2[3] = {2.0, 3.0, 4.0};
retval = _Dot3dVW1(v1, v2);
/***********************************************************/
printf("retval=%f\n", retval);
}

This example results in the following output.

retval=21.000000

Requirements
Routine Required header Architecture
_Dot3dVW1 <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_Dot4dV
_Dot3dVW0
Smart Device Development

_Dot4dV
Computes the inner product of a pair of four-dimensional vectors.

float _Dot4dV(
float* vector1,
float* vector2
);

Parameters
vector1
[in] Pointer to a four-dimensional source vector.
vector2
[in] Pointer to a four-dimensional destination vector.
Return Values
The scalar resulting from the inner product.
Remarks
The following code example shows how to compute the inner product of four-dimensional vectors.

/***********************************************************/
#include <stdio.h>
#include <shintr.h>
void main()
{
float retval;
float v1[4] = {1.0, 2.0, 3.0, 4.0};
float v2[4] = {2.0, 3.0, 4.0, 5.0};
retval = _Dot4dV(v1, v2);
printf("retval=%f\n", retval);
}

This example results in the following output.

retval=40.000000

Requirements
Routine Required header Architecture
_Dot4dV <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_Dot3dVW0
_Dot3dVW1
Smart Device Development

_LoadMatrix
Loads a 4x4 matrix into the extended floating-point register bank.

float* _LoadMatrix(
float* matrix
);

Parameters
matrix
[in] Pointer to an array of float values arranged such that the indices of the array are the [row][column] values of the 4x4
matrix.
Return Values
Pointer to the 4x4 matrix that has been loaded.
Remarks
The following code example shows how to use _LoadMatrix.

#include <stdio.h>
#include <shintr.h>

void main()
{
int i,j;
float result[4][4];
// #########################################################
float m1[4][4] = {1.0,1.0,1.0,1.0,
2.0,2.0,2.0,2.0,
3.0,3.0,3.0,3.0,
4.0,4.0,4.0,4.0};
// #########################################################
float m2[4][4] = {2.0,2.0,2.0,2.0,
2.0,2.0,2.0,2.0,
2.0,2.0,2.0,2.0,
2.0,2.0,2.0,2.0};
// #########################################################
_LoadMatrix(m1); //Load m1 matrix into XD bank regs
_XDMultMatrix(m2); //[m1]x[m2] Saved result into XD bank regs
_SaveMatrix(result); //Load XD bank regs into result buffer

// Print out result


printf("Result of [m1]x[m2] = \n");
for (i = 0; i < 4; i++)
{
printf("| ");
for (j =0; j < 4; j++)
printf("%8.4f ", result[i][j]);
printf(" |\n");
}
}

This example results in the following output.

Result of [m1]x[m2] =
| 8.0000 8.0000 8.0000 8.0000 |
| 16.0000 16.0000 16.0000 16.0000 |
| 24.0000 24.0000 24.0000 24.0000 |
| 32.0000 32.0000 32.0000 32.0000 |
Requirements
Routine Required header Architecture
_LoadMatrix <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_SaveMatrix
Smart Device Development

_Multiply4dM
Multiplies a 4x4 matrix by a 4x4 matrix.

float* _Multiply4dM(
float* result,
float* matrix1,
float* matrix2
);

Parameters
result
[out] Pointer to an array of float values arranged such that the indices of the array are the [row][column] values of the 4x4
matrix. This matrix receives the result of the operation.
matrix1
[in] Pointer to an array of float values arranged such that the indices of the array are the [row][column] values of the 4x4
matrix.
matrix2
[in] Pointer to an array of float values arranged such that the indices of the array are the [row][column] values of the 4x4
matrix.
Return Values
Pointer to the 4x4 result matrix.
Remarks
The following code example shows how to use _Multiply4DM.

void main()
{
int i,j;
float result[4][4];
float m1[4][4] = {1.0,1.0,1.0,1.0,
2.0,2.0,2.0,2.0,
3.0,3.0,3.0,3.0,
4.0,4.0,4.0,4.0};
float m2[4][4] = {2.0,2.0,2.0,2.0,
2.0,2.0,2.0,2.0,
2.0,2.0,2.0,2.0,
2.0,2.0,2.0,2.0};
Multiply4dM(result, m1, m2);
printf("Result of [m1]x[m2] = \n");
for (i = 0; i < 4; i++)
{
printf("| ");
for (j = 0; j < 4; j++)
printf("%8.4f ",result[i][j]);
printf(" |\n");
}
}

Output

Result of [m1]x[m2] =
| 8.0000 8.0000 8.0000 8.0000 |
| 16.0000 16.0000 16.0000 16.0000 |
| 24.0000 24.0000 24.0000 24.0000 |
| 32.0000 32.0000 32.0000 32.0000 |

Requirements
Routine Required header Architecture
_Multiply4dM <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_XDMultMatrix
Smart Device Development

_SaveMatrix
Stores the extended floating-point register bank into a 4x4 matrix.

float* _SaveMatrix(
float* matrix
);

Parameters
matrix
[out] Pointer to an array of float values arranged such that the indices of the array are the [row][column] values of the 4x4
matrix.
Return Values
Pointer to the 4x4 matrix that has been stored.
Remarks
The following code example shows how to use _SaveMatrix.

void main()
{
int i,j;
float result[4][4];
float m1[4][4] = {1.0,1.0,1.0,1.0,
2.0,2.0,2.0,2.0,
3.0,3.0,3.0,3.0,
4.0,4.0,4.0,4.0};

float m2[4][4] = {2.0,2.0,2.0,2.0,


2.0,2.0,2.0,2.0,
2.0,2.0,2.0,2.0,
2.0,2.0,2.0,2.0};

_LoadMatrix(m1); //Load m1 matrix into XD bank regs


_XDMultMatrix(m2); //[m1]x[m2] —> result saved into XD bank regs
_SaveMatrix(result); //Load XD bank regs into result buffer
//
// Print out the result
//
printf("Result of [m1]x[m2] = \n");
for (i = 0; i < 4; i++)
{
printf("| ");
for (j = 0; j < 4; j++)
printf("%8.4f ",result[i][j]);
printf(" |\n");
}

_XDMultMatrix(m2); //[m1]x[m2]x[m2]->saved results into XD bank


_SaveMatrix(result); //Load XD bank regs into result buffer

//
// Print out the result
//
printf("\nResult of [m1]x[m2]x[m2] = \n");
for (i = 0; i < 4; i++)
{
printf("| ");
for (j = 0; j < 4; j++)
printf("%8.4f ",result[i][j]);
printf(" |\n");
}
}

Output

Result of [m1]x[m2] =
| 8.0000 8.0000 8.0000 8.0000 |
| 16.0000 16.0000 16.0000 16.0000 |
| 24.0000 24.0000 24.0000 24.0000 |
| 32.0000 32.0000 32.0000 32.0000 |

Result of [m1]x[m2]x[m2] =
| 64.0000 64.0000 64.0000 64.0000 |
| 128.0000 128.0000 128.0000 128.0000 |
| 192.0000 192.0000 192.0000 192.0000 |
| 256.0000 256.0000 256.0000 256.0000 |

Requirements
Routine Required header Architecture
_SaveMatrix <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_LoadMatrix
Smart Device Development

_XDMultMatrix
Multiplies a 4x4 matrix by a 4x4 matrix. This instruction requires one of the matrices to have been previously loaded into the
extended floating-point register bank. The matrix passed as the parameter receives the result of the operation.

void _XDMultMatrix(
float* matrix
);

Parameters
matrix
[in, out]Pointer to an array of float values arranged such that the indices of the array are the [row][column] values of the 4x4
matrix.
Return Values
None.
Requirements
Routine Required header Architecture
_XDMultMatrix <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_Multiply4dM
_LoadMatrix
_SaveMatrix
Smart Device Development

_XDXform3dV
Multiplies a three-dimensional vector by a 3x3 matrix. This instruction requires that the matrix has been previously loaded into
the extended floating-point register bank.

float* _XDXform3dV(
float* src,
float* dst
);

Parameters
src
[in] Pointer to a three-dimensional source vector.
dst
[out] Pointer to a three-dimensional destination vector.
Return Values
A pointer to the three-dimensional destination vector.
Remarks
The following code shows how to use _XDXform3dV.

void print_matrix(float *matrix, float *src, float *dest)


{
int row, col;

printf("Matrix:\t\t\tSrc:\tDest:\n");

for (row = 0; row < 3; row++)


{
printf("| ");
for (col = 0; col < 3; col++)
{
printf("%6.2f", *matrix++);
}
printf(" |");
printf(" |%6.2f|", *src++);
printf(" |%10.4f|\n", *dest++);
}
}

void main()
{
int i;
float dest[6];

float src[6] = {1.0,2.0,3.0,


4.0,5.0,6.0,};

float matrix[16]= {1.0, 2.0, 3.0, 4.0,


5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0};

_LoadMatrix(matrix); //Load matrix into XD bank registers


for (i = 0; i < 6; i +=3)
_XDXform3dV(src+i, dest+i); //[matrix]x[src[i]] --> dest[i]
print_matrix(matrix, src, dest);
printf("\n");
print_matrix(matrix, src+3, dest+3);
}

Output

Matrix: Src: Dest:


| 1.00 2.00 3.00 | | 1.00| | 14.0000|
| 4.00 5.00 6.00 | | 2.00| | 38.0000|
| 7.00 8.00 9.00 | | 3.00| | 62.0000|
Matrix: Src: Dest:
| 1.00 2.00 3.00 | | 4.00| | 32.0000|
| 4.00 5.00 6.00 | | 5.00| | 92.0000|
| 7.00 8.00 9.00 | | 6.00| | 152.0000|

Requirements
Routine Required header Architecture
_XDXform3dV <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_Xform3dV
_Xform4dV
_XDXform4dV
_LoadMatrix
_SaveMatrix
Smart Device Development

_XDXform4dV
Multiplies a four-dimensional vector by a 4x4 matrix. This instruction requires that the matrix has been previously loaded into
the extended floating-point register bank.

float* _XDXform4dV(
float* src,
float* dst
);

Parameters
src
[in] Pointer to a three-dimensional source vector.
dst
[out] Pointer to a three-dimensional destination vector.
Return Values
Pointer to the four-dimensional destination vector.
Remarks
The following code shows how to use _XDXform4dV.

#pragma intrinsic(_XDXform4dV, _LoadMatrix)


void print_matrix(float *matrix, float *src, float *dest)
{
int row, col;
printf("Matrix:\t\t\t\tSrc:\tDest:\n");

for (row = 0; row < 4; row++)


{
printf("| ");
for (col = 0; col < 4; col++)
printf("%6.2f", *matrix++);
printf(" |");
printf(" |%6.2f|", *src++);
printf("\t|%10.4f|\n", *dest++);
}
}

void main()
{
int i;
float dest[8];
float src[8] = {1.0, 2.0 ,3.0, 4.0,
5.0, 6.0, 7.0, 8.0};

float matrix[16]={ 1.0, 2.0, 3.0, 4.0,


5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0};
LoadMatrix(matrix); //Load matrix into XD bank registers

for (i = 0; i < 8; i +=4)


XDXform4dV(src+i, dest+i); //[matrix]x[src[i]] --> dest[i]
print_matrix(matrix, src, dest);
printf("\n");
print_matrix(matrix, src+4, dest+4);
}

Output

Matrix: Src: Dest:


| 1.00 2.00 3.00 4.00 | |
1.00 | | 30.0000|
| 5.00 6.00 7.00 8.00 | |
2.00 | | 70.0000|
| 9.00 10.00 11.00 12.00 | |
3.00 | | 110.0000|
| 13.00 14.00 15.00 16.00 | |
4.00 | | 150.0000|
Matrix: Src: Dest:
| 1.00 2.00 3.00 4.00 | | 5.00| | 70.0000|
| 5.00 6.00 7.00 8.00 | | 6.00| | 174.0000|
| 9.00 10.00 11.00 12.00 | | 7.00| | 278.0000|
| 13.00 14.00 15.00 16.00 | | 8.00| | 382.0000|

Requirements
Routine Required header Architecture
_XDXform4dV <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_Xform3dV
_Xform4dV
_LoadMatrix
_SaveMatrix
Smart Device Development

_Xform3dV
Multiplies a three-dimensional vector by a 3x3 matrix. This intrinsic will load a constant zero into Bank1 floating-point registers
(fr12, fr13, fr14, fr15) and Bank0 floating-point register (fr3).

float* _Xform3dV(
float* dst,
float* src,
float* matrix
);

Parameters
dst
[out] Pointer to a three-dimensional destination vector.
src
[in] Pointer to a three-dimensional source vector.
matrix
[in] Pointer to an array of float values arranged such that the indices of the array are the [row][column] values of the 3x3
matrix.
Return Values
Pointer to the three-dimensional destination vector.
Remarks
The following code shows how to use _Xform3dV.

void print_matrix(float *matrix, float *src, float *dest)


{
int row, col;

printf("Matrix:\t\t\tSrc:\tDest:\n");
for (row = 0; row < 3; row++)
{
printf("| ");
for (col = 0; col < 3; col++)
{
printf("%6.2f", *matrix++);
}
printf(" |");
printf(" |%6.2f|", *src++);
printf("\t|%10.4f|\n", *dest++);
}
}
void main()
{
int i;
float dest[3];
float src[3] = {1.0, 2.0, 3.0}

float matrix[9]={1.0, 2.0, 3.0,


4.0, 5.0, 6.0,
7.0, 8.0, 9.0};

_Xform3dV(dest, src, matrix); // [matrix]x[src[i]] à dest[i]


print_matrix(matrix, src, dest);
}
Output
Matrix: Src: Dest:
| 1.00 2.00 3.00 | | 1.00| | 14.0000|
| 4.00 5.00 6.00 | | 2.00| | 32.0000|
| 7.00 8.00 9.00 | | 3.00| | 50.0000|

Requirements
Routine Required header Architecture
_Xform3dV <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_Xform4dV
_XDXform4dV
_XDXform3dV
_LoadMatrix
_SaveMatrix
Smart Device Development

_Xform4dV
Multiplies a four-dimensional vector by a 4x4 matrix.

float* _Xform4dV(
float* dst,
float* src,
float* matrix
);

Parameters
dst
[out] Pointer to a four-dimensional destination vector.
src
[in] Pointer to a four-dimensional source vector.
matrix
[in] Pointer to an array of float values arranged such that the indices of the array are the [row][column] values of the 4x4
matrix.
Return Values
Pointer to the four-dimensional destination vector.
Remarks
The following code shows how to use _Xform4dV.

void print_matrix(float *matrix, float *src, float *dest)


{
int row, col;

printf("Matrix:\t\t\t\tSrc:\tDest:\n");

for (row = 0; row < 4; row++)


{
printf("| ");
for (col = 0; col < 4; col++)
{
printf("%6.2f", *matrix++);

}
printf(" |");
printf(" |%6.2f|", *src++);
printf("\t|%10.4f|\n", *dest++);
}

}
void main()
{
int i;
float dest[4];

float src[4] = {1.0,2.0,3.0,4.0};


float matrix[16]={ 1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0};
_Xform4dV(dest, src, matrix); //[matrix]x[src[i]] --> dest[i]

print_matrix(matrix, src, dest);


}
Output
Matrix: Src: Dest:
| 1.00 2.00 3.00 4.00 | | 1.00| | 30.0000|
| 5.00 6.00 7.00 8.00 | | 2.00| | 70.0000|
| 9.00 10.00 11.00 12.00 | | 3.00| | 110.0000|
| 13.00 14.00 15.00 16.00 | | 4.00| | 150.0000|

Requirements
Routine Required header Architecture
_Xform4dV <shintr.h> SH-4
See Also
Reference
Intrinsic Functions for Renesas Microprocessors
_Xform3dV
_XDXform4dV
_XDXform3dV
_LoadMatrix
_SaveMatrix
Smart Device Development

Renesas Compiler Options


The Renesas compiler supports the following command-line options:
-QSfast, -QSfastd - Provide Backward Compatibility
-Qsh4
-QSimplicit-import- Disable Importing of Helpers
See Also
Concepts
Unique Build Options
Smart Device Development

-QSfast, -QSfastd - Provide Backward Compatibility


These options, -QSfast and -QSfastd provide backward compatibility. -QSfastd is the default.
The device compilers support full IEEE compliant hardware operations including the use of denormal operands. This allows the
compiler to default to use of the Renesas SuperH SH-4 hardware instructions for both single and double precision floating-
point operations.
The -QSfast option causes the compiler to call CRT emulation routines for all floating-point operations.
The -QSfast option allows the compiler to use single precision SH-4 floating-point instructions. It will also generate a warning
if the compiler finds a double floating point constant.
Do not use double constants when performance is a consideration, because double constants can unnecessarily promote an
operation-type from single to double precision.
Note that floating-point constants default to type double. You may specify single precision floating point constants with a
floating suffix f or F such as 3.14159f.
The default -QSfastd option allows the compiler to use single and double precision SH-4 floating-point instructions.
The compiler does not generate warnings for double constants when you specify -QSfastd. The -QSfastd command line
option may cause the compiler to produce slightly larger code.
See Also
Reference
Renesas Compiler Options
Smart Device Development

-QSh4
This option specifies compilation for the Renesas SH-4 microprocessor.
See Also
Reference
Renesas Compiler Options
Smart Device Development

-QSimplicit-import- Disable Importing of Helpers


This option forces the compiler to use statically linked helper functions. Compiler helper functions are typically located in a
DLL.
To reduce the thunk overhead when calling these functions, the compiler uses the dllimport calling mechanism. If OS or driver
code is linked statically with the helper functions, the -QSimplicit-import- flag is used to force the compiler to use typical
calling mechanisms.
See Also
Reference
Renesas Compiler Options
Smart Device Development

Renesas SH-4 Calling Sequence Specification


The Renesas SuperH SH-4 Calling Sequence Specification provides direction for the development of compilers and assembly
language programs for the SH-4 microprocessor.
In addition, the standard enables the development of tools, debuggers, and operating system utilities that perform automated
walking of the call stack.
In This Section
Renesas SH-4 Registers
Describes register assignments and parameter passing conventions.
Renesas SH-4 Stack Frame Layout
Describes the stack frame layout.
Renesas SH-4 Prolog and Epilog
Describes the code sequence specifications for setting up a stack frame for unwinding.
Related Sections
Renesas Family Processors
Provides an overview of compiler options, intrinsic functions, and call specifications for Renesas microprocessors supported
in this release of Visual Studio.
Smart Device Development

Renesas SH-4 Registers


The Renesas SuperH SH-4 has 16 general-purpose registers. The following table shows the roles assigned to these registers.
Regis Description
ter
R0 Serves as a temporary register when expanding assembly language pseudo-instructions, and holds function return valu
es.
In addition, R0 serves as an implicit source or destination in byte and 16-bit operations.
Not preserved.

R1-R Serve as temporary registers


3
Not preserved

R4-R Hold the first four words of integer and non-scalar incoming arguments. The argument build area provides space into
7 which R4 through R7 holding arguments may spill.
Not preserved.

R8-R Serve as permanent registers


13
Preserved

R14 Serves as the default frame pointer. Any other permanent register may serve as the frame pointer, and leaf routines ma
y use a temporary register as the frame pointer.
Preserved.

R15 Serves as the stack pointer or as a permanent register


Preserved.

The SH-4 has two banks of 16 floating-point registers designated Bank0 and Bank1. This specification does not define the use
of Bank1. This calling convention assigns the following roles to the SH-4 Bank0 floating-point registers.
Double-Precis Single-Precisi Description
ion Register on Register
DR0 FR0 Hold function return values. DR0 is another name for the single-precision registers FR0 and F
R1 as a pair.
FR1

DR2 FR2-FR3 Serve as temporary registers. DR2 is another name for FR2 and FR3 as a pair.
Not preserved

DR4-DR10 FR4-FR11 Hold single- or double-precision floating-point arguments. The argument build area also provi
des space into which floating-point registers holding arguments may spill.

DR12-DR14 FR12-FR15 Serve as permanent registers.


Preserved

The floating-point status control affects the behavior of some floating-point instructions. For information about the use of the
PR, SZ, and FR bits within prologs and epilogs, see Renesas SH-4 Prolog and Epilog.
See Also
Concepts
Renesas SH-4 Stack Frame Layout
Other Resources
Renesas SH-4 Prolog and Epilog
Smart Device Development

Renesas SH-4 Stack Frame Layout


The Renesas SuperH SH-4 stack frame layout uses four designated areas to hold register areas used by functions and space for
variables.
The Register Save Area (RSA) holds the preserved values of any permanent registers used by the function. It also
contains the function's return address.
The Locals and Temporaries area represents the stack space allocated for local variables and compiler-generated
temporaries.
An alloca() locals area is dynamically allocated during function execution by the use of the alloca() intrinsic function.
Compiler-generated code may also dynamically allocate space to manage the construction of outgoing arguments.
The Outgoing Arguments area must be large enough to hold all the arguments passed when calling another function,
including all arguments passed in registers. This area may be dynamically allocated or extended prior to a call if the rules
for alloca() are observed.
SH-4 Frame and Stack Pointers
The following list gives more information about stack and frame pointers:
The stack pointer and frame pointer addresses are aligned on 4-byte boundaries.
If a routine has alloca() locals, or dynamically allocates stack frame space for any other reason, a separate frame pointer
register accesses incoming arguments and locals. A leaf routine may use any free integer register as the frame pointer. A
non-leaf routine must use a permanent register.
By convention, a routine that establishes a separate frame pointer should use R14. However, a routine may establish
another frame pointer to more efficiently access data in large stack frames. If a routine establishes no frame pointer, R15
must remain unchanged between the end of prolog and the beginning of the epilog.
See Also
Concepts
Renesas SH-4 Registers
Other Resources
Renesas SH-4 Prolog and Epilog
Smart Device Development

Renesas SH-4 Prolog and Epilog


Renesas SuperH SH-4 prolog and epilog code segments are required to implement Structured Exception Handling (SEH) on
Renesas microprocessors. For more information, see SEH in RISC Environments.
The prolog contains the code that sets up the stack frame for a routine. The epilog contains the code that removes the routine's
frame and then returns to the calling function.
In This Section
SH-4 Prolog
Describes the requirements for an SH-4 prolog sequence.
SH-4 Epilog
Describes the requirements for an SH-4 epilog sequence.
SH-4 Prolog and Epilog Examples
Provides examples of paired prolog and epilog sequences.
Smart Device Development

SH-4 Prolog
The SH-4 prolog contains four parts that are immediately contiguous with no intervening instructions. The following list shows
the required parts.
1. A sequence of zero or more instructions that save the incoming argument values from R4 - R7 and FR4 - FR11 to the
argument home locations.
This sequence typically uses the fmov instruction with R15 as the base address register. This sequence will not change
the stack pointer, R15.
In addition, floating-point argument registers can be stored onto the stack using the fmov instruction with the register-
indirect and register-indirect-pre-decrement addressing modes.
A sequence of one or more such fmov instructions may be preceded by a two-instruction address register setup
sequence composed of a constant move to a general register, followed by an add of the sp to the register. For example:
mov #36, r0
add sp, r0
fmov fr5, @r0
fmov fr4, @-r0

2. A sequence of zero or more instructions that push all permanent registers to be saved and the return address (PR), if it is
to be saved, onto the stack using the pre-decrement indirect register addressing mode with R15 as the address register.
If a permanent register such as R14 is to be used as the frame pointer, it is pushed first.
If the PR is to be saved, it is pushed last.
The prolog uses mov.l instructions to save registers other than the return address, and the sts.l instruction to save the
return address.
The prolog also uses the fmov.s instruction to save floating-point registers, and may invoke double-precision and move-
extension fmov instructions by first setting the SZ bit in the FPSCR.
3. A sequence of one or more instructions that set up the frame pointer, if one is to be established.
To set up the frame pointer, the step 3 sequence first copies the contents of R15 to the frame pointer register, then adds
or subtracts the amount of offset to the frame pointer address from the frame pointer register.
If the frame pointer address is less than the current value in R15, the prolog subtracts the offset to the frame pointer
address from R15, and copies R15 to the frame pointer register. If this method is used, the routine must later take the
size of the decrement to R15 into account.
If the routine is not a leaf routine, the function must use a permanent register, typically R14, as the frame pointer.
4. A sequence of zero or more instructions that allocate the remaining stack frame space for local variables, compiler-
generated temporaries, and the argument-build area by subtracting a 4-byte aligned offset from R15.
The Virtual Unwinder considers the last instruction in this sequence the last instruction of the prolog.
If necessary, the temporary register R1 holds an offset too large to be represented in the immediate field of an add instruction.
See Also
Concepts
SH-4 Epilog
SH-4 Prolog and Epilog Examples
Other Resources
Renesas SH-4 Prolog and Epilog
Smart Device Development

SH-4 Epilog
The SH-4 epilog is a contiguous sequence of instructions that restores the saved permanent registers, resets the stack pointer
to its value on function entry, and returns to the function's calling function.
In addition, the Virtual Unwinder requires the epilog to have the following parts, except where noted:
1. A single add instruction that increments the frame pointer. This instruction must immediately precede the sequence of
instructions defined for part 2. (Optional)
2. A sequence of instructions that modify R15 by referencing it in the destination operand of the instruction or in a post-
increment memory address operand of the instruction. This sequence immediately precedes the rts instruction of part 3.
All instructions in this sequence must be lds, mov, fmov, fschg, or add instructions.
This item is optional. It does not appear in functions that have no RSA area to restore.
3. The rts instruction and its delay slot instruction. The instruction in the delay slot of the rts is considered part of the epilog
but is not required to conform to the rules listed for item 2.
When unwinding out of a function, the Virtual Unwinder must determine if the currently executing instruction is in the prolog
or epilog. If the current point of control is in the prolog or in the epilog, the Virtual Unwinder must take special measures to
unwind out of the function.
The following list shows three conditions that the Virtual Unwinder must maintain:
If the function establishes a frame pointer, the function may not modify the frame pointer value during the interval
between the completion of the last prolog instruction and the beginning of the first instruction of the epilog.
If the function does not establish a frame pointer, the function must not modify value in R15 during the interval between
the completion of the last prolog instruction and the beginning of the first instruction of the epilog.
The address contained in the stack pointer, which is always R15, must never be greater than the lowest address of any
unrestored register value in the Register Save Area.
The SZ, PR, and FR bits of the FPSCR register must always be set to zero on entering and exiting the prolog and epilog.
The PR and FR bits must not be modified within the prolog or epilog. This condition enables the Virtual Unwinder to
correctly reverse-execute floating-point instructions.
See Also
Concepts
SH-4 Prolog
SH-4 Prolog and Epilog Examples
Other Resources
Renesas SH-4 Prolog and Epilog
Smart Device Development

SH-4 Prolog and Epilog Examples


The following code examples show how to use prolog and epilog to perform certain tasks.
Allocate a stack frame to save R14, R8, and PR
This example allocates a stack frame to save R14, R8, and PR, and to allow alloca() calls. It also allocates a 4-word
argument build area. Local variables and temporaries do not need stack space.
// Prolog

NESTED_ENTRY Function

mov.l R14, @-R15 // Save old frame pointer.


mov.l R8, @-R15 // Save a permanent register.
sts.l PR, @-R15 // Save return address.
mov R15, R14 // Set up new frame pointer.
add #12, R14
add #-16, R15 // Allocate argument save area

PROLOG_END

// Routine body

// Epilog

add #-12, R14 // Find base of RSA.


mov R14, R15
lds.l @R15+, PR // Restore return address.
mov.l @R15+, R8 // Restore R8.
rts // Return.
mov.l @R15+, R14 // Restore R14.

ENTRY_END Function

Allocate a stack frame for a leaf routine


This example allocates a stack frame for a leaf routine that requires 40 bytes for local variables and temporaries. It uses
permanent registers R8, R9, and R10. This routine has no _alloca locals, so no frame pointer is required.
// Prolog

NESTED_ENTRY Function

mov.l R8, @-R15


mov.l R9, @-R15
mov.l R10, @-R15
add #-40, R15

PROLOG_END

// Routine body

add #40, R15


mov.l @R15+, R10
mov.l @R15+, R9
rts
mov.l @R15+, R8
ENTRY_END Function

See Also
Reference
SH-4 Assembler Macros
Other Resources
Renesas SH-4 Prolog and Epilog
Smart Device Development

SH-4 Assembler Macros


SH-4 assembler-level macros are reuired to implement prolog and epilog code sequences.
The following table shows the macros defined for SH-4 microprocessors.
Macro name Description
ALTERNATE_ENTRY (SH-4) Declares an alternate entry to a routine.

END_REGION (SH-4) Marks the end of a contiguous range of text or data.

ENTRY_END (SH-4) Ends the routine that was specified by a prior NESTED_ENTRY.

EXCEPTION_HANDLER (SH-4) Associates a named exception handler with the subsequent NESTED_ENTRY.

EXCEPTION_HANDLER_DATA (SH-4) Associates a named exception handler and the handler data with the subsequent NESTED
_ENTRY.

LEAF_ENTRY (SH-4) Declares the beginning of a routine that does not require any prolog code.

NESTED_ENTRY (SH-4) Declares the beginning of a routine that either has an existing stack frame or creates a ne
w stack frame.

PROLOG_END (SH-4) Marks the end of the prolog area.

START_REGION (SH-4) Marks the beginning of a contiguous range of text or data.


See Also
Other Resources
Renesas SH-4 Calling Sequence Specification
Smart Device Development

ALTERNATE_ENTRY (SH-4)
This macro declares an alternate entry to a routine of type NESTED_ENTRY (SH-4) or LEAF_ENTRY (SH-4).

ALTERNATE_ENTRY Name[,
[Section=]SectionName]

Parameters
Name
Name is the entry point and is in the global name space.
SectionName
SectionName is the name of the section in which the entry will appear; see Remarks.
Return Values
None.
Remarks
The ALTERNATE_ENTRY macro does not use the SectionName parameter. The parameter is accepted and ignored for
consistency with NESTED_ENTRY and LEAF_ENTRY.
If used, an ALTERNATE_ENTRY call must appear in the body of a routine.
See Also
Reference
NESTED_ENTRY (SH-4)
LEAF_ENTRY (SH-4)
Smart Device Development

END_REGION (SH-4)
This macro marks the end of a contiguous range of text or data.

END_REGION NameEnd

Parameters
NameEnd
NameEnd labels the end of the range.
Return Values
None.
Remarks
NameEnd is in the global name space.
See Also
Reference
START_REGION (SH-4)
Smart Device Development

ENTRY_END (SH-4)
This macro ends the current routine specified by NESTED_ENTRY (SH-4) or LEAF_ENTRY (SH-4).

ENTRY_END [Name]

Parameters
Name
Name is the entry point and is in the global name space.See Remarks.
Return Values
None.
Remarks
Name should be the same name used in the NESTED_ENTRY or LEAF_ENTRY macros.
The ENTRY_END (SH-4) macro currently ignores Name.
See Also
Reference
NESTED_ENTRY (SH-4)
LEAF_ENTRY (SH-4)
Smart Device Development

EXCEPTION_HANDLER (SH-4)
This macro associates an exception handler Handler with a subsequent NESTED_ENTRY (SH-4) or LEAF_ENTRY (SH-4) routine.

EXCEPTION_HANDLER Handler

Parameters
Handler
Name of exception handler.
Return Values
None.
Remarks
This association is in effect until the compiler encounters a matching ENTRY_END (SH-4) macro.
See Also
Reference
NESTED_ENTRY (SH-4)
LEAF_ENTRY (SH-4)
ENTRY_END (SH-4)
Smart Device Development

EXCEPTION_HANDLER_DATA (SH-4)
This macro associates an exception handler Handler and the HandlerData with a subsequent NESTED_ENTRY (SH-4) or
LEAF_ENTRY (SH-4) routine.

EXCEPTION_HANDLER_DATA Handler,
HandlerData

Parameters
Handler
Name of exception handler.
HandlerData
String associated with exception handler.
Return Values
None.
Remarks
This association is in effect until compiler encounters a matching ENTRY_END (SH-4) macro.
See Also
Reference
NESTED_ENTRY (SH-4)
LEAF_ENTRY (SH-4)
ENTRY_END (SH-4)
EXCEPTION_HANDLER (SH-4)
Smart Device Development

LEAF_ENTRY (SH-4)
This macro declares the beginning of a routine that does not require any prolog code.

LEAF_ENTRY Name[,
[Section=]SectionName]

Parameters
Name
Name is the routine name and is in the global name space.
SectionName
SectionName is the name of the section in which the entry will appear; it is optional and defaults to .text.
Return Values
None.
Remarks
A LEAF_ENTRY must have an associated ENTRY_END (SH-4).
See Also
Reference
ENTRY_END (SH-4)
PROLOG_END (SH-4)
Smart Device Development

NESTED_ENTRY (SH-4)
This macro declares the beginning of a routine that either has an existing frame or creates a stack frame.

NESTED_ENTRY Name[,
[Section=]SectionName]

Parameters
Name
Name is the routine name and is in the global name space.
SectionName
SectionName is the name of the section in which the entry will appear; it is optional and defaults to text.
Return Values
None.
Remarks
A NESTED_ENTRY must have an associated PROLOG_END (SH-4) and ENTRY_END (SH-4).
See Also
Reference
ENTRY_END (SH-4)
PROLOG_END (SH-4)
Smart Device Development

PROLOG_END (SH-4)
This macro marks the end of the prolog area.

PROLOG_END

Parameters
None.
Return Values
None.
Remarks
This macro must appear following a NESTED_ENTRY (SH-4) or LEAF_ENTRY (SH-4) macro.
It appears after the prolog area and before the matching ENTRY_END (SH-4) macro.
See Also
Reference
NESTED_ENTRY (SH-4)
LEAF_ENTRY (SH-4)
ENTRY_END (SH-4)
Smart Device Development

START_REGION (SH-4)
This macro marks the beginning of a contiguous range of text or data.

START_REGION NameBegin

Parameters
NameBegin
NameBegin labels the beginning of the range. NameBegin is in the global name space.
Return Values
None.
See Also
Reference
END_REGION (SH-4)
Smart Device Development

Renesas SH-4 Series Assembler


The SH-4 Series Assembler (SHASM) converts source programs written in assembly language into a format that can be
handled by SH microprocessors, outputting the result as an object module and as an assembler listing. SHASM generates
output in Microsoft Common Object File Format (COFF).
SHASM contains numerous enhancements designed to enhance the programming environment and to address compatibility
issues.
Although SHASM closely resembles the Renesas native assembler, it is not identical. For example, SHASM generates error and
warning messages that contain not only an error number but also a descriptive message.
In This Section
SH-4 Assembler Command-Line Options
Describes the command-line options available to SHASM
SH-4 Assembler Directives

Describes assembler directives


SH-4 Assembler Error Messages
Lists the error messages displayed by the SH-4 assembler.
Related Sections
Renesas SH-4 Calling Sequence Specification
Provides an overview and links to information about register assignments and stack layout
Smart Device Development

SH-4 Assembler Command-Line Options


To start the SH-4 assembler, enter a command line with the following format when the host computer operating system is in
the input wait state.

shasm <input source file> [,<input source file>...][command line options>...]

When you specify multiple source files on the command line, the assembler creates a unit of assembly processing by
concatenating the specified files in the specified order. Because of this, the .END directive must appear only in the last file.
Command line options can begin with either a - (hyphen) or a / (slash). File names can be specified with forward or backward
slashes.
If the assembler has the option of interpreting an argument as either a command line option or a file name, the argument will
be interpreted as a command line option. For example, if a file called /source.src is assembled by writing shasm /source, the
assembler interprets /source as a switch, and issues a message that there are no input files.
Command line options provide additional specifications for the assembly processing. The following table shows the command
line options for the SH-4 assembler.
Command line opt Description
ion
-OBJECT Specifies output of an object module. Default value.

-NOOBJECT Suppresses output of an object module.

-DEBUG Specifies output of debug information.

-NODEBUG Suppresses output of debug information.

-LIST Specifies output of an assembler listing. Default value.

-NOLIST Suppresses output of an assembler listing.

-SHOW Specifies output of the preprocessor function source program.

-NOSHOW Suppresses output of specified preprocessor function source statements and object code display lines in t
he source program listing.

-LINES Sets the number of lines in the assembler listing.

-COLUMNS Sets the number of columns in the assembler listing.

-FoOBJPATH Sets the path to which the object should be written. A synonym for the -o=OBJPATH option. Provided for
compatibility with Microsoft-based tools.

-wide[_listing] Shows up to eight bytes of machine code or data per line in the assemble listing. Default is four bytes per
line.

-nowide[_listing] Shows up to four bytes of machine code or data per line in the assemble listing. This is the default behavi
or.

-tab[_expand][=<nu Expands tab characters in the assemble listing. The number, if specified, is the spacing of tab stops. Defaul
mber>] t is eight.
-Notab[_expand] Writes tab characters into the assemble listing unchanged. This is the default behavior.

-maxerr[ors]=<num Aborts the assembly after <number> errors have been reported. Default is 100.
ber>

-Qsh<version>[r<r Selects SH microprocessor version and revision that control the setting of the _M_SH and _M_SH_REV pr
evision>] edefined symbols. Default is version SH-4.

-nologo Instructs not to print the logo banner when it runs.

-help -usage Output a detailed command line usage message and exit immediately.

-D<name>[=<num Predefines an equate; for example, -DTERM is equivalent to TERM.


ber>]

-CPU=SH<version> Selects target CPU for the source program being assembled. Valid options are:
SH1
SH2
SH4

The assembler listing is a listing to which the results of the assembly processing are output.
Note that when compiling an assembly source file that ends in .s, in contrast to .asm or .src, then the output object file
concatenates .obj to the end of the file name. For example, a file named test.s is assembled to test.s.obj.
Return Codes
The assembler delivers a return code that reports whether or not the assembly processing terminated normally. The following
table shows the return values that indicate the activity at termination.
Activity Return value
Normal termination 0

Warnings occurred 0

Errors occurred 2

Fatal error occurred 4


See Also
Other Resources
Renesas SH-4 Series Assembler
Smart Device Development

SH-4 Assembler Directives


The SH-4 assembler (SHASM) includes numerous assembler directives that the assembler interprets and executes.
In This Section
SH-4 Assembler Macro Directives
SH-4 Assembler Section and Location Directives
SH-4 Assembler Symbol Handling Directives
SH-4 Assembler Data and Data Area Directives
SH-4 Assembler Function-Definition Directives
SH-4 Assembler Debug Information Directives
SH-4 Assembler Listing Directives
SH-4 Assembler Miscellaneous Directives
SH-4 Assembler Conditional Assembly Directives
Smart Device Development

SH-4 Assembler Macro Directives


The assembler provides the following macro function directives.
Directi Syntax Description
ve
.MACR .MACRO <macro name>[ <formal parameter>[=<default>] [,<forma Defines a macro.
O l parameter>...]]

.ENDM ENDM Indicates the end of a macro d


efinition.