Heads up: This is a strange question.
I have some really useful macros that I like to simplify some notes. For example, I can do Log(@"My message with arguments: %@, %@, %@", @"arg1", @"arg2", @"arg3") , and this will be expanded into a more complex method call, including things like self , _cmd , __FILE__ , __LINE__ , etc., so that I can easily track where things are being logged. This works great.
Now I would like to expand my macros to work not only with Objective-C methods, but also with common C functions. The problem is with the self and _cmd parts that are in the macro extension. These two parameters do not exist in C functions. Ideally, I would like to be able to use the same set of macros inside C functions, but I am having problems. When I use (for example) my Log() macro, I get compiler warnings about self and _cmd that are not declared (which makes full sense).
My first thought was to do something like the following (in my macro):
if (thisFunctionIsACFunction) { DoLogging(nil, nil, format, ##__VA_ARGS__); } else { DoLogging(self, _cmd, format, ##__VA_ARGS__); }
This still causes compiler warnings, since the entire if () statement is replaced instead of the macro, which leads to errors with the keywords self and _cmd (although they will never be executed during the execution of the function).
My next thought was to do something like this (in my macro):
if (thisFunctionIsACFunction) { #define SELF nil #define CMD nil } else { #define SELF self #define CMD _cmd } DoLogging(SELF, CMD, format, ##__VA_ARGS__);
This does not work, unfortunately. I get "error:" # "does not follow the macro parameter" on my first #define .
My other thought was to create a second set of macros, specifically for use in C functions. It smells like an unpleasant code smell, and I really don't want to do this.
Is it possible to use the same set of macros from both Objective-C methods and C functions, and only the self and _cmd link if the macro is in the Objective-C method?
change additional information:
thisFunctionIsACFunction defined in a rather primitive way (and I'm definitely open to improvements and suggestions). Mainly:
BOOL thisFunctionIsACFunction == (__PRETTY_FUNCTION__[0] != '-' && __PRETTY_FUNCTION__[0] != '+');
It relies on compiler behavior to add "-" or "+" methods for the instance and class on Objective-C objects. Everything else should be a C function (since C functions cannot have names beginning with "-" or "+").
I understand that this check is technically a runtime check, as __PRETTY_FUNCTION__ is replaced with char* , and this is probably the main road block for my request for help.