Reputation: 1643
I expected the code to output suse.sys but it actually prints win.sys. Why is this the case?
#define SYS SUSE
#if SYS == WIN
#define HDR "win.sys"
#elif SYS == SUSE
#define HDR "suse.sys"
#else
#define HDR "default.sys"
#endif
#include HDR
#include <stdio.h>
int main()
{
char *name = HDR;
printf("%s\n", name);
return 0;
}
This is similar to the example in the C Programming language second edition. The .sys files don't contain anything, they have no real use.
Upvotes: 0
Views: 68
Reputation: 42159
The preprocessor comparison with ==
works on integer values, not strings or names of macros. You should be able to fix this by first defining the macros SUSE
and WIN
with integer values, e.g.,
#define SUSE 1
#define WIN 2
#define SYS SUSE
After this both SYS
and SUSE
resolve to the integer 1, and the comparison should work.
However, I would suggest a more conventional approach of defining different macros altogether for the systems, e.g.:
#define SYS_SUSE
//#define SYS_WIN
#if defined(SYS_SUSE)
#define HDR "suse.sys"
#elif defined(SYS_WIN)
#define HDR "win.sys"
#else
#define HDR "default.sys"
#endif
This approach has the advantage of being able to more conveniently specify the system on command-line, makefiles, etc. without depending on the numeric constants being defined in every context:
cc -DSYS_WIN -c foo.c
Upvotes: 3