s.paszko
s.paszko

Reputation: 732

How to catch undefined macro in preprocessor #if condition?

Based on this question How to catch empty defined macro with gcc? I have another problem. How to catch undefined macro in preprocessor #if condition? Example code:

#include <stdio.h> 

int main()
{
#if ENABLE_SOMETHING == 1
    ... do something ..
#endif
 return 0;
}

Is there a way to catch error/warning when ENABLE_SOMETHING is not set using gcc compiler(maybe some flag)? Or maybe there are external tools which I can use?


I know than i can write something like this :

#ifndef ENABLE_SOMETHING
    #error "ENABLE_SOMETHING undefined!"
#endif

But I have a huge amount of different defines(ENABLE_STH1, ENABLE_STH2, ENALBE_STH3 ... etc.) in code and i don't want to fix this manually. I'm looking for some automatic solution for our project.

Upvotes: 11

Views: 5951

Answers (4)

Morten Jensen
Morten Jensen

Reputation: 5936

Is there a way to catch error/warning when ENABLE_SOMETHING is not set using gcc compiler(maybe some flag)?

With GCC you can use the -Wundef flag (clang supports it as well).

From the official documentation

-Wundef

Warn if an undefined identifier is evaluated in an #if directive. Such identifiers are replaced with zero.

EDIT:

For example, this C-code:

#include <stdio.h>

int main(void)
{
#if UNDEFINED_MACRO
  printf("hi mum!\n");
#endif

  return 0;
}

... compiled with GCC and the -Wundef flag yields this:

$ gcc undef.c -Wundef
undef.c: In function 'main':
undef.c:5:5: warning: "UNDEFINED_MACRO" is not defined [-Wundef]
 #if UNDEFINED_MACRO
     ^

Upvotes: 11

chqrlie
chqrlie

Reputation: 144550

You can test if a macro is defined in a #if preprocessor expression with defined(ENABLE_SOMETHING):

#if !defined(ENABLE_SOMETHING)
  #error ENABLE_SOMETHING is not defined
#endif

You can handle macros with an empty definition this way:

#if ENABLE_SOMETHING + 0 == 1
   /* ENABLE_SOMETHING is defined and not 0 or empty */
#endif

Upvotes: 0

David Collins
David Collins

Reputation: 3012

You could try something like the following:

#ifndef MAX_N_LENGTH
#warning "MAX_N_LENGTH is undefined"
    int array[16];
#else
    int array[MAX_N_LENGTH + 1];
#endif

Upvotes: 0

Blaze
Blaze

Reputation: 16876

Let's assume you have this code and it compiles, but you don't know if MAX_N_LENGTH is a macro, or if it's something else:

int main()
{
    int a = MAX_N_LENGTH; // MAX_N_LENGTH could also be an int declared somewhere else
    return 0;
}

You can check whether it actually is a macro like this:

#ifdef MAX_N_LENGTH
    printf("MAX_N_LENGTH is a macro.\n");
#else
    printf("MAX_N_LENGTH is NOT macro.\n");
#endif // MAX_N_LENGTH

Of course, if that ever is an issue, I'd rethink my naming conventions.

Upvotes: 0

Related Questions