Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
Synetech Avatar asked Jun 04 '11 04:06

Synetech


1 Answers

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
like image 192
dkackman Avatar answered Sep 21 '22 03:09

dkackman