Main Content

AUTOSAR C++14 Rule A16-0-1

The preprocessor shall only be used for unconditional and conditional file inclusion and include guards, and using specific directives

Description

Rule Definition

The preprocessor shall only be used for unconditional and conditional file inclusion and include guards, and using specific directives.

Rationale

Other than unconditional and conditional file inclusion and include guards, avoid the use of preprocessor directives. Use a safer alternative instead. For instance:

  • Instead of:

    #define MIN(a,b) ((a < b)? (a) : (b))
    You can use inline functions and function templates.

  • Instead of:

    #define MAX_ARRAY_SIZE 1024U
    You can use a constant object.

In these situations, preprocessor directives do not provide the benefits that the alternatives provide, such as linkage, type checking, overloading, and so on.

Polyspace Implementation

The rule checker does not allow the use of preprocessor directives. The only exceptions are:

  • #ifdef, #ifndef, #if, #if defined, #elif, #else and #endif, only if used for conditional file inclusion and include guards.

  • #define only if used for defining macros to be used in include guards. For instance, in this example, the macro __FILE_H__ prevents the contents of the header file from being included more than once:

    /* aHeader.h */
    
    #ifndef __FILE_H__
    #define __FILE_H__
       /* Contents of header file */   
    #endif
    

    When #ifdef, #define and #endif are used as include guards in a header file, the entire content of the header file must be in the include guard.

  • #include

The checker does not allow the #define directives in other contexts. If you use #define-s for purposes other than for include guards, do one of the following:

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdint>       //Compliant: unconditional file inclusion

#ifdef WIN32             //Compliant: include guard
   #include <windows.h>  //Compliant: conditional file inclusion
#endif                   

#ifdef WIN32     //Noncompliant
    std::int32_t func(std::int16_t x, std::int16_t y) noexcept; 
#endif

In this example, the rule is not violated when preprocessor directives are used for unconditional and conditional inclusion and include guards. Otherwise, the rule is violated.

Check Information

Group: Preprocessing directives
Category: Required, Automated

Version History

Introduced in R2019b