Search code examples
c++cifndef

possible to use #ifndef on a function name?


I'm working with MicroPython and their header files use a ton of

#ifndef function_name
void function_name(const char *str, size_t len);
#endif

Using both an online C and C++ compiler, I tried the following code to test this in both C++

#include <iostream>
using namespace std;

void func();    

#ifndef func
int a = 5;
#else
int a = 3;
#endif    

int main()
{
  cout << "a = " << a << endl;
}

And in C

#include <stdio.h>

void func();


#ifndef func
int a = 5;
#else
int a = 3;
#endif


int main()
{
    printf("Hello World");
    printf("a = %d\n", a);
    return 0;
}

and both times, I got 5 which means using #ifndef on function names doesn't work.

QUESTION

Is there some special compiler flag that enables this feature or do they have a bug?


Solution

  • #ifndef X checks if a macro with the name X has been defined. Function names and macro names belong to different name spaces. Presence or absence of function X would not affect #ifndef X.