Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...