180

I am compiling my program that will run on linux gcc 4.4.1 C99.

I was just putting my #defines in to separate the code that will be compiled on either windows or linux. However, I got this error.

error: macro names must be identifiers.

Using this code

#ifdef(WIN32)
/* Do windows stuff */
#elif(UNIX)
/* Do linux stuff */
#endif

However, when I changed to this the error was fixed:

#if defined(WIN32)
/* Do windows stuff */
#elif(UNIX)
/* Do linux stuff */
#endif

Why did I get that error and why the #defines are different?

4 Answers 4

256

If you use #ifdef syntax, remove the parenthesis.

The difference between the two is that #ifdef can only use a single condition,
while #if defined(NAME) can do compound conditionals.

For example in your case:

#if defined(WIN32) && !defined(UNIX)
/* Do windows stuff */
#elif defined(UNIX) && !defined(WIN32)
/* Do linux stuff */
#else
/* Error, both can't be defined or undefined same time */
#endif
4
  • 2
    yeah, but you could also cascade #ifdef UNIX with #ifndef WIN32, and get the same flexibility (not as readable, I agree)
    – jpinto3912
    Nov 11, 2009 at 11:42
  • 3
    @jpinto3912 But that gets even hairier with ||
    – Aidiakapi
    Jan 5, 2016 at 18:18
  • 2
    If only they had just gone with #if defined(NAME) from the start and avoided creating an #ifdef statement.
    – Andy
    Feb 20, 2018 at 7:47
  • Sourceforge has a good reference on pre-defined compiler macros.
    – vesperto
    May 23, 2022 at 10:54
72
#ifdef FOO

and

#if defined(FOO)

are the same,

but to do several things at once, you can use defined, like

#if defined(FOO) || defined(BAR)
36

#ifdef checks whether a macro by that name has been defined, #if evaluates the expression and checks for a true value

#define FOO 1
#define BAR 0

#ifdef FOO
#ifdef BAR
/* this will be compiled */
#endif
#endif

#if BAR
/* this won't */
#endif

#if FOO || BAR
/* this will */
#endif
3
  • 27
    This does not answer the question. The question asks for difference between #if defined and #ifdef.
    – Hassan
    Jun 12, 2017 at 7:57
  • 3
    This is the best explanation of how #if FOO and #if defined(FOO) can behave differently. Sep 30, 2019 at 22:47
  • 2
    A useful answer since it shows the subtle difference between #ifdef and #if
    – daparic
    Jul 16, 2021 at 18:44
0

With C23, you can use #elifdef and #elifndef:

#ifdef WIN32
/* Do windows stuff */
#elifdef UNIX
/* Do linux stuff */
#endif

Not the answer you're looking for? Browse other questions tagged or ask your own question.