difference between #if defined(WIN32) and #ifdef(WIN32)

C

C Problem Overview


I am compiling my program that will running 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

I was just wondering why I got that error and why the #defines are different?

Many thanks,

C Solutions


Solution 1 - C

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

Solution 2 - C

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

Solution 3 - C

#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

Solution 4 - C

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

is correct

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionant2009View Question on Stackoverflow
Solution 1 - Cuser44556View Answer on Stackoverflow
Solution 2 - CnehaView Answer on Stackoverflow
Solution 3 - CjohannesView Answer on Stackoverflow
Solution 4 - CMariusz TerebeckiView Answer on Stackoverflow