0

There is something that I fundamentally don't understand because I cannot for the life of me get this to work. I want to create a macro that extends NSLog(NSString *format, ...). Here is what I came up with:

NSLogExtensions.h

#define DebugLog(debugMode, format, ...) MyDebugLog(debugMode, [[NSString stringWithFormat:@"<%@> (Line %d): ", NSStringFromClass([self class]), __LINE__] stringByAppendingString:format], ##__VA_ARGS__)

@interface NSLogExtensions : NSObject

@end

NSLogExtensions.m

#import "NSLogExtensions.h"

@implementation NSLogExtensions

void MyDebugLog(bool debugMode, NSString *format, ...) {
    va_list(argumentList);
    va_start(argumentList, format);
    if (debugMode) {
        NSLogv(format, argumentList);
    }
    va_end(argumentList);
}

@end

I expected to be able to include the NSLogExtensions header file and then be able to use the macro, but I receive the GCC implicit function declaration warning still.

Alec
  • 1,646
  • 3
  • 19
  • 35
  • what are you trying to achieve with this? Turn off logging based on teh macro? – Nitin Alabur Aug 01 '12 at 17:05
  • The main goal is to be able to turn on and off logging with a boolean that I can specify within each class. I also added line numbers and the class name to each log. – Alec Aug 01 '12 at 17:20

2 Answers2

2

Checkout this answer

Is it true that one should not use NSLog() on production code?

it has a lot more detail on how to go about using a macro for your extended NSLogs

Community
  • 1
  • 1
Nitin Alabur
  • 5,812
  • 1
  • 34
  • 52
  • My macro is almost exactly the same, but rather than using a single global macro to enable/disable logging, I want to pass it as a parameter. – Alec Aug 01 '12 at 17:25
1

The DebugLog macro uses the function MyDebugLog, therefore you must add the prototype

void MyDebugLog(bool debugMode, NSString *format, ...);

to NSLogExtensions.h. Then it compiles without warnings.

BUT your solution has one (in my opinion) great disadvantage compared to the solutions that @calvinBhai refers to: Even if you switch off logging by setting debugMode to false, the DebugLog macro will evaluate all arguments and call MyDebugLog. With the other solutions, the preprocessor will remove everything if logging is disabled.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • If I was worried about having logs in my production code, I would probably add a global flag as well. But for now I just want to be able to control what part of my project prints debug code when. Thank you for your help! – Alec Aug 01 '12 at 18:31