Does #ifdef (or other Preprocessor Directives) Work for Function Declarations (to Test for Function Existence)?

半腔热情 提交于 2019-11-27 18:53:06

问题


Why doesn’t the following code work as expected?

void foobar(int);

#ifndef foobar
  printf("foobar exists");
#endif

It always prints the message; it obviously cannot detect the existence of a function as an entity. (Is it an over-loading issue?)

Why can’t #ifdef (or its variants) detect function declarations? Declarations should be available at pre-processing, so it should work, shouldn’t it? If not, is there an alternative or work-around?


回答1:


Declarations should be available at pre-processing, so it should work, shouldn’t it?

The pre-processor operates before the compilation (hence the "pre") so there are no compiled symbols at that point, just text and text expansion. The pre-procesor and the compiler are distinctly separate and work independantly of each other, except for the fact that the pre-processor modifies the source that is passed to the compiler.

The typical pattern to doing something like with the pre-processor is to pair the function declaration with the function usage using the same define constant:

#define FOO

#ifdef FOO
 void foo(int);
#endif

#ifdef FOO
   printf("foo exists");
#endif



回答2:


The pre-processor works against pre-processor tokens that are defined using pre-processor directives. The pre-processor does not work against types declared in your code (whatever the language may be).

You must use the #define preprocessor directive to declare a token visible to other pre-processor condition checks.

#define FOO

#if FOO
// this code will compile
int x = 5;
#else
// this code won't
int x = 10;
#endif


来源:https://stackoverflow.com/questions/6234755/does-ifdef-or-other-preprocessor-directives-work-for-function-declarations-t

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