简体   繁体   English

#ifdef不起作用。 但为什么?

[英]#ifdef doesn't work. But why?

#ifdef doesn't work. But why? 

CGFloat maxScale;

if ( [[UIScreen mainScreen] respondsToSelector: @selector (scale)] == YES )
{
    NSLog (@"case1");
#define GLOBAL1
}
else 
{
    NSLog (@"case2");
#undef GLOBAL1
}

#ifdef GLOBAL1
NSLog (@"first");
maxScale = 1.0 / [[UIScreen mainScreen] scale];
#else
NSLog (@"second");
maxScale = 1.0;
#endif

#undef GLOBAL1

my log:case1, second. 我的日志:case1,第二。 But it must be case1, first. 但首先必须是case1。

#define , #ifdef are pre-processor macros/conditionals. #define#ifdef是预处理器宏/条件。 That means that the logic contained in them is compiled before your code is compiled. 这意味着其中包含的逻辑要在编译代码之前先进行编译。 It is not actually part of your code. 它实际上不是代码的一部分。

See this guide for learning what pre-processor macros/conditionals are and do. 请参阅本指南以了解什么是预处理器宏/条件。


[EDIT] [编辑]

This is what your pre-processor sees when it reads your code. 这就是预处理器在读取代码时所看到的。

#define GLOBAL1
#undef GLOBAL1

#ifdef GLOBAL1
   //...
#else
   //...
#endif

#undef GLOBAL1

it IGNORES all other code and logic. 忽略所有其他代码和逻辑。

This is the actual code output the compiler makes: 这是编译器生成的实际代码输出:

if ( [[UIScreen mainScreen] respondsToSelector: @selector (scale)] == YES )
{
    NSLog (@"case1");
}
else 
{
    NSLog (@"case2");
}

// because the pre-processor #undef GLOBAL1
NSLog (@"second");
maxScale = 1.0;

The pre-processor code is "executed" telling the compiler how to compile, and will not be used or run during run-time. 预处理器代码是“执行的”,告诉编译器如何编译,并且在运行时不会被使用或运行。

Hope that helps! 希望有帮助!

The preprocessor does not care that the #define is inside a coded if statement - it is processed before the code and only cares about other preprocessor definitions. 预处理程序并不关心#define是否位于已编码的if语句中-它在代码之前被处理,仅关心其他预处理程序定义。 You can't use #defines and other preprocessor commands (such as #undef ) as code- they will not be hit each time the code enters the conditional branches. 您不能将#defines和其他预处理程序命令(例如#undef )用作代码-每次代码进入条件分支时都不会命中它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM