开发者

How do macros work in Objective-C?

开发者 https://www.devze.com 2023-02-25 16:38 出处:网络
I would like to know how do macros work in Objective-C, how does the compiler inte开发者_运维问答rpret them ,what makes them different from a regular function. Also, how are they able to access __LINE

I would like to know how do macros work in Objective-C, how does the compiler inte开发者_运维问答rpret them ,what makes them different from a regular function. Also, how are they able to access __LINE__, __FILE__, _cmd and most curious self (without passing it to them) in the current context?


They work the same as they would in pure C.

Macros are processed by the compiler's pre-processor, as which time the compiler still has the full source code available (and by that the name of the enclosing __FUNCTION__ or the current __LINE__). You could think of Macros as some kind of advanced "text replacement" magic.

With macros you basically tell the compiler: "Please replace this macro of mine with the block of source code that I defined it with before doing any actual compilation."

For more information on Macros and the C preprocessor look here: http://en.wikipedia.org/wiki/C_preprocessor


Macros differ from a regular function because they are processed as text not as code.

Macro expansion is done before the compiler parses your code and is language agnostic - the macro is treated the same regardless of the target language. The process is usually referred to as macro expansion which happens during preprocessing.

__LINE__ and __FILE__ are macros defined by the compiler, so they are just replaced by text. A macro can "access" _cmd and self if, and only if, those variables exist in the context the macro is expanded - the macro is not really accessing these variables, the macro is being expanded and the resultant code accesses the variables.

You can see the effect of the macro processing by selecting Preprocess in XCode's Build menu.

Here is a (strange) example to demonstrate:

#define BEGIN {
#define END }

int main(int argv, char *argv[])
BEGIN
    ... // body of main
END

which expands to the more usual:

int main(int argv, char *argv[])
{
    ... // body of main
}


Those are specified in the C language standard and support for them is built into the compiler. See http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html for a longer list of available standard macros.


__LINE__ and __FUNCTION__ are provided by the compiler and expanded during preprocessing. self and _cmd are parameters implicitly passed to every ObjC method, and are part of the Objective-C language. They are not macros, just invisible parameters.

0

精彩评论

暂无评论...
验证码 换一张
取 消