Search code examples
objective-cextern

OBJC_EXTERN: what's the purpose?


Hi was reviewing some Objective-C code and found out the following statement:

OBJC_EXTERN void CLSLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2);

What does this mean? Also, what is supposed to be the syntax of this statement?

Thanks in advance.


Solution

  • OBJC_EXTERN is defined in <objc/objc-api.h> as

    #if !defined(OBJC_EXTERN)
    #   if defined(__cplusplus)
    #       define OBJC_EXTERN extern "C" 
    #   else
    #       define OBJC_EXTERN extern
    #   endif
    #endif
    

    and therefore prevents "C++ name mangling" even if the above declaration is included from a C++ source file, as for example explained here:

    For pure C code, you can just remove the OBJC_EXTERN, because the extern keyword is not needed in a function declaration.


    NS_FORMAT_FUNCTION is defined as

    #define NS_FORMAT_FUNCTION(F,A) __attribute__((format(__NSString__, F, A)))
    

    and __attribute__((format(...))) is a GCC specific extension, also understood by Clang:

    It allows the compiler to check the number and types of the variable argument list against the format string. For example

    CLSLog(@"%s", 123);
    

    would cause a compiler warning, because %s is the placeholder for a string, but 123 is an integer.