开发者

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

开发者 https://www.devze.com 2023-03-10 03:26 出处:网络
Why doesn’t the following code work as expected? void foobar(int); #ifndef foobar printf(\"foobar exists\");

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 vari开发者_运维技巧ants) 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?


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号