Objective c 在预编译头中定义常量--如何避免重复
我想使用CocoaLumberjack,正在尝试在.pch文件中插入Objective c 在预编译头中定义常量--如何避免重复,objective-c,c-preprocessor,constants,Objective C,C Preprocessor,Constants,我想使用CocoaLumberjack,正在尝试在.pch文件中插入ddLogLevelconst: #if DEBUG static const int ddLogLevel = LOG_LEVEL_VERBOSE; #else static const int ddLogLevel = LOG_LEVEL_INFO; #endif 然而,由于我使用的是XMPP框架,并且使用的是CocoaLumberjack,因此我得到了对“ddLogLevel”的重新定义错误,因为这些类包含与上面完全相同
ddLogLevel
const
:
#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_INFO;
#endif
然而,由于我使用的是XMPP框架,并且使用的是CocoaLumberjack,因此我得到了对“ddLogLevel”的重新定义错误,因为这些类包含与上面完全相同的const
定义
我绝对不想在我的每一个类中定义ddLogLevel
,以避免这种情况。我怎样才能避开它呢?你可以在它周围加一个防护装置。大概是这样的:
#ifndef ddLogLevel
#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_INFO;
#endif //DEBUG
#endif //ddLogLevel
如果无法将ddLogLevel用作防护:(现在无法测试)
我希望它能起作用。将定义包装在预处理器指令中:
#ifndef DEFINED_DD_LOG_LEVEL
#define DEFINED_DD_LOG_LEVEL
# if DEBUG
...
# endif // DEBUG
#endif // DEFINED_DD_LOG_LEVEL
我认为答案是不要将ddLogLevel声明为静态(正如本指南中指出的)
相反,请遵循以下步骤
这与MagicalRecord遇到的情况类似
常数h
extern int const ddLogLevel;
常数m
#import <CocoaLumberjack/DDLog.h>
#ifdef DEBUG
int const ddLogLevel = LOG_LEVEL_VERBOSE;
#else
int const ddLogLevel = LOG_LEVEL_WARN;
#endif
#导入
#ifdef调试
int const ddLogLevel=LOG_LEVEL_VERBOSE;
#否则
int const ddLogLevel=日志级别警告;
#恩迪夫
另外,有些人似乎不明白头文件中的static
关键字是什么意思,所以请阅读此Hmm,因此现在我学习了#ifndef的语法,但是,同样的错误。我的假设是,如果我把它放在.pch中,那么ddLogLevel在任何地方都还没有定义。.pch代码位于每个类的顶部,对吗?因此,当XMPPFramework文件定义ddLogLevel时,我得到了错误。还有很多XMPPFramework类。我不想改变它们。@SmoothAlmonds:为什么它必须是.pch?你不能只使用normal.h(然后它会通过#include in every file插入)吗?所以如果我使用normal.h,自动将其插入每个文件的唯一方法就是将该头放入.pch,对吗?问题是,我希望在每个类中都使用DDLog,所以我希望它能够自动可用,而不需要手动包含它。我理解错了吗?我想你需要包含头文件才能使用。如果变量或常量未在要使用它的范围内声明,则不能使用它。
#import <CocoaLumberjack/DDLog.h>
#ifdef DEBUG
int const ddLogLevel = LOG_LEVEL_VERBOSE;
#else
int const ddLogLevel = LOG_LEVEL_WARN;
#endif