How to catch undefined macro in preprocessor #if condition?

我怕爱的太早我们不能终老 提交于 2021-02-08 21:20:57

问题


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.


回答1:


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.

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
     ^



回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/54476352/how-to-catch-undefined-macro-in-preprocessor-if-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!