1

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?

Bob
  • 4,576
  • 7
  • 39
  • 107
  • 2
    " both times, I got 5 which means using #ifndef on function names doesn't work." - that's because it doesn't work. –  Feb 05 '18 at 23:17
  • 4
    `#if(n)def` only works with things declared with `#define`. So, I'm guessing that MicroPython allows `function_name` to be defined as a preprocessor macro, eg `#define function_name(str, len) ...`, and if it is not defined as a macro then `#ifndef function_name` is used to declare `function_name` as a real C/C++ function instead – Remy Lebeau Feb 05 '18 at 23:17
  • 1
    *"Is there some special compiler flag that enables this feature or do they have a bug?"* That's quite a wrong dichotomy. You just completely misunderstood what `#ifndef` does. – Baum mit Augen Feb 05 '18 at 23:18

1 Answers1

5

#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.

DYZ
  • 55,249
  • 10
  • 64
  • 93