广告
广告
require_prototypes
28.6 require_prototypes
Controls whether or not the compiler should expect function prototypes.
Syntax
#pragma require_prototypes on | off | reset
Remarks
This pragma only affects non-static functions.
If you enable this pragma, the compiler generates an error message if you use a function that does not have a preceding prototype. Use this pragma to prevent error messages caused by referring to a function before you define it. For example, without a function prototype, you might pass data of the wrong type. As a result, your code might not work as you expect even though it compiles without error.
In
Listing 28-2 on page 430 , function
main()
calls
PrintNum()
with an integer argument even though
PrintNum()
takes an argument of type float
.
Listing 28-2. Unnoticed Type-mismatch
#include <stdio.h> 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 program, you could get this result:
0.000000
Although the compiler does not complain about the type mismatch, the function does not give the result you intended. Since
PrintNum()
does not have a prototype, the compiler does not know to generate instructions to convert the integer to a floating-point number before calling
PrintNum()
. Consequently, the function interprets the bits it received as a floating-point number and prints nonsense.
CodeWarrior Development Studio for Power Architecture Processors Build Tools Reference Manual, Rev.
10.6, 02/2014
430 Freescale Semiconductor, Inc.
Chapter 28 Pragmas for Standard C Conformance
A prototype for
PrintNum()
, as in
, gives the compiler sufficient information about the function to generate instructions to properly convert its argument to a floating-point number. The function prints what you expected.
Listing 28-3. Using a Prototype to Avoid Type-mismatch
#include <stdio.h> void PrintNum(float x); /* Function prototype. */ void main(void)
{
PrintNum(1); /* Compiler converts int to float.
} Prints 1.000000. */ void PrintNum(float x)
{
printf("%f\n", x);
}
In other situations where automatic conversion is not possible, the compiler generates an error message if an argument does not match the data type required by a function prototype. Such a mismatched data type error is easier to locate at compile time than at runtime.
CodeWarrior Development Studio for Power Architecture Processors Build Tools Reference Manual, Rev.
10.6, 02/2014
Freescale Semiconductor, Inc.
431
require_prototypes
CodeWarrior Development Studio for Power Architecture Processors Build Tools Reference Manual, Rev.
10.6, 02/2014
432 Freescale Semiconductor, Inc.
广告