simplecpp icon indicating copy to clipboard operation
simplecpp copied to clipboard

handling of defined() conditions nested in function like macros

Open illu89 opened this issue 8 years ago • 1 comments

defined() conditions in function like macros are not handled correctly.

minimal example, which expects __FOO__ to be defined or not.

#include <stdio.h>
#define macro(var) (defined(__ ## var ## __))

int main(void) {
  #if macro(FOO)
    printf("__FOO__ defined\r\n");
  #else
    printf("__FOO__ not defined\r\n");
  #endif
  return 0;
}

preprocessing with gcc gives:

# gcc  -D__FOO__ -E test.c
[...]
int main (void)  {
    printf("__FOO__ defined\r\n");
    return 0;
}

preprocessing with simplecpp gives

# simplecpp -D__FOO__ -E test.c
int main (  void  )  {
    printf( "__FOO__ not defined\r\n" ) ;
    return 0 ;
}

The real world code i encountered the problem with is in parts.h of atmel software framework. They expect the user to define the chip, software is being compiled for, as __chipname__ and derive family, series and product line from this.

short excerpt to clarify:

#define SAM_PART_IS_DEFINED(part) (defined(__ ## part ## __))
 [...]

/* SAM4S series */
#define SAM4S16 ( \
        SAM_PART_IS_DEFINED(SAM4S16B) || \
        SAM_PART_IS_DEFINED(SAM4S16C) \
        )
[...]

/* SAM4S Family */
#define SAM4S (SAM4S2 || SAM4S4 || SAM4S8 || SAM4S16 || SAM4SA16 || SAM4SD16 || SAM4SD32)
[...]

/* SAM product line */
#define SAM (SAM3S || SAM3U || SAM3N || SAM3XA || SAM4S || SAM4L || SAM4E || \
        SAM0 || SAM4N || SAM4C || SAM4CM || SAM4CP || SAMG)

So if __SAM4S16C__ was defined by -D__SAM4S16C__ the macros SAM4S16, SAM4S and SAM are expected to be set to 1

illu89 avatar Jun 01 '17 08:06 illu89

It now reports:

a.cpp:5: syntax error: failed to evaluate #if condition, undefined function-like macro invocation: defined( ... )

firewave avatar Jul 03 '25 10:07 firewave