C Compilers Reference
C Compilers Reference
C Compilers Reference
3 C Compiler 29
C Compiler Overview . . . . . . . . . . . . . . . . . . . 29
The CodeWarrior Implementation of C . . . . . . . . . . . 30
Identifiers . . . . . . . . . . . . . . . . . . . . . . . 30
Include Files . . . . . . . . . . . . . . . . . . . . . . 30
Prefix Files . . . . . . . . . . . . . . . . . . . . . . 32
Sizeof() Operator . . . . . . . . . . . . . . . . . . . . 32
Volatile Variables . . . . . . . . . . . . . . . . . . . . 33
Enumerated Types . . . . . . . . . . . . . . . . . . . 33
Extensions to ANSI/ISO C . . . . . . . . . . . . . . . . . 36
4 C++ Compiler 55
C++ Compiler Overview . . . . . . . . . . . . . . . . . 55
CodeWarrior Implementation of C++ . . . . . . . . . . . . 56
Implicit Return Statement for main() . . . . . . . . . . . 57
Keyword Ordering . . . . . . . . . . . . . . . . . . . 57
Additional Keywords . . . . . . . . . . . . . . . . . . 58
Conversions in the Conditional Operator . . . . . . . . . 58
Default Arguments in Member Functions . . . . . . . . . 58
Local Class Declarations with Inline Functions . . . . . . . 59
Index 211
Each chapter begins with an overview section. Table 1.1 lists each of
these and describes what each chapter in this manual covers.
What’s New
This reference has been updated to cover CodeWarrior C/C++ ver-
sion 2.3 and later.
If the text
looks like… Then…
literal Include it in your statement exactly as it’s printed.
metasymbol Replace the symbol with an appropriate value. The text after the
syntax example describes what the appropriate values are.
a|b|c Use one and only one of the symbols in the statement: either a, b,
or c.
[a] Include this symbol only if necessary. The text after the syntax ex-
ample describes when to include it.
The C/C++ Compiler settings panel, where you set compiler op-
tions, is also known as the C/C++ Language settings panel.
Each compiler option has a corresponding pragma that you can use
in source code to turn that particular option on or off, regardless of
the settings in the C/C++ Compiler panel. In addition, there are
some pragmas that do not have a corresponding setting in the C/
C++ Compiler panel. See “Pragmas and Symbols Overview” on
page 89 for details on each available pragma.
Some of the options shown in Figure 2.1 may not appear for some
targets. For example, the Direct to SOM item appears for Mac OS.
Most of the items in this panel are discussed elsewhere in this man-
ual, because they are closely related to how the compiler imple-
ments standard C and C++.
Other items
This table lists where to find information about the other items in
this panel.
When the compiler finds one of these possible mistakes, it can gen-
erate a warning. Warnings are not fatal. Unless you choose to treat
these warnings as errors, your code will still compile (although it
may not run correctly).
This section describes the items in the C/C++ Warnings panel. You
determine which warnings you receive by setting options in the
panel. Figure 2.2 illustrates this panel.
Each warning also has a corresponding pragma that you can use in
source code to turn that particular warning on or off for a limited
piece of code. See “Pragmas and Symbols Overview” on page 89 for
details on each available pragma.
Illegal Pragmas
If the Illegal Pragmas option is on, the compiler displays a warning
when it encounters an illegal pragma. For example, these pragma
statements generate warnings:
#pragma near_data off // WARNING: near_data is not a pragma.
#pragma far_data select // WARNING: select is not defined
#pragma far_data on // OK
Empty Declarations
If the Empty Declarations option is on, the compiler displays a
warning when it encounters a declaration with no variable name.
For example:
int ; // WARNING
int i; // OK
Possible Errors
If the Possible Errors option is on, the compiler checks for some
common typographical mistakes that are legal C syntax but that
may have unwanted side effects, such as putting in unintended
semicolons or confusing = and ==. The compiler generates a warn-
ing if it encounters one of these:
• An assignment in a logical expression or the condition in an
if, while, or for expression. This check is useful if you fre-
quently use = when you meant to use ==. For example:
if (a=b) f(); // WARNING: a=b is an assignment
Unused Variables
If the Unused Variables option is on, the compiler generates a
warning when it encounters a variable that you declare but do not
use. This check helps you find misspelled variable names and vari-
ables you have written out of your program. For example:
void foo(void)
{
int temp, errer; // ERROR: errer is misspelled
error = do_something() // WARNING: temp and error are unused.
}
If you want to use this warning, but need to declare a variable that
you don’t use, use the pragma unused, as in this example:
void foo(void)
{
int i, temp, error;
#pragma unused (i, temp) /* Compiler won’t warn that i and temp
Unused Arguments
If the Unused Arguments option is on, the compiler generates a
warning when it encounters an argument you declare but do not
use. This check helps you find misspelled argument names and ar-
guments you have written out of your program.
void foo(int temp,int errer); // ERROR: errer is misspelled
{
error = do_something(); // WARNING: temp and error are unused.
}
If you need to declare an argument that you don’t use, there are two
ways to avoid this warning. You can use the pragma unused, as in
this example:
void foo(int temp, int error)
{
#pragma unused (temp)
/* Compiler won’t warn that temp is not used */
error=do_something();
}
You can also turn off the ANSI Strict option, and not give the un-
used argument a name. (See “Unnamed Arguments in Function
Definitions” on page 38.) For example:
error=do_something(); */
}
Extra Commas
If the Extra Commas option is on, the compiler generates a warning
when it encounters an extra comma. For example, this statement is
legal in C, but it causes a warning when this option is on:
int a[] = { 1, 2, 3, 4, }; // ^ WARNING: Extra comma after 4
d = 5; /* WARNING */
d = Monday; /* OK */
d = (Day)3 ; /* OK */
/* ... */
/* ... */
class B: public A {
public:
void f(char); // WARNING: Hides A::f(int)
virtual void g(int); // OK: Overrides A::g(int)
};
Non-Inlined Functions
If the Non-Inlined Functions option is on, the compiler issues a
warning when it is unable to inline a function.
C Compiler Overview
This chapter discusses the CodeWarrior C compiler as it applies to
all CodeWarrior targets. For the most part, the information in this
chapter is equally applicable to any operating system or processor.
This chapter does not cover C++ features. For more information on
the C++ language, see “C++ Compiler Overview” on page 55.
Identifiers
(K&R, §A2.3) The C compiler lets let you create identifiers of any
size. However, only the first 255 characters are significant for inter-
nal and external linkage.
Include Files
(K&R, §A12.4) The C compiler can nest #include files up to 32
times. An include file is nested if another #include file uses it in an
#include statement. For example, if Main.c includes the file
MyFunctions.h, which includes the file MyUtilities.h, the file
MyUtilities.h is nested once.
You can use full path names in #include directives, as in this ex-
ample for Mac OS:
#include "HD:Tools:my headers:macros.h"
The CodeWarrior IDE lets you specify where the compiler looks for
#include files with the Access Paths settings panel, shown in Fig-
ure 3.1. It contains two lists of folders: the User list and the System
list. By default, each list contains one folder. The User list contains
{Project ƒ}, which is the folder that the project file is in and all
The compiler searches for a #include file in either the System list
or both the User and System lists, depending on which characters
enclose the file. If you enclose the file in brackets (#include
<stdio.h>), the compiler looks for the file in the System list. If you
enclose the file in quotes (#include "myfuncs.h"), the compiler
looks for the file in the User list first, and then in the System list. In
general, use brackets for include files that are for a large variety of
projects and use quotes for include files that are for a specific
project.
Prefix Files
If you have a single file you wish to include in every source file in a
project, you can use the Prefix File item in the C/C++ Language
Panel. Enter the name of the file in the Prefix File edit field in this
panel.
The compiler automatically includes this file (and any files that it, in
turn, includes) in every source file in the project’s current target.
This is an excellent way to include a precompiled header file in a
project.
Sizeof() Operator
The sizeof() operator returns a number of type size_t, which
the compiler declares to be of type unsigned long int (in the file
stddef.h). If your code assumes that sizeof() returns a number
of type int, it may not work correctly.
Volatile Variables
(K&R, §A4.4) When you declare a variable to be volatile the C com-
piler takes the following precautions:
• It does not store the variable in a register.
• It computes the variable’s address every time a piece of code
references the variable.
a = 5;
b = 20;
i[a + b] = 15;
i[a + b] = 30;
}
Enumerated Types
(K&R, §A8.4) This section describes how the C compiler selects the
underlying integer data type for an enumerated type. The compiler
behavior is controlled primarily by the Enums Always Int option in
the C/C++ Language Panel.
If Enums Always Int is off, the compiler chooses the integral data
type that supports the largest enumerated constant. The type could
be as small as a char or as large as a long int. It could even be a
64-bit long long value.
For example:
#pragma enumsalwaysint off
enum { a=0,b=1 }; // base type: unsigned char
The compiler will use long long data types only if Enums Always
Int is off and the longlong_enums pragma is on. (There is no set-
tings panel option corresponding to the longlong_enums pragma.)
For example:
#pragma enumsalwaysint off
#pragma longlong_enums off
enum { a=0x7FFFFFFFFFFFFFFF }; // ERROR: a is too large
#pragma longlong_enums on
enum { b=0x7FFFFFFFFFFFFFFF };// OK: base type: signed long long
enum { c=0x8000000000000000 };// OK: base type: unsigned long long
enum { d=-1,e=0x80000000 }; // OK: base type: signed long long
For example:
#pragma enumsalwaysint off
#pragma longlong_enums off
#pragma ANSI_strict on
enum { a=-1,b=0xFFFFFFFF }; // error
#pragma ANSI_strict off
enum { c=-1,d=0xFFFFFFFF }; // base type: signed int (b==-1)
Extensions to ANSI/ISO C
This section describes CodeWarrior extensions to the C standard
that apply to all targets. In most cases you turn the extension on or
off with an option in the C/C++ Language Panel. See “C/C++ Lan-
guage Panel” on page 15 for information about that panel.
ANSI Strict
The ANSI Strict option in the C/C++ Language Panel affects several
extensions to the C language supported by the CodeWarrior com-
piler. The extensions are:
• C++ Style Comments
• Unnamed Arguments in Function Definitions
• A # not Followed by Argument in a Macro
• Using an Identifier After #endif
• Using Typecasted Pointers as lvalues
• Converting Pointers to Types of the Same Size
• Arrays of Zero Length in Structures
• The “D” Constant Suffix
In each case the extension is only available if the ANSI Strict setting
is off. If the ANSI Strict setting is on, then these extensions to the
ANSI C standard are disabled.
You cannot turn on the extensions controlled by the ANSI Strict set-
ting individually. They are all on or off depending upon the setting.
This setting may affect how the compiler handles enumerated con-
stants. See “Enumerated Types” on page 33 for more information.
This setting may also affects the main() function for C++ pro-
grams. See “Implicit Return Statement for main()” on page 57..
To turn this feature on, turn off the ANSI Strict setting in the C/C++
Language Panel. If the ANSI Strict setting is on, then this extension
to standard C is disabled.
To turn this feature on, turn off the ANSI Strict setting in the C/C++
Language Panel. If the ANSI Strict setting is on, then this extension
to standard C is disabled.
To turn this feature on, turn off the ANSI Strict setting in the C/C++
Language Panel. If the ANSI Strict setting is on, then this extension
to standard C is disabled.
To turn this feature on, turn off the ANSI Strict setting in the C/C++
Language Panel. If the ANSI Strict setting is on, then this extension
to standard C is disabled.
TIP: If you turn on the ANSI Strict option (disabling the exten-
sion), you can still use the same idea to help you match your #if-
def and #endif directives. Simply put the identifiers into com-
ments, as in the following example.
#ifdef __MWERKS__
# ifndef __cplusplus
/*
* . . .
*/
# endif /* __cplusplus */
#endif /* __MWERKS__ */
For example:
char *cp;
((long *) cp)++; /* OK if ANSI Strict is off. */
To turn this feature on, turn off the ANSI Strict setting in the C/C++
Language Panel. If the ANSI Strict setting is on, then this extension
to standard C is disabled.
are compatible with future versions of the Mac OS, use the func-
tions defined in the LowMem.h header file.
Expand Trigraphs
(K&R, §A12.1) The C compiler lets you ignore trigraph characters.
Many common character constants (especially on Mac OS) look like
trigraph sequences, and this extension lets you use them without in-
cluding escape characters.
Inlining
The compiler determines whether to inline a function based on the
settings of the ANSI Keywords Only item and the Inline Depth
and Auto-inline items in the C/C++ Language Panel.
For beginners: When you call an inline function, the compiler in-
serts the function’s code instead instructions to call that function.
Inlining functions makes your programs faster (because you exe-
cute the function’s code immediately without a function call), but
possibly larger (because the function’s code may be repeated in
several different places).
If you turn off the ANSI Keywords Only option, you can declare C
functions to be inline. The inlining items in the C/C++ Language
Panel let you choose to inline no functions, only functions declared
inline, or all small functions as shown in Table 3.2.
The Smart item and items 1 to 8 in the Inline Depth pop-up menu
correspond to the pragma inline_depth (“C/C++ Language
Panel” on page 15). To check whether this option is on, use
__option(inline_depth), described at “Checking Options” on
page 202.
The Don’t Inline item in the Inline Depth pop-up menu corre-
sponds to the pragma dont_inline, described at “dont_inline” on
page 115. To check whether this option is on, use __option
(dont_inline), described at “dont_inline” on page 204. By de-
fault, this option is off.
Pool Strings
The Pool Strings option in the C/C++ Language Panel affects how
the compiler stores string constants
If this option is on, the compiler collects all string constants into a
single data object so your program needs one TOC entry for all of
them. Turning this option on decreases the number of TOC entries
in your program but increases your program’s size, because it uses a
less efficient method to store the string’s address.
If this option is off, the compiler creates a unique data object and
TOC entry for each string constant.
TIP: You can change the size of the TOC with the Store Static
Data in TOC option in the PPC Processor settings panel. For
more information, see the Targeting Mac OS manual.
NOTE: If you turn the Pool Strings option on, the compiler ig-
nores the setting of the PC-Relative Strings option. This is a 68K-
only feature.
Reusing Strings
The Don’t Reuse Strings option in the C/C++ Language Panel af-
fects how the compiler stores string literals.
If this option is on, the compiler stores each string literal separately.
If this option is off, the compiler stores only one copy of identical
string literals. This option helps you save memory if your program
contains identical string literals which you do not modify.
If this option is off (meaning that string storage is reused for identi-
cal strings) and you change one of the strings, you change them all.
For example, take this code snippet:
char *str1="Hello";
char *str2="Hello"; // two identical strings
*str2 = 'Y';
If the Don’t Reuse Strings option is on. the strings are stored sepa-
rately. After changing the first character, str1 is still "Hello" but
str2 is "Yello".
If the Don’t Reuse Strings option is off, the two strings are stored in
one memory location (i.e. the same memory location is reused), be-
cause they are both identical. After changing the first character, both
str1 and str2 are "Yello". This is counter-intuitive, and can lead
to difficult-to locate bugs.
This option helps you prevent errors that happen when you call a
function before you declare or define it. For example, without a
function prototype, you may pass data if the wrong type. As a re-
sult, your code may not work as you expect even though it compiles
without error.
void main(void)
{
PrintNum(1); // PrintNum() tries to interpret the
integer as a float. Prints 0.000000.
}
void PrintNum(float x)
{
printf("%f\n", x);
}
When you run this code, you could get this result:
0.000000
Although the compiler does not complain about the type mismatch,
the function does not work as you want. Since PrintNum() is not
prototyped, the compiler does not know it needs to convert the inte-
ger to a floating-point number before calling the function. Instead,
the function interprets the bits it received as a floating-point number
and prints nonsense.
void main(void)
{
PrintNum(1); // Compiler knows to convert int to float.
} // Prints 1.000000.
void PrintNum(float x)
{
printf("%f\n", x);
}
Map Newlines to CR
The C compiler lets you choose how to interpret the newline ('\n' )
and return ('\r') characters. This behavior is controlled by the
Map Newlines to CR item in the C/C++ Language Panel.
If you turn this option on, the compiler uses the MPW conventions
for the '\n' and '\r' characters.
If this option is off, the compiler uses the CodeWarrior C and C++
conventions for these characters.
If you turn this option on, be sure you use ANSI/ISO C and C++ li-
braries that were compiled with this option on. If you turn this op-
tion on and use libraries built with this option off, you won’t be able
to read and write '\n' and '\r' properly. For example, printing
‘\n’ would bring you to the beginning of the current line instead of
inserting a new line.
This option has no effect on C++. When compiling C++ source code,
the compiler differentiates char* and unsigned char* data types
even if the relaxed pointer option is on.
When the Use Unsigned Chars option is on, the C compiler treats a
char declaration as if it were an unsigned char declaration.
NOTE: If you turn this option on, your code may not be compati-
ble with libraries that were compiled with this option turned off.
If this option is on, you may declare a long long integer. A long
long can hold values from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807. An unsigned long long can hold
values from 0 to 18,446,744,073,709,551,615.
able if the ANSI Strict option is off in the C/C++ Language settings
panel. See “ANSI Strict” on page 37 for more information on this
option.
The op argument represents the item to have its bits rotated. The n
argument represents the number of times to rotate op bits. The op ar-
gument is not promoted to a larger data type, and may be of type
char, short, int, long or long long.
These functions are intrinsic (“built-in”). That is, to use the func-
tions you do not first have to provide function prototypes for them.
Also, you do not need to link with any special libraries.
This chapter covers all the features of the compiler that exist in sup-
port of the C++ language. In addition to describing those features
and how to control them, this chapter also has sections on working
with advanced features of C++ such as RTTI, exceptions, and tem-
plates.
Examples:
int main() { } // equivalent to:
// int main() { return 0; }
main() { } // equivalent to:
// int main() { return 0; }
Keyword Ordering
(ARM §7.1.2, §11.4) If you use either the virtual or the friend
keyword in a declaration, it must be the first word in the declara-
tion. For example:
Additional Keywords
(ARM §2.4, ANSI §2.8) In addition to reserving the symbols in §2.4
of the ARM as keywords, CodeWarrior C++ reserves these symbols
from §2.8 of the ANSI C++ Standard as keywords:
class foo {
enum A { AA };
int f(A a = AA); // OK
int f(B b = BB); // ERROR: BB is not declared yet
enum B { BB };
};
void foo()
{
static int s;
class local {
int f1() { return s; } // ERROR: cannot access 's'
For example, this stub checks for a floating-point unit. In this case
you would also have to define the functions HasFPU() and Dis-
playNoFPU() yourself.
void __PreInit__(void)
{
if(!HasFPU()) {
DisplayNoFPU(); // Display "No FPU" Alert
abort(); // Abort program exection
}
}
The first way is supported by the ANSI/ISO C++ Standard and sim-
ply qualifies the member function with its base class.
From within a function of MySubClass, you can call the base class
version of MyFunc() this way:
MyBaseClass::MyFunc();
However, if you change the class hierarchy, this code may break.
Assume you introduce an intermediate class, and your hierarchy is
now MyBaseClass, MyMiddleClass, and MySubClass. Each has a
version of MyFunc(). The code above still calls the original version
of MyFunc() in the MyBaseClass, bypassing the additional behav-
ior you implemented in MyMiddleClass. In all likelihood, this is
not what you intend, and this kind of subtlety in the code can lead
to unexpected results and bugs that are very hard to locate.
inherited::MyFunc();
With the inherited keyword, the compiler identifies the base class
at compile time. This line of code would call the immediate base
class in both cases: where the base class is MyBaseClass, and where
the immediate base class is MyMiddleClass.
If your class hierarchy changes at a later date and your subclass in-
herits from a different base class, the immediate base class is still
called, despite the change in hierarchy.
The statement calls the func-name in the class’s immediate base class.
If class has more than one immediate base class (because of multiple
inheritance) and the compiler can’t decide which func-name to call,
the compiler generates an error.
This example creates a Q class that draws its objects by adding be-
havior to the O class.
Make sure to insert this directive before using the inherited key-
word:
#pragma def_inherited on
Unsupported Extensions
The C++ compiler does not support this extension to the C++ stan-
dard as described in The Annotated C++ Reference Manual (Addison-
Wesley) by Ellis and Stroustrup:
• Overloading methods operator new[] and operator
delete[] to allocate and deallocate the memory for a whole
array of objects at once. Instead overload operator new()
and operator delete(), which are the functions that op-
erator new[] and operator delete[] call (ARM, §5.3.3,
§5.3.4).
the IDE User Guide for more information on configuring this settings
panel.
Controlling RTTI
CodeWarrior C++ supports run-time type information (RTTI), in-
cluding the dynamic_cast and typeid operators. To use these op-
Enabling the bool data type and its true and false values is not
equivalent to defining them using typedef and #define. The C++
bool type is a distinct type defined by the ANSI/ISO C++ Stan-
dard. Source code that does not treat it as a distinct type might not
compile properly.
If this pragma is on, the compiler lets you use these extensions to the
ANSI/ISO C++ standard:
• Anonymous structs (ARM, §9). For example:
#pragma cpp_extensions on
void foo()
{
union {
long hilo;
struct { short hi, lo; };
// annonymous struct
};
hi=0x1234;
lo=0x5678;
// hilo==0x12345678
}
void (Foo::*ptmf2)() = f;
// OK, if cpp_exptensions is on.
}
If exceptions are enabled, you can throw exceptions across any code
that’s compiled by the CodeWarrior C/C++ compiler. You cannot
throw exceptions across the following:
• Mac OS Toolbox function calls
• Libraries compiled with exception support turned off
• Libraries compiled with versions of the CodeWarrior C/C++
compiler earlier than CodeWarrior 8
• Libraries compiled with CodeWarrior Pascal or other
compilers
nary cast returns an unpredictable value that may crash your pro-
gram if the conversion is not possible.
The Type must be either void or a class with at least one virtual
member function. If the object that expr points to (*expr) is of type
Type or is derived from type Type, this expression converts expr to a
pointer of type Type* and returns it. Otherwise, it returns 0, the null
pointer.
a = dynamic_cast<Athlete*>(arnold);
// a is arnold, since arnold is an Athlete.
a = dynamic_cast<Athlete*>(lois);
// a is 0, since lois is not an Athelete.
a = dynamic_cast<Athlete*>(clark);
// a is clark, since clark is both a Superman and an Athlete.
You can also use the dynamic_cast operator with reference types.
However, since there is no equivalent to the null pointer for refer-
ences, dynamic_cast throws an exception of type bad_cast if it
cannot perform the conversion.
#include <exception>
// . . .
Person &superref = *clark;
try {
Person &ref = dynamic_cast<Person&>(superref);
}
catch(bad_cast) {
cout << "oops!" << endl;
}
#include <typeinfo>
// . . .
if (typeid(Athlete) == typeid(*arnold))
// arnold is an Athlete, result is true
if (typeid(*arnold) == typeid(*louganis))
// arnold and louganis are both Athletes, result is true
if (typeid(*lois) == typeid(*arnold)) // ...
// lois and arnold are not the same type, result is false
You can access the name of a type with the name() member func-
tion in the type_info class. For example, these statements:
#include <typeinfo>
// . . .
cout << "Lois is a(n) "
<< typeid(*lois).name() << endl;
cout << "Arnold is a(n) "
<< typeid(*arnold).name() << endl;
Print this:
In a source file, include the header file and define the function tem-
plates and the member functions of the class templates. Listing 4.9
shows you an example.
This source file is a template definition file. You’ll include this file in
any file that uses your templates. You do not need to add the tem-
plate definition file to your project. Although this is technically a
source file, you work with it as if it were a header file.
The template definition file does not generate code. The compiler
cannot generate code for a template until you specify what values it
should substitute for the templates arguments. Specifying these val-
ues is called instantiating the template. See “Instantiating a Tem-
plate” on page 76.
#include "templ.h"
foo<int> fi;
struct bar;
template<typename T> struct foo {
bar *member; // OK
};
struct bar { };
foo<int> fi;
return 0;
}
Instantiating a Template
The compiler cannot generate code for a template until you:
• declare the template class
• provide a template definition
• specify the data type(s) for the template
Automatic instantiation
#include <iostreams.h>
#include "templ.cp" // includes templ.h as well
void main(void) {
Templ<long> a = 1, b = 2;
// The compiler instantiates Templ<long> here.
cout << Max(a.Get(), b.Get());
// The compiler instantiates Max<long>() here.
}
Explicit instantiation
Activating EC++
To compile EC++ source code, make sure the EC++ Compatibility
Mode option is on in the C/C++ Language settings panel.
Templates
ANSI C++ supports templates. The EC++ proposal does not include
template support for class or functions.
Libraries
The classes <string>, <complex>, <ios>, <streambuf>, <is-
tream> and <ostream> are supported in Embedded C++ specifica-
tions. However only in a non-template form. All other ANSI C++ li-
braries including the STL-type algorithm libraries are not supported
File Operations
There are no file operations specified in the EC++ proposed stan-
dard except for simple console input and output file types.
Localization
There are no localization libraries in the EC++ proposed standard
because of the excessive memory requirements.
Exception Handling
Exception handling is not supported in the EC++ proposed stan-
dard.
Compiler-related strategies
Language-related strategies
Library-related strategies
• Stream-Based Classes—these classes in the Metrowerks Stan-
dard Libraries comprise a lot of object code
• Alternative Class Libraries—non-standard class libraries
may provide a subset of the standard library’s functionality
with less overhead
Size Optimizations
Metrowerks compilers include optimization settings for size or
speed, and various levels of optimization. Choose size as your de-
sired outcome, and the level of optimization you wish to apply.
Inlining
With CodeWarrior you can turn inlining off, allow normal inlining,
auto-inline, or set the maximum depth of inlining.
However, MSL C++ defines many functions as inline, and this is not
good if you want minimal code size. For optimal code size when
using MSL C++, turn inlining off when you build the library. If you
are not using MSL C++, normal inlining and a common sense use of
the keyword “inline” may improve your code size.
Virtual Functions
For optimal code size virtual functions should not be used except
when necessary. A virtual function is never dead-stripped, even if
it’s never called.
The proposal for Embedded C++ does not allow runtime type iden-
tification. Turn RTTI off as a C++ language option in the target set-
tings. The option is in the C/C++ Language settings panel.
Exception Handling
Be selective when using C++ exception handling routines, or not
use exceptions at all. CodeWarrior has a zero runtime overhead
error handling mechanism. However, using exceptions still adds
some code size. The exception tables (data) can get pretty big when
using exception handling.
The proposal for Embedded C++ does not allow exception han-
dling. Turn exception handling off as a C++ language option in the
target settings. The option is in the C/C++ Language settings panel.
Operator New
The C++ new operator might throw an exception or not depending
on how the runtime library implements the new operator. To have it
throw exceptions set __throws_bad_alloc to 1, to have it not set
__throws_bad_alloc to 0 in the prefix file for your target and re-
build your library.
Please read your release notes or Targeting manual for more infor-
mation.
Multiple Inheritance
The code and data overhead required to implement multiple inher-
itance is fairly modest.
The proposal for Embedded C++ does not allow multiple inherit-
ance.
Virtual Inheritance
For optimal code size, do not use virtual inheritance. Virtual base
classes are often complex and will add a lot of code to the construc-
tor and destructor functions.
The proposal for Embedded C++ does not allow virtual inheritance.
Stream-Based Classes
The Metrowerks Standard Library (MSL) C++ stream-based classes
will initialize several instances of direct and indirect objects. When
code size is critical, do not use any stream-based classes. The
stream-based classes include standard input (cin), standard output
(cout), and standard error (cerr). There are wide-character equiv-
alents for the normal input and output routines as well. Unless there
is a great need for these classes, use standard C input and output
functions instead.
The proposal for Embedded C++ does not allow for templatized
classes or functions. MSL is compliant with the ANSI/ISO proposed
standards that are based on templates.
To avoid this overhead, you may want to devise your own vector,
string, or other utility classes that you use commonly. In addition,
there are other class libraries available, such as the NIH's (National
Institute of Health) Class Library. These may be more suitable for
your work.
Typically, you use the settings panels to set the options for most of
your code and use pragmas to change the options for special cases.
For example, with the C/C++ Language Panel, you can turn off a
time-consuming optimization and, with a pragma, turn it on only
for the code it helps most.
Pragmas
This section describes how to use pragmas and lists and explains
each pragma.
Pragma Syntax
Most pragmas have this syntax:
#include <smallfuncs.h>
that you don’t inadvertently change the settings in the Project Set-
tings dialog.
Pragma Scope
In general, the scope of a pragma setting is limited to a single file.
As discussed in Pragma Syntax, you should use on, or off after the
pragma’s name to change a pragma’s setting to the condition you
want. After you have set the pragma to the desired state, all code
after that point is compiled with that setting until either:
• change the setting with on, off, or (preferred) reset
• you reach the end of the file
For example, this code says that the variable xxx is a far variable.
// in file pch.h
#pragma far_data on
extern int xxx;
// in file test.c
#pragma far_data off // far data is off
The pragma setting still works within the header file, even though
the source file including the header has a different setting.
a6frames
Description Controls the generation of stack frames based on the A6 register.
This is the code that the compiler generates for each function, if this
pragma is on:
LINK #nn,A6
UNLK A6
align
Description Specifies how to align data.
This pragma specifies how to align structs and classes, where align-
ment can be one of the following values:
If alignment is The compiler …
mac68k Aligns every field on a 2-byte boundaries,
unless a field is only 1-byte long. This is the
standard alignment for 68K Macintosh com-
puters.
mac68k4byte Aligns every field on 4-byte boundaries.
power Align every field on its natural boundary.
This is the standard alignment for Power
Macintosh computers. For example, it aligns
a character on a 1-byte boundary and a 16-bit
integer on a 2-byte boundary. The compiler
applies this alignment recursively to struc-
tured data and arrays containing structured
data. So, for example, it aligns an array of
structured types containing an 4-byte float-
ing point member on an 4-byte boundary.
native Aligns every field using the standard align-
ment. It is equivalent to using mac68k for
68K Macintosh computers and power for
Power Macintosh computers.
align_array_members
Description Controls the alignment of arrays within struct and class data.
This option lets you choose how to align an array in a struct or class.
If this option is on, the compiler aligns all array fields larger than a
byte according to the setting of the Struct Alignment option. If this
option is off, the compiler doesn’t align array fields.
#pragma align_array_members on
#pragma align mac68k
struct X2 {
char c; // offset==0
char arr[4]; // offset==2 (2-byte align)
};
#pragma align_array_members on
#pragma align mac68k4byte
struct X3 {
char c; // offset==0
char arr[4]; // offset==4 (4-byte align)
};
always_inline
Description Controls the use of inlined functions.
Remarks When this option is on, the compiler attempts to inline every func-
tion declared with the inline keyword.
ANSI_strict
Description Controls the use of non-standard language features.
Remarks The common ANSI extensions are the following. If you turn on the
pragma ANSI_strict, the compiler generates an error if it encoun-
ters any of these extensions.
• C++-style comments. For example:
a = b; // This is a C++-style comment
#ifdef __MWERKS__
/* . . . */
#endif /*__MWERKS__*/ /* ALWAYS OK */
arg_dep_lookup
Description Controls C++ argument-dependent name lookup.
Remarks When this option is on, the C++ compiler uses argument-dependent
name lookup. By default this option is on.
ARM_conform
Description Controls the use of non-ARM language features.
auto_inline
Description Controls the selection of which functions to inline.
Note that if either the Don’t Inline option (“Inlining” on page 43) or
the dont_inline pragma (“dont_inline” on page 115) is on, the
compiler ignores the setting of the auto_inline pragma and
doesn’t inline any functions.
bool
Description Controls if bool, true, and false are treated as keywords or not.
Remarks When this pragma is on, you can use the standard C++ bool type to
represent true and false. Turn this pragma off if recognizing
bool, true, or false as keywords would cause problems in your
program.
check_header_flags
Description Sets if checking should be done to ensure that a precompiled
header’s data matches a project’s target settings.
When this pragma is on, the compiler makes sure that the precom-
piled header’s preferences for double size (8-byte or 12-byte), int
size (2-byte or 4-byte) and floating point math correspond to the
build target’s settings. If they do not match, the compiler generates
an error.
This pragma does not correspond to any option in the C/C++ Lan-
guage Panel. To check whether this option is on, use __option
(check_header_flags), described in “Checking Options” on
page 202. By default, this pragma is off.
code_seg
Description Specifies the segment into which code is placed.
Remarks This pragma designates the segment into which compiled code is
placed. The name is a string specifying the name of the code seg-
ment. For example, the pragma
#pragma code_seg(".code")
code68020
Description Controls object code generation for Motorola 680x0 (and higher)
processors.
When this option is on, the compiler generates code that’s opti-
mized for the MC68020. The code runs on a Power Macintosh or a
Macintosh with a MC68020 or MC68040. The code does crash on a
Macintosh with a MC68000. When this option is off, the compiler
generates code that will run on any Macintosh.
Before your program runs code optimized for the MC68020, use the
gestalt() function to make sure the chip is available. For more in-
formation on gestalt(), see Chapter “Gestalt Manager” in Inside
Macintosh: Operating System Utilities.
code68881
Description Controls object code generation for Motorola 68881 (and higher)
math coprocessors.
When this option is on, the compiler generates code that’s opti-
mized for the MC68881 floating-point unit (FPU). This code runs on
a Macintosh with an MC68881 FPU, MC68882 FPU, or a MC68040
processor. (The MC68040 has a MC68881 FPU built in.) The code
does not run on a Power Macintosh, a Macintosh with an
MC68LC040, or a Macintosh with any other processor and no FPU.
When this option is off, the compiler generates code that will run on
any Macintosh.
Before your program runs code optimized for the MC68881, use the
gestalt() function to make sure an FPU is available. For more in-
formation on gestalt(), see Chapter “Gestalt Manager” in Inside
Macintosh: Operating System Utilities.
cplusplus
Description Specifies if subsequent source code should be translated as C or C++
source code.
Remarks When this pragma is on, the compiler compiles the code that fol-
lows as C++ code. When this option is off, the compiler uses the suf-
fix of the filename to determine how to compile it. If a file’s name
ends in .cp, .cpp, or .c++, the compiler automatically compiles it
as C++ code. If a file’s name ends in .c, the compiler automatically
compiles it as C code. You need to use this pragma only if a file con-
tains a mixture of C and C++ code.
cpp_extensions
Description Controls language extensions to ANSI/ISO C++.
Remarks If this option is on, it enables these extensions to the ANSI C++ stan-
dard:
• Anonymous structs. For example:
#pragma cpp_extensions on
void foo()
{
union {
long hilo;
struct { short hi, lo; }; // annonymous struct
};
hi=0x1234;
lo=0x5678; // hilo==0x12345678
}
This pragma does not correspond to any option in the C/C++ Lan-
guage Panel. To check whether this option is on, use the __option
(cpp_extensions), described in “Checking Options” on page
202. By default, this option is off.
d0_pointers
Description Specifies which register should be used to hold function result
pointers.
This pragma lets you choose between two calling conventions: the
convention for MPW and Macintosh Toolbox routines and the con-
vention for Metrowerks C and C++ routines. In the MPW and Mac-
intosh Toolbox calling convention, functions return pointers in the
register DO. In the Metrowerks C and C++ convention, functions re-
turn pointers in the register A0.
This pragma does not correspond to any option in the 68K Processor
settings panel. To check whether this option is on, use the
__option (d0_pointers), described in “Checking Options” on
page 202.
data_seg
Description Ignored, but included for compatibility with Microsoft compilers.
def_inherited
Description Controls the use of the inherited keyword.
Remarks This option allows the use of the inherited keyword in C++ pro-
gramming. The default is off.
defer_codegen
Description Controls the inlining of functions that haven’t been compiled yet.
Remarks This option allows inlining of inline and auto-inline functions that
are called before their definition:
#pragma defer_codegen on
#pragma auto_inline on
main()
{
f(); // will be inlined
g(); // will be inlined
}
NOTE: The compiler will need more memory when this option is
selected.
define_section
Description Arranges object code into sections.
Remarks This sophisticated and powerful pragma lets you arrange compiled
object code into predefined sections and sections you define.
The default value for ustring is the same as istring. The default
value for addrmode is "standard". The default value for accmode
is"RWX".
Table 6.5 Predefined sections for NEC V810 and V830 processors
Table 6.6 Predefined sections for NEC V810 and V830 processors (C++)
direct_destruction
This pragma is no long available.
direct_to_som
Description Controls the generation of SOM object code.
This pragma lets you create SOM code directly in the CodeWarrior
IDE. SOM is an integral part of OpenDoc. For more information, see
Targeting Mac OS.
Note that when you turn on this pragma, Metrowerks C/C++ auto-
matically turns on the Enums Always Int option in the C/C++ Lan-
guage Panel, described in “Enumerated Types” on page 33.
disable_registers
Description Controls compatibility for the ANSI/ISO function setjmp().
Remarks If this option is on, the compiler turns off certain optimizations for
any function that calls setjmp(). It disables global optimization
and does not store local variables and arguments in registers. These
changes ensure that all local variables will have up-to-date values.
For Mac OS, this pragma mimics a feature that’s available in THINK
C and Symantec C++. Use this pragma only if you’re porting code
that relies on this feature, since it drastically increases your code’s
size and decreases its speed. In new code, declare a variable to be
volatile if you expect its value to persist across setjmp() calls.
dollar_identifiers
Description Controls use of dollar signs ($) in identifiers.
Remarks When this pragma is on, the compiler accepts dollar signs ($) in
identifiers. When this option is off, the compiler issues an error if it
encounters anything but underscores, alphabetic, and numeric char-
acters in an identifier.
dont_inline
Description Controls the generation of inline functions.
Remarks If the pragma dont_inline is on, the compiler doesn’t inline any
function calls, even functions declared with the inline keyword or
member functions defined within a class declaration. Also, it
doesn’t automatically inline functions, regardless of the setting of
the auto_inline pragma, described in “auto_inline” on page 98. If
this option is off, the compiler expands all inline function calls.
dont_reuse_strings
Description Specifies if each string literal should be stored separately in the
string pool.
ecplusplus
Description Controls the use of embedded C++ features.
Remarks If this option is on the C++ compiler disables the non-EC++ features
of ANSI C++ such as templates, multiple inheritance, and so on. See
“C++ and Embedded Systems” on page 79 for more information on
Embedded C++ support in CodeWarrrior C/C++.
EIPC_EIPSW
Description Controls the saving of processor information for interrupt functions.
enumsalwaysint
Description Specifies the size of enumerated types.
For example:
enum SmallNumber { One = 1, Two = 2 };
/* If enumsalwaysint is on, this type will
be the same size as a char.
If the pragma is off, this type will be
the same size as an int. */
enum BigNumber
{ ThreeThousandMillion = 3000000000 };
/* If enumsalwaysint is on, this type will
be the same size as a long int.
If this pragma is off, the compiler may
generate an error. */
exceptions
Description Controls the availability of C++ exception handling.
Remarks If you turn on this pragma, you can use the try and catch state-
ments to perform exception handling. If your program doesn’t use
You can throw exceptions across any code that’s compiled by the
CodeWarrior 8 (or later) Metrowerks C/C++ compiler with the En-
able C++ Exceptions option turned on. You cannot throw excep-
tions across the following:
• Macintosh Toolbox function calls
• Libraries compiled with the Enable C++ Exceptions option
turned off
• Libraries compiled with versions of the Metrowerks C/C++
compiler earlier than CodeWarrior 8
• Libraries compiled with Metrowerks Pascal or other compil-
ers.
export
Description Controls items to export from a module.
The pragma export gives you another way to export symbols be-
sides using a .exp file. To export symbols with this pragma, choose
Use #pragma from the Export Symbols menu in the PPC PEF or
CFM68K settings panel. Then turn on this pragma to export vari-
If you want to export all the functions and variables declared or de-
fined within a certain range, use #pragma export on at the begin-
ning of the range and use #pragma export off at the end of the
range. If you want to export all the functions and variables in a list,
use #pragma export list. If you want to export a single variable
or function, use __declspec(export) at the beginning of the dec-
laration
For example, this code fragment use #pragma export on and off
to export the variable w and the functions a1() and b1():
#pragma export on
int a1(int x, double y);
double b1(int z);
int w;
#pragma export off
extended_errorcheck
Description Controls the issuing of warnings for possible unintended logical er-
rors.
void main()
{
printf ("hello world\n");
}
d = 5; /* WARNING */
d = Monday; /* OK */
d = (Day)3; /* OK */
// . . .
}
int MyInit(void)
{
int err = GetMyResources();
if (err!=0) return -1; // OK
// . . .
}
far_data
Description Controls the use of 32-bit addressing to refer to global data.
Remarks If this pragma is on, you can have any amount of global data since
the compiler uses 32-bit addressing to refer to globals instead of 16-
bit addressing. Your program will also be slightly bigger and
slower. this pragma is off, your global data is stored as near data
and add to the 64K limit on near data.
This pragma corresponds to the Far Data option in the 68K Proces-
sor settings panel. To check whether this option is on, use
__option (far_data), described in “Checking Options” on page
202.
far_strings
Description Controls the use of 32-bit addressing to refer to string literals.
Remarks If this pragma is on, you can have any number of string literals since
the compiler uses 32-bit addressing to refer to string literals, instead
of 16-bit addressing. Your program will also be slightly bigger and
slower. If this pragma is off, your string literals are stored as near
data and add to the 64K limit on near data.
far_vtables
Description Controls the use of 32-bit addressing for C++ virtual function tables.
faster_pch_gen
Description Controls the performance of precompiled header generation.
float_constants
Description Controls how floating pointing constants are treated.
Remarks If this option is on, the compiler assumes that all unqualified float-
ing point constant values are of type float, not double.
This pragma is useful when working with source code compiled for
the AMD K6 processors.
For related information, see “The “D” Constant Suffix” on page 53.
force_active
Description Controls how “dead” functions are linked.
If this option is on, the linker will not strip the following functions
out of the finished application, even if the functions are never called
in the program.
fourbyteints
Description Controls the size of the int data type.
Remarks When this option is on, the size of an int is 4 bytes. When this op-
tion is off, the size of an int is 2 byes.
This pragma corresponds to the 4-Byte Ints option in the 68K Pro-
cessor settings panel. To check whether this option is on, use
__option (fourbyteints), described in “Checking Options” on
page 202.
fp_contract
Description Controls the use of special floating point instructions to improve
performance.
register double A, B, C, D, Y, Z;
register double T1, T2;
A = C = 2.0e23;
B = D = 3.0e23;
Y = (A * B) - (C * D);
printf("Y = %f\n", Y);
/* prints 2126770058756096187563369299968.000000 */
T1 = (A * B);
T2 = (C * D);
Z = T1 - T2;
printf("Z = %f\n", Z); /* prints 0.000000 */
fp_pilot_traps
Description Controls floating point code generation for Palm OS.
Remarks This pragma controls floating point code generation. If on, the com-
piler makes references to Palm OS library routines to perform float-
ing point operations.
function
Description Ignored but included for compatibility with Microsoft compilers.
global_optimizer, optimization_level
Description Controls optimization.
Remarks These pragmas control the global optimizer performs. To turn the
global optimizer on and off, use the pragma global_optimizer.
To choose which optimizations the global optimizer performs, use
the pragma optimization_level with an argument from 1 to 5.
The higher the argument, the more optimizations that the global op-
timizer performs. If the global optimizer is turned off, the compiler
ignores the pragma optimization_level.
IEEEdoubles
Description Specifies the size of the double type.
Remarks This option, along with the 68881 Codegen option, specifies the
length of a double. The table below shows how these options work:
If IEEEDoubles and code68881 Then a double is this
is… is… size…
on on or off 64 bits
off off 80 bits
off on 96 bits
ignore_oldstyle
Description Controls the recognition of function declaration that follow the con-
vention before ANS/ISO C.
#pragma ignore_oldstyle on
f(x, y, z)
char x;
short y;
float z;
{
return (int)x+y+z;
}
import
Description Controls or specifies the availability of imported symbols.
This pragma lets you import variables and functions that are in
other fragments. Use this to import symbols that have been ex-
ported with the export pragma, an .exp file, or the Export Sym-
bols menu in the CFM68K and PPC PEF settings panel.
If you want to import all the functions and variables declared or de-
fine within a certain range, use #pragma import on at the begin-
ning of the range and use #pragma import off at the end of the
range. If you want to import all the functions and variables in a list,
use #pragma import list. If you want to import a single vari-
able or function, use __declspec(external) at the beginning of
the declaration
int w;
#pragma import list a1, b1, w
init_seg
Description Controls the order in which initialization code is executed.
Remarks This pragma controls the order in which initialization code is exe-
cuted.The initialization code for a C++ compiled module calls con-
structors for any statically declared objects. For C, no initialization
code is generated.
inline_depth
Description Controls how deeply inline function calls are expanded.
Remarks Sets the number of passes used to expand inline function calls. The
number n is an integer from 0 to 1024 or the smart specifier.
The smart specifier is the default mode, with 4 passes where the
passes 2-4 are limited to small inline functions. All inlineable func-
tions are expanded if inline_depth is set to 1-1024.
inline_intrinsics
Description Controls the inlining of intrinsic functions.
Remarks When this option is on, the compiler directly generates intrinsic
functions without generating a function call.
internal
Description Controls the availability of symbols outside a module.
This pragma lets you specify that certain variables and functions are
internal and not imported. The compiler generates smaller and
faster code when it calls an internal function, even if you declared it
as extern.
If you want to declare all the functions and variables declared or de-
fine within a certain range as internal, use #pragma internal on
at the beginning of the range and use #pragma internal off at
the end of the range. If you want to declare all the functions and
variables in a list as internal, use #pragma internal list. If you
want to declare a single variable or function as internal, use
__declspec(internal) at the beginning of the declaration.
int w;
#pragma internal list a1, b1, w
interrupt
Description Controls the compilation of object code for interrupt routines.
Remarks When this option is on, the compiler generates a special prologue
and epilogue for these functions: all modified registers (both non-
volatile and scratch registers) are saved or restored, and the func-
tion returns via RETI instead of JMP [LP].
For convenience, the compiler will also mark any interrupt function
so that the linker does not dead-strip it.
k63d
Description Controls special code generation for AMD K6 3D extensions.
Remarks This pragma tells the x86 compiler to generate code for AMD K6 3D
extensions. This option causes the compiler to generate code that
will only run on processors that are equipped with the circuitry
needed to execute the specialized 3D instructions.
To learn more about this pragma, read the Targeting Win32 manual.
k63d_calls
Description Controls use of AMD K6 3D calling conventions.
Remarks This pragma tells the x86 compiler to generate code for AMD K6 3D
and Intel MMX extensions. This option causes the compiler to gen-
erate code that will only run on processors that are equipped with
the circuitry needed to execute these specialized instruction sets.
This pragma generates code that requires fewer register operations
at mode switching time.
To learn more about this pragma, read the Targeting Win32 manual.
lib_export
Description Controls the recognition of the export, import, and internal
pragmas.
If this pragma is off, the compiler ignores the pragmas export, im-
port, and internal. It is available for compatibility with previous ver-
sions of the compiler. It corresponds to the
__declspec(lib_export) type qualifier, described in “ANSI
Keywords Only” on page 41. To check whether this option is on, use
__option (lib_export), described in “Checking Options” on
page 202.
longlong
Description Controls the availability of the long long type.
Remarks When the longlong pragma is on, the C or C++ compiler lets you
define a 64-bit integer with the type specifier long long. This is
twice as large as a long int, which is a 32-bit integer. A long long
can hold values from -9,223,372,036,854,775,808 to
longlong_enums
Description Controls whether or not enumerated types are the size of the long
long type.
Remarks This pragma lets you use enumerators that large enough to be long
long integers. It’s ignored if the enumsalwaysint pragma is on
(described in “enumsalwaysint” on page 117).
longlong_prepval
Description Controls whether or not the preprocessor treats expressions of type
long as long long instead.
Remarks When this option is on, the C/C++ preprocessor treats expressions
of type long as type long long instead.
macsbug, oldstyle_symbols
Description Control the generation of debugger data for MacsBug.
These pragmas let you choose how the compiler generates Macsbug
symbols. Many debuggers, including Metrowerks debugger, use
Macsbug symbols to display the names of functions and variables.
The pragma macsbug lets you turn on and off Macsbug generation.
The pragma oldstyle_symbols lets you choose which type of
symbols to generate. The table below shows how these pragmas
work:
To do this… Use these pragmas…
Do not generate Macsbug #pragma macsbug on
symbols
mark
Description Adds an item to the Function pop-up menu in the IDE’s editor win-
dow.
Remarks This pragma adds itemName to the source file’s Function pop-up
menu. If you open the file in the CodeWarrior Editor and select the
item from the Function pop-up menu, the editor brings you to the
pragma. Note that if the pragma is inside a function definition, the
item will not appear in the Function pop-up menu.
message
Description Issues a text message to the user.
Remarks This pragma tells the compiler to issue a message, text, to the user.
When running under the CodeWarrior IDE, the message appears in
the Errors & Warnings window.
microsoft_exceptions
Description Controls the use of Microsoft C++ exception handling.
Remarks This pragma tells the x86 compiler to generate exception handling
code that is compatible with Microsoft C++ exception handling
code.
microsoft_RTTI
Description Controls the use of Microsoft C++ runtime type information.
Remarks This pragma tells the x86 compiler to generate runtime type infor-
mation that is compatible with Microsoft C++.
mmx
Description Controls special code generation Intel MMX extensions.
Remarks This pragma tells the x86 compiler to generate code for Intel MMX
extensions. This option causes the compiler to generate code that
will only run on processors that are equipped with the circuitry
needed to execute the more than 50 specialized MMX instructions.
To learn more about this pragma, read the Targeting Win32 manual.
mmx_call
Description Controls the use of MMX calling conventions.
Remarks When this pragma is on, the compiler favors the use of MMX calling
conventions.
To learn more about this pragma, read the Targeting Win32 manual.
mpwc
Description Controls the use Apple’s MPW C calling conventions.
When the pragma mpwc is on, the compiler does the following to be
compatible with MPW C’s calling conventions:
• Passes any integral argument that is smaller than 2 bytes as a
sign-extended long integer. For example, the compiler
converts this declaration:
int MPWfunc ( char a, short b, int c, long d, char *e );
• To this:
long MPWfunc( long a, long b, long c, long d, char *e );
• To this:
void MPWfunc( long double a, long double b, long double c );
mpwc_newline
Description Controls the use new line character convention used by Apple’s
MPW C.
Remarks If you turn on the pragma mpwc_newline, the compiler uses the
MPW conventions for the '\n' and '\r' characters. If this pragma
is off, the compiler uses the Metrowerks C and C++ conventions for
these characters.
If you want to turn this pragma on, be sure you use the ANSI C and
C++ libraries that were compiled with this option on. The 68K ver-
sions of these libraries are marked with an NL; for example, MSL
C.68K (NL_2i).Lib. The PowerPC versions of these libraries are
marked with NL; for example, MSL C.PPC (NL).Lib.
If you turn this pragma on and use the standard ANSI C and C++ li-
braries, you won’t be able to read and write '\n' and '\r' prop-
erly. For example, printing '\n' brings you to the beginning of the
current line instead of inserting a new line.
mpwc_relax
Description Controls the compatibility of the char* and unsigned char*
types.
Remarks When you turn on this pragma, the compiler treats char* and un-
signed char* as the same type. This option is especially useful if
you’re using code written before the ANSI C standard. This old
source code frequently used these types interchangeably.
no_register_coloring
Description Controls the use of a register to hold the values of more than one
variable.
However, if a line like the one below appears anywhere in the func-
tion, the compiler would realize that you’re using i and j at the
same time and place them in different registers:
int k = i + j;
no_static_dtors
Description Controls the generation of static destructors in C++
Remarks When this option is on, the compiler does not generate object code
for any static or global object destructors, reducing the size of the
object code.
once
Description Specifies if a header file may be included more than once in the
same source file.
Remarks Use this pragma to ensure that the compiler includes header files
only once in a source file. This pragma is especially useful in pre-
compiled header files.
only_std_keywords
Description Controls the use of ANSI/ISO keywords.
opt_common_subs
Description Controls the use of common subexpression optimization.
Remarks When this option is on, the compiler replaces similar redundant ex-
pressions with a single expression. For example, if two statements in
a function both use the expression
a * b * c + 10
opt_dead_assignments
Description Controls the use of dead store optimization.
Remarks When this option is on, the compiler removes assignments to vari-
ables if the variables are not used before being reassigned.
opt_dead_code
Description Controls the use of dead code optimization.
Remarks When this option is on, the compiler removes statements that, logi-
cally, will never be executed or is never referred to by other state-
ments.
opt_lifetimes
Description Controls the use of lifetime analysis optimization.
Remarks When this option is on, the compiler uses the same processor regis-
ter for different variables in the same routine if the variables aren’t
used in the same statement.
opt_loop_invariants
Description Controls the use of loop invariant optimization.
Remarks When this option is on, the compiler moves computations that don’t
change on the inside of a loop to the outside of a loop to improve the
loop’s speed.
opt_propagation
Description Controls the use of copy and constant propagation optimization.
Remarks When this option is on, the compiler replaces multiple occurrences
of one variable with a single occurrence.
opt_strength_reduction
Description Controls the use of strength reduction optimization.
opt_unroll_loops
Description Controls the use of loop unrolling optimization.
opt_vectorize_loops
Description Controls the use of loop vectorizing optimization.
optimization_level
See the pragma global_optimizer, described in
“global_optimizer, optimization_level” on page 129.
optimize_for_size
Description Controls optimization to reduce the size of object code.
Remarks This option lets you choose what the compiler does when it must
decide between creating small code or fast code. If this option is on,
the compiler creates smaller object code at the expense of speed. If
this option is off, the compiler creates faster object code at the ex-
pense of size.
Most significantly if this option is on, the compiler ignores the in-
line directive, and generates function calls to call any function de-
clared inline.
oldstyle_symbols
See “macsbug, oldstyle_symbols” on page 140 for information
about this pragma.
pack
Description Controls the alignment of data structures.
Remarks Sets the packing alignment for data structures. It affects all data
structures declared after this pragma until you change it again with
another pack pragma.
This pragma… Does this…
#pragma pack(n) Sets the alignment modulus to n,
where n may be 1, 2, 4, 8 or 16. For
MIPS compilers, if n is 0, structure
alignment is reset to the default
setting.
#pragma pack(push, n) Pushes the current alignment mod-
ulus on a stack, then sets it to n,
where n may be 1, 2, 4, 8 or 16.
Use push and pop when you need
a specific modulus for some decla-
ration or set of declarations, but do
not want to disturb the default set-
ting. This form is not supported by
the MIPS compilers.
#pragma pack(pop) Pops a previously pushed align-
ment modulus from the stack. This
form is not supported by the MIPS
compilers.
#pragma pack() For x86 compilers, resets align-
ment modulus to the value speci-
fied in the x86 CodeGen settings
panel. For MIPS compilers, resets
structure alignment to the default
setting.
parameter
Description Specifies the use of registers to pass parameters.
The compiler passes the parameters for the function func-name in the
registers specified in param-regs instead of the stack, and returns any
return value in the register return-reg. Both return-reg and param-regs
are optional.
When you define the function, you need to specify the registers
right in the parameter list, as described in the appropriate Targeting
manual.
pcrelstrings
Description Controls the storage and reference of string literals from the pro-
gram counter.
Remarks If this option is on, the compiler stores the string constants used in a
local scope in the code segment and addresses these strings with
PC-relative instructions. If this option is off, the compiler stores all
peephole
Description Controls the use peephole optimization.
pointers_in_A0, pointers_in_D0
Description Controls which calling convention to use.
Remarks These pragmas are available for Mac OS on 68K processors only.
These pragmas let you choose between two calling conventions: the
convention for MPW and Macintosh Toolbox routines and the con-
vention for Metrowerks C and C++ routines. In the MPW and Mac-
intosh Toolbox calling convention, functions return pointers in the
register DO. In the Metrowerks C and C++ convention, functions re-
turn pointers in the register A0.
pool_data
Description Controls how data is stored.
This pragma corresponds to the Pool Data option in the PPC Pro-
cessor settings panel. To check whether this option is on, use
__option (pool_data), described in “Checking Options” on
page 202.
pool_strings
Description Controls how string literals are stored.
pop, push
Description Save and restore pragma settings.
Remarks The pragma push saves all the current pragma settings. The pragma
pop restores all the pragma settings to what they were at the last
push pragma. For example, see Listing 6.4.
These pragmas are available so you can use MacApp with Metro-
werks C and C++. If you’re writing new code and need to set a
pragma option to its original value, use the reset argument, de-
scribed in “Pragma Syntax” on page 90.
precompile_target
Description Specifies the file name for a precompiled header file.
Listing 6.5 shows sample source code from the MacHeaders pre-
compiled header source file. By using the predefined symbols
__cplusplus and powerc and the pragma precompile_target,
the compiler can use the same source code to create different pre-
compiled header files for C and C++, 680x0 and PowerPC.
profile
Description Controls the generation of extra object code for use with the
CodeWarrior profiler.
If this pragma is on, the compiler generates code for each function
that lets the Metrowerks Profiler collect information on it. For more
information, see the Metrowerks Profiler Manual.
readonly_strings
Description Controls how to store string literals.
Remarks This option determines where to stores string constants. If this op-
tion is off, the compiler stores string constants in the data section. If
this option is on, the compiler stores string constants in the code sec-
tion.
register_coloring
Description Controls whether the use of register coloring.
Remarks When this pragma is on, the compiler uses a single register to hold
the value of more than one variable if those variables are never used
in the same statement to improve a program’s performance.
require_prototypes
Description Controls whether or not the compiler should expect function proto-
types.
This pragma helps you prevent errors that happen when you use a
function before you define it.
RTTI
Description Controls the availability of runtime type information.
Remarks When this pragma is on, you can use runtime type information (or
RTTI) features, such as dyanamic_cast and typeid. The other
RTTI expressions are available even if the Enable RTTI option is off.
Note that *type_info::before(const type_info&) is not
yet implemented.
scheduling
Description Specifies the use of instruction scheduling optimization.
Remarks This pragma lets you choose how the compiler rearranges instruc-
tions to increase speed. Some instructions, such as a memory load,
take more than one processor cycle. By moving an unrelated in-
struction between the load and the instruction that uses the loaded
item, the compiler saves a cycle when executing the program.
For PowerPC, you can use 601, 603, or 604. If you use on, the com-
piler performs 601 scheduling.
section
Description Controls the organization of object code.
Parameters
Specify one or more of these object types without quotes and sepa-
rated by spaces.
The uname parameter may be changed. For example, you may want
most uninitialized data to go into the “.bss” section while specific
variables be stored in the COMM section. Listing 6.6 shows an exam-
ple of specifying that specific uninitialized variables be stored in the
COMM section.
You may not use any of the object types, data modes, or code modes
as the names of sections. Also, you may not use pre-defined section
names in the PowerPC EABI for your own section names.
When you define a section using #pragma section, its default ac-
cess permission is read only. If you change the current section for a
particular object type, the compiler adjusts the access permission to
allow the storage of objects of that type while continuing to allow
objects of previously-allowed object types. Associating code_type
to a section adds execute permission to that section. Associating
data_type, sdata_type, or sconst_type to a section adds write
permission to that section.
The predefined sections set with an object type become the default
section for that type. After assigning a non-standard section to an
object type, you may rever to the default section with one of the
forms in “Forms for #pragma section” on page 172.
With the addition of one or more object types, the compiler stores
objects of the types specified in the section “.name2”. If “.name2”
doesn’t exist, the compiler creates it with the appropriate access per-
missions. If only one section name is specified, it is considered the
name of the initialized object section, iname. If the section is already
declared, you may also optionally specify the uninitialized object
section, unameThis feature is useful for temporarily circumventing
the small data threshold.
#pragma section objecttype
You may store a specific object of an object type into a section other
than the current section for that type without changing the current
section. Use the __declspec keyword with the name of the target
section and put it next to the extern declaration or static definition of
the item you want to store in the section. Listing 6.8 shows exam-
ples.
This pragma may be used with #pragma push and #pragma pop
to ease complex or frequent changes to sections settings. See Listing
6.6 for an example. Note that #pragma pop doesn’t restore any
changes to the access permissions of sections that exists before or
after the corresponding #pragma push.
segment
Description Specifies the code segment where subsequent object code should be
stored.
This pragma places all the functions that follow into the code seg-
ment named name. For more on function-level segmentation, con-
sult the Targeting manual for the platform you’re developing for.
side_effects
Description Controls the use of pointer aliases.
Remarks If your program does not use pointer aliases, turn off this pragma to
make your program smaller and faster. If your program does use
pointer aliases, turn on this pragma to avoid incorrect code. A
pointer alias looks like this:
int a, *p;
p = &a; // *p is an alias for a.
simple_prepdump
Description Controls the suppression of comments in preprocessor dumps.
Remarks By default, the preprocessor adds comments about the current in-
clude file being processed in its output. These comments can be dis-
abled by turning this pragma on.
SOMCallOptimization
Description Controls the error checking used for making calls to SOM objects.
Remarks This pragma is only available for Mac OS using C++ code.
SOMCallStyle
Description Specifies the convention used to call SOM objects.
Remarks This pragma is only available for Mac OS using C++ code.
If a class uses the IDL style, its methods must have an Environment
pointer as the first parameter. Note that the SOMClass and SOMOb-
ject classes use OIDL, so if you override a method from one of them,
you should not include the Environment pointer.
SOMCheckEnvironment
Description Controls whether or not to perform SOM environment checking.
Remarks This pragma is only available for Mac OS using C++ code.
First, the compiler calls the method and stores the result in a tempo-
rary variable. Then it checks the environment pointer. Finally, it re-
turns the method’s result.
SOMClassVersion
Description Specifies a SOM class’s version.
Remarks This pragma is only available for Mac OS using C++ code.
SOM uses the class’s version number to make sure the class is com-
patible with other software you’re using. If you don’t declare the
version numbers, SOM assumes zeroes. The version numbers must
be positive or zero.
When you define the class, the program passes its version number
to the SOM kernel in the class’s metadata. When you instantiate an
object of the class, the program passes the version to the runtime
kernel, which checks to make sure the class is compatible with the
running software.
SOMMetaClass
Description Specifies a SOM class’s metaclass.
Remarks This pragma is only available for Mac OS using C++ code.
SOMReleaseOrder
Description Specifies the order in which a SOM class’s member functions are re-
leased.
Remarks This pragma is only available for Mac OS using C++ code.
A SOM class must specify the release order of its member functions.
As a convenience for when you’re first developing the class,
Metrowerks C++ lets you leave out the SOMReleaseOrder pragma
and assumes the release order is the same as the order in which the
functions appear in the class declaration. However, when you re-
lease a version of the class, use the pragma, since you’ll need to
modify its list in later versions of the class.
You must specify every SOM method that the class introduces. Do
not specify inline member functions that are virtual, since they’re
not considered to be SOM methods. Don’t specify overridden func-
tions.
If you remove a function from a later version of the class, leave its
name in the release order list. If you add a function, place it at the
end of the list. If you move a function up in the class hierarchy,
leave it in the original list and add it to the list for the new class.
stack_cleanup
Description Controls when the compiler generates code to clean up the stack.
Remarks Turning this option on will disable the deferred stack cleanup after
function calls, forcing the compiler to remove arguments from the
stack after every function call. Although this option slows down ex-
ecution, it reduces stack usage, making it less likely the stack will in-
trude on other parts of the program.
static_inlines
Description Controls how many instances of inline functions that the compiler
generates.
This pragma is available only so that the compiler can pass certain
validation suites. Generally, you’ll want to leave this pragma off to
make your code smaller without any loss of speed.
suppress_init_code
Description Controls the suppression of static initialization object code.
Remarks When this pragma is on, the compiler doesn’t generate any code for
static data initialization such as C++ constructors. By default this
pragma is off.
sym
Description Controls the generation of debugger symbol information.
Remarks The compiler pays attention to this pragma only if you turn on the
debug marker for a file in the IDE’s project window. If this pragma
is off, the compiler does not put debugging information into this
source file’s debugger symbol file (SYM or DWARF) for the func-
tions that follow. If this pragma is on, the compiler does generate
debugging information.
Note that the compiler always generates a debugger symbol file for
a source file that has a debug diamond next to it in the project win-
dow. This pragma changes only which functions have information
in that symbol file.
syspath_once
Description Controls how include files are treated.
Remarks Files referred to in #include <> and #include "" directives are
treated as distinct files if this option is selected, even if they refer to
the same file.
toc_data
Description Controls how static variables are stored.
trigraphs
Description Controls the use ANSI/ISO trigraph sequences.
Remarks If you’re writing code that must follow the ANSI standard strictly,
turn on the pragma trigraphs in the C/C++ Language Panel.
Many common Macintosh character constants look like trigraph se-
quences, and this pragma lets you use them without including es-
cape characters. Be careful when you initialize strings or multi-char-
acter constants that contain question marks. For example:
char c = '????'; // ERROR: Trigraph sequence expands to '??^
char d = '\?\?\?\?'; // OK
traceback
Description Controls the generation of AIX-format traceback tables for debug-
ging.
Remarks This pragma helps other people debug your application or shared
library if you do not distribute the source code. If this option is on,
the compiler generates an AIX-format traceback table for each func-
tion, which are placed in the executable code. Both the Metrowerks
and Apple debuggers can use traceback tables.
unsigned_char
Description Controls whether or not declarations of type char are treated as
unsigned char.
NOTE: If you turn this pragma on, your code may not be compat-
ible with libraries that were compiled with it turned off. In particular,
your code may not work with the ANSI libraries included with
CodeWarrior.
unused
Description Controls the suppression of warnings for variables and parameters
that aren’t referenced in a function.
Remarks This pragma suppresses the compile time warnings for the unused
variables and parameters specified in its argument list. You can use
this pragma only within a function body, and the listed variables
must be within the function’s scope. You cannot use this pragma
with functions defined within a class definition or with template
functions. For example:
#pragma warn_unusedvar on
#pragma warn_unusedarg on
use_fp_instructions
Description Controls the generation of NEC V800 floating point instructions.
Remarks This option corresponds to the option Use V810 Floating-Point In-
structions, which is part of the NEC V800 Processor panel. To check
whether this option is on, use __option
(use_fp_instructions), described in “Checking Options” on
page 202.
use_frame
Description Controls the use of the BP register for stack frames.
Remarks When this option is on the compiler uses the BP register to point to
the start of the stack frame.
use_mask_registers
Description Controls the use of the NEC V800 r20 and r21 registers.
Remarks This option corresponds to the option Use r20 and r21 as Mask Reg-
isters, which is part of the NEC V800 Processor panel. To check
whether this option is on, use __option
warn_emptydecl
Description Controls the recognition of declarations without variables.
warning_errors
Description Controls whether warnings are treated as errors or not.
Remarks When the pragma warning_errors is on, the compiler treats all
warnings as though they were errors. It will not compile a file until
all warnings are resolved.
warn_extracomma
Description Controls the recognition of superfluous commas.
warn_hidevirtual
Description Controls the recognition of a non-virtual member function that
hides a virtual function in a superclass.
class B: public A {
public:
void f(char); // WARNING: Hides A::f(int)
virtual void g(int); // OK: Overrides A::g(int)
};
warn_illpragma
Description Controls the recognition of illegal pragma directives.
warn_implicitconv
Description Controls the issuing of warnings for implicit arithmetic conversions.
Remarks The compiler will print a warning for implicit arithmetic conver-
sions when the source value may not be representable by the desti-
nation type. See Listing 6.9 for an example.
char foo(int a)
{
return a+1; // Warning : implicit arithmetic conversion ...
// ... from 'int' to 'char'
}
warn_notinlined
Description Controls the issuing of warnings for functions the compiler isn’t
able to inline.
Remarks The compiler will issue a warning if it is not able to inline a function.
This pragma corresponds to the Non-Inlined Functions option in
the C/C++ Warnings settings panel. To check whether this option is
on, use __option (warn_notinlined), described in “Checking
Options” on page 202.
warn_padding
Description Controls the notification of the padding of data structures.
Remarks If the pragma warn_padding is on, the compiler warns about any
bytes it adds to data structures to improve their alignment in mem-
ory. Refer to the appropriate Targeting manual for more information
on how CodeWarrior C++ pads data structures for a particular pro-
cessor or operating system.
warn_possunwant
Description Controls the recognition of possible unintentional logical errors.
warn_structclass
Description Controls the issuing of warnings for possibly unintended mixing of
class and struct keywords.
warn_unusedarg
Description Controls the recognition of unreferenced arguments.
warn_unusedvar
Description Controls the recognition of unreferenced variables.
warning
Description Available for compatibility only.
• 4
• disable
• error
wchar_type
Description Controls the size and format of the wchar_t type.
Predefined Symbols
Metrowerks C and C++ define several preprocessor symbols that
give you information about the compile-time environment. Note
that these symbols are evaluated at compile time and not at run
time. The topics in this section are:
• ANSI Predefined Symbols
• Metrowerks Predefined Symbols
Listing 6.10 shows a small program that uses the ANSI predefined
symbols.
void main(void)
{
printf("Hello World!\n");
Hello World!
Oct 31 1995, 18:23:50
main.ANSI.c, line: 10
Checking Options
The preprocessor function __option() lets you test the setting of
many pragmas and options that control the C/C++ compiler and
code generation. You typically modify these settings using various
panels in the Project Settings dialog box.
This function is useful when you want one source file to contain
code that uses different option settings. The example below shows
how to compile one series of lines if you’re compiling for machines
with the MC68881 floating-point unit and another series if you’re
compiling for machines without out:
#if __option (code68881) // Code for 68K chip with FPU
#else
// Code for any 68K processor
#endif
The table below lists all the option names you can use in the prepro-
cessor function __option().
C Compilers Reference
Credits
writing lead: Marc Paquette
other writers: Mark Anderson, Gene Backlin, BitHead,
Jeff Mattson, Jim Trudeau
engineering: Mark Anderson, Bob Campbell, Ben
Combee, Pascal Cleve, Rajeev Gulati, An-
dreas Hommel, Udi Kalekin, Michael
Kahl, Bob Kushlis, John McEnerney, Fred
Peterson, Laurent Visconti, Rhonda Wit-
tels
frontline warriors: Richard Atwell, John C. Daub, Ron
Liechty, John Roseborough, Joel Sumner,
Jim Trudeau, L. Frank Turovich,
CodeWarrior users everywhere
Guide to CodeWarrior Documentation
CodeWarrior documentation is modular, like the underlying tools. There are manuals
for the core tools, languages, libraries, and targets. The exact documentation provided
with any CodeWarrior product is tailored to the tools included with the product. Your
product will not have every manual listed here. However, you will probably have addi-
tional manuals (not listed here) for utilities or other software specific to your product.
Core Documentation
IDE User Guide How to use the CodeWarrior IDE
Debugger User Guide How to use the CodeWarrior debugger
CodeWarrior Core Tutorials Step-by-step introduction to IDE components
Language/Compiler Documentation
C Compilers Reference Information on the C/C++ front-end compiler
Pascal Compilers Reference Information on the Pascal front-end compiler
Error Reference Comprehensive list of compiler/linker error messages, with many fixes
Pascal Language Reference The Metrowerks implementation of ANS Pascal
Assembler Guide Stand-alone assembler syntax
Command-Line Tools Reference Command-line options for Mac OS and Be compilers
Plugin API Manual The CodeWarrior plugin compiler/linker API
Library Documentation
MSL C Reference Function reference for the Metrowerks ANSI standard C library
MSL C++ Reference Function reference for the Metrowerks ANSI standard C++ library
Pascal Library Reference Function reference for the Metrowerks ANS Pascal library
MFC Reference Reference for the Microsoft Foundation Classes for Win32
Win32 SDK Reference Microsoft’s Reference for the Win32 API
The PowerPlant Book Introductory guide to the Metrowerks application framework for Mac OS
PowerPlant Advanced Topics Advanced topics in PowerPlant programming for Mac OS
Targeting Manuals
Targeting BeOS How to use CodeWarrior to program for BeOS
Targeting Java VM How to use CodeWarrior to program for the Java Virtual Machine
Targeting Mac OS How to use CodeWarrior to program for Mac OS
Targeting MIPS How to use CodeWarrior to program for MIPS embedded processors
Targeting NEC V810/830 How to use CodeWarrior to program for NEC V810/830 processors
Targeting Net Yaroze How to use CodeWarrior to program for Net Yaroze game console
Targeting Nucleus How to use CodeWarrior to program for the Nucleus RTOS
Targeting OS-9 How to use CodeWarrior to program for the OS-9 RTOS
Targeting Palm OS How to use CodeWarrior to program for PalmPilot
Targeting PlayStation OS How to use CodeWarrior to program for the PlayStation game console
Targeting PowerPC Embedded Systems How to use CodeWarrior to program for PPC embedded processors
Targeting VxWorks How to use CodeWarrior to program for the VxWorks RTOS
Targeting Win32 How to use CodeWarrior to program for Windows