【问题标题】:Defining const in precompiled header -- How to avoid duplication在预编译头文件中定义 const -- 如何避免重复
【发布时间】:2013-05-09 13:30:30
【问题描述】:

我想使用 CocoaLumberjack 并尝试在我的 .pch 文件中插入 ddLogLevel const

#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
static const int ddLogLevel = LOG_LEVEL_INFO;
#endif

但是,由于我使用的是 XMPP 框架,并且使用了 CocoaLumberjack,我收到了 Redefinition of 'ddLogLevel' 错误,因为这些类包含与上面完全相同的 const 定义。

我绝对不想在我的每一堂课中都定义ddLogLevel 以避免这种情况。我该如何解决这个问题?

【问题讨论】:

    标签: objective-c c-preprocessor constants


    【解决方案1】:

    我认为答案是不要将 ddLogLevel 声明为静态(如本指南中所指出的 https://github.com/CocoaLumberjack/CocoaLumberjack/wiki/XcodeTricks

    请关注Global log level for cocoalumberjack

    这类似于MagicalRecord遇到的Magical Record takes ownership of ddLogLevel

    常数.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
    

    另外,有些人似乎不明白 static 关键字在头文件中的含义,请阅读此Variable declarations in header files - static or not?

    【讨论】:

      【解决方案2】:

      将定义包装在预处理器指令中:

      #ifndef DEFINED_DD_LOG_LEVEL
      #define DEFINED_DD_LOG_LEVEL
      #  if DEBUG
      ...
      #  endif // DEBUG
      #endif // DEFINED_DD_LOG_LEVEL
      

      【讨论】:

        【解决方案3】:

        你可以在它周围加一个守卫。像这样的:

        #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 DDLOGLEVEL
        #if DEBUG
        #define DDLOGLEVEL
        static const int ddLogLevel = LOG_LEVEL_VERBOSE;
        #else
        static const int ddLogLevel = LOG_LEVEL_INFO;
        #endif //DEBUG
        #endif //DDLOGLEVEL
        

        我希望它有效。

        【讨论】:

        • 嗯,所以现在我学习了#ifndef 的语法,但是,同样的错误。我的假设是,如果我把它放在我的 .pch 中,那么 ddLogLevel 还没有在任何地方定义。 .pch 代码位于每个类的顶部,对吗?因此,当 XMPPFramework 文件定义 ddLogLevel 时,这就是我得到错误的地方。并且有很多 XMPPFramework 类。我不想改变它们。
        • @SmoothAlmonds:为什么它需要是 .pch?你不能只使用一个普通的 .h (然后它会通过 #include 插入到每个文件中)吗?
        • 因此,如果我使用普通的 .h,将其自动放入每个文件的唯一方法就是将该标头放入 .pch 中,对吗?问题是,我想在每个类中使用 DDLog,所以我希望它可以自动使用,而无需手动包含它。我理解错了吗?
        • 我认为您需要包含头文件才能使用它。如果变量或常量未在您要使用的范围内声明,则不能使用它。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-16
        • 2011-10-06
        • 2013-10-31
        相关资源
        最近更新 更多