Precompiled directives in iOS

Source: Internet
Author: User

A preliminary study of pre-compiled instructions in iOS

Catalog [+]

Opening

We humans create things when there is a word called "bionics"! Human creation of anything will imitate their own to create, so God did not grow into a tree like the same as people, sci-fi film inside the aliens also like people have eyes have nose ... But human creation of things if too like themselves, they will also scare urine (fear Valley effect), human is really wonderful; we created in 20th century to change the world of Things-computer (computer), no doubt, this goods is also bionics! Where does the shipment look like a human being?? Don't disobey, listen to me first, put your bricks down first. In the narrow sense, bionics is a bionic form. In fact, the generalized bionics can also be the principle of bionics, the bionic structure, the performance of Bionic Alabara ..., computer (here I use personal pc in the narrow sense for example) we often say that there is an input device (keyboard Ah mouse ah camera ah ...), processing equipment (CPU, GPU ...) and output devices (monitors, stereos ...); And then you look at your own eyes. Ear (input), brain (processing), limbs (output) the person who designed the computer must have this kind of construction, didn't you look at yourself to design the computer? ^_^

So on the computer composition principle when there is obscure difficult to understand when, I immediately lifted my high school biology knowledge, and then solved the ~ but today I this blog is to talk about the program Ah, this duzi pull so far onlookers also unavoidably heart has resentment, you do not impatience, I immediately take you to fly! Then I use the bionic angle to understand the computer, then the computer program is God Horse? What does the textbook say? Can be executed by the computer, that God horse things will be executed? The wife's orders, Dad's reprimand, the project manager's needs change ... We will execute, it seems that this is the human program, this is really a human program! Below I specifically take the wife's order to explain the process of the implementation of human procedures; For example, the wife said, "You get out of the couch!" "First of all, the process of this sentence is this:

Figure 1

I'll show you. Before the process of computer program execution, we need to get a serious understanding of the process of compiling a program, that is, in which we convert our wives ' commands into electrical signals. In the computer world, some good people call this thing compiler (compiler), what GCC ah clang ah Alabara, said the name of the compiler is very high ~ actually plainly is a translation of things, such as our people execute the procedure, the wife's words (also human words) Translated into the brain to understand the words (radio waves), in the computer is the various programming languages (C, C + +, OC ...) Translated into 0101011 ... Let the computer know. The compiler works basically three-segment, which can be divided into front-end (Frontend), Optimizer (Optimizer), back-end (backend). The frontend is responsible for parsing the source code, checking for grammatical errors, and translating it into an abstract syntax tree (abstract Syntax trees). The optimizer optimizes this intermediate code to try to make the code more efficient. The backend is responsible for converting the optimizer's optimized intermediate code into the code of the target machine, which maximizes the use of special instructions from the target machine to improve the performance of the code.

Figure 2

Why do we have to do this three-stage? I certainly will not from what frame, structure AH optimization ... Angle, because I do not understand ah, haha, but I can tell a story of the past to everyone, we imagine how the compiler is developed, ah, good guy, internet a search LLVM compiler is C + + write, that C + + compiler? In fact, don't be so troublesome, now lend your hand to me, let me lead you back to the 70 's, Ricky is for his newly invented C language in writing compiler, he is in assembly language! How does assembly language compile into binary stream? The answer is a compiler written with 01011 machine code, so the compiler and the computer language progress is like this iterative development, then is in high-level language to write more advanced compiler, advanced compiler can compile more advanced computer language ..., although Lanxiang's excavator technology is strong, but the problem still comes, There are so many computers in the world, different architectures, people are fine. Basic architecture is the same, but the computer has an Intel architecture and ARM architecture, how can the programming language by compiling a separate code to produce different schemas? So this is the benefit of the compiler three-segment model, and when we want to support multiple languages, we just need to add multiple front ends. When you need to support multiple target machines, you just need to add multiple backend. For the intermediate optimizer, we can use the generic intermediate code. GCC can support C, C + +, Java ... and other language compilations.

Figure 3

Then a Helloword program of the compilation and implementation of the process we will follow figure 1 self-brain repair it

Said so much finally positive start ~ Originally my long-winded, because I was called the words tuberculosis wears ^_^, I have not developed the Mac OS application so this article main sample code and framework are under iOS, but because of the C-language pre-compilation instructions, so basic can be universal. Although this article has a grand beginning, but this article is mainly to explore the process of the pre-processing part of the pre-processing instructions, I hope this article can do is to give a little more than my food of the vast ape Friends guide a direction of learning.

In a long, long time ago Xcode did not know what version, build settings inside can also choose a different compiler.

Figure 4

Different compilers, whether there is a difference between the pre-processing instructions, I have no way to be elegant. There are actually, actually people contact iOS also only 3 months, I develop iOS use of the first IDE is XCODE6, if pits everyone, then Soray ~ ~

Now the compiler for Apple LLVM 6.0 is used by default in Xcode6

Figure 5

The differences between the various compilers also have several comparative knowledge to see the difference between LLVM and GCC

A story of the passion behind Apple and GCC and LLVM to see this Miyoshi students Chris Lattner's LLVM compilation toolchain

So the next step is the climax of the positive--preprocessing instructions.

Before the climax to add a pre-climax ^_^, why do you have to preprocess it? Go back to figure one, the wife said, "You get out of the couch!" "If you don't have pre-treatment, you run in order, you may not want to sleep, you watch TV on the couch for a few hours before you plan to go to bed, when you find that you unexpectedly forget to take the pillow and quilt out of the room, you then go knocking on the door of the wife, is a scolding, then you can sleep ... Toss it out? If you have a pre-treatment, when the wife finished the instructions, where you get to the keyword "couch", whether I go out and sleep, I first from the room quilt pillow to the sofa, this is not a lot of high efficiency? Also for the C-series language development, preprocessing is very important, if you read the excellent C source code, you must see a lot of #define #if #error ... Precompilation provides a lot of convenience and optimization for post-program compilation, for error handling, package referencing, cross-platform ... Have a great help. and the development of using precompiled instructions to accomplish something is also a very good thing, and since you have embarked on a path to change the world, then when a force of the program ape Consciousness also need to awaken

file contains # include

This I really do not want to say, as long as your college C language courses are not taught by the PE teacher, they must have told you the difference of "" ", #include <>, they must have said # include" XXX "contains and uses include The difference is that when you use <> include, the preprocessor searches for files under the C function library header file path, and uses "" to search for the directory where the program is located, followed by the system path definition directory, and if not found, search the directory where the C function library header file is located.

So I do not want to make up for your teacher's mistakes, I do not want to repeat, there is a need to note that when using # include files can not be recursively included, for example, the A.h file contains B.h, and b.h can no longer contain a.h, and there is a repetition of the inclusion (for example, A.H contains B.h, A.h and B.h are then included in the MAIN.C, although they are allowed, but this can degrade compilation performance. What should we do then? 1, use #import to replace include 2, use macro judgment (macro judgment below will explain), Xcode is very clever, as long as a new header file A.h inside automatically generated

Figure 6

Can't you read this? You can see after reading #ifndef and # define, the approximate principle is to use the macro definition to determine whether a macro is defined, if not defined, it will define the macro, so that if it has been included in the macro definition has been defined, even if it is not redefined, The following code will not be included.

This is a non-C standard library inside the preprocessing instructions, but the use of Xcode allowed, so also introduce it. #include_next是GNU (a bunch of people crazy open source organization, can be said to be the soul of Linux) an extension, not standard C directives such as a search path chain, in # include, their search order is a,b,c,d and E. In the B directory has a header file is called A.h, in the D directory also has a head file called A.h, if in our source code that this write # include, then we will contain the B directory in the A.H headers, if we write #include_next Then we will include the A.H header file in the D directory. The meaning of #include_next is "search for the A.H header file and include it in the directory path (i.e. C,d and E) after the A.H header file in the B directory, as explained in the quotation marks above." #include_next operation will be like this, it will be in A,b,c, D and E directory search a.h header file, then first it will be in the B directory to search for the A.H header file, then it will be the B directory as a split point, search directories after the B directory (C,d and E), and then search the directory behind the A.H header file, and the search after the A.H header file included. You should be clear about that.

#import

OC-specific is a smart # include, which solves the problem of the repeated inclusion of # include.

Macro Definition # define

This is too much to use, and I think it's the coolest of all pre-processing instructions! Have to learn! Here I have the audacity to reprint Onev's Den (meow) Articles that he wrote very well! Macro definition of Black magic-Macro rookie takeoff manual, please call me happy Porter!

Attach the calf.

#define NSLog(format, ...)   fprintf(stderr, "<%s : %d> %s\n",                                           [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String],  __LINE__, __func__);                                                        (NSLog)((format), ##__VA_ARGS__);                                           fprintf(stderr, "\n ------------------\n/ Hello David Day! \\\n\\ my Macro Log ~   /\n ------------------\n            \\\n             \\   ^__^\n                 (OO)\__________\n                 (__)\\          )\\/\\\n                     ||_______ _)\n                     ||       W |\n       YYy           ww        ww\n");

Figure 9

#undef

When you use the # define macro definition, the macro is valid throughout the program's run cycle, but sometimes we want the macro to fail in some logic and don't want to use it.

#define NetworkOn -(void)closeNetwork{#undef NetworkOn}
Conditional Compilation # if #else #endif

If it is the same as the if use of our usual conditional statement, #if的后面跟上条件表达式, followed by a #endif to end # If, although this thing is simple, but good, for some trickery work is particularly easy to achieve. For example, you now have such a demand, my program normally debug mode when you need to print some log, but the release mode of the application will not have to print log, how to do? A lot of people say when the release of the log statement a sentence of the deletion Bai ~ that customer hair Rotten I say you write something is dog excrement let you change, so you have to come back to debug, when you are debugging the chrysanthemum must be a tight, the previous debug statement because too confident in the release of all deleted, and do not want to post and be asked to modify ~, Have a friend to say, then do not delete the log statement, anyway, is the information printed to the console, the user can not see ~, there is no security awareness, enterprise development is not learn Lei Feng, do not have all your log is written in the diary, sometimes your software is cracked because of your debugging information betrayed you. Safety consciousness must not be no, otherwise Lao Wang for you to give birth to children ~~~~~.

How do you do it?

#if DEBUG func dlog<T>(object: T) {     println(object)}#elsefunc dlog<T>(object: T) {}#endif

Debug is Xcode's pre-defined macro, this thing is much more, to slowly dig it. After you print the log you will only use Dlog () This function, if you are in the debug mode when you print, otherwise it will not print.

Other examples:

To determine if arc is turned on, and some libraries require arc support, you can tell before compiling that the user has opened the arc

#if !__has_feature(objc_arc)#error "啊 啊 啊~ 伦家需要ARC"#endif

Similarly __has_feature (OBJC_ARC) This thing is also Xcode preset, the prefix is this "__" is a predetermined macro;

Another example is the strategy for different versions of OS systems

#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0#endif

Or judging the device type.

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)#if IS_IPAD#else#endif

This thing is simple but very often used, is the so-called if in hand, the world I have hahaha

 #if define  #ifdef  #ifndef  #elif  #if define = #ifdef  #if !define = #ifndef  #elif = "else if"
Error, warning handling #error

If the compiler encounters this shipment, it will strike immediately. Again Xcode error correction function so powerful, so almost impossible in the compilation process encountered #error, so said this goods useless? Not also ~, we are highly educated high-flyers, we must understand the dialectical point of view and the value theorem! Everything has the value of being there. Although today's IDE is very good and powerful, #error似乎没什么用了 ~ But there are a group of apes Pride Mellow Fellow, seclusion forest, they despise all the IDE, they believe Notepad is their dragon slayer Blades ...

For these unreal program apes, they still need #error to predict the errors before they compile. We say something valuable, and if we have to use #error, how do we use it in our current development?

Now #error still useful, especially when you are developing a library, the use of this library requires a certain condition, if you do not meet this condition, you will not let users compile. That's why you can use #error.

#if !__has_feature(objc_arc)#error "我的低调不是你装逼的资本!这个库需要开启ARC,不然你别用!"#endif

Then if the user does not open arc will not be able to compile, because Xcode see #error will not compile, here only open arc, #error才会不见.

#warning

This is easy to use, so just follow up with the warning you want, so you can let the compiler warn you.

Figure 10

If you set up in Xcode

Figure 11

If you set to Yes, then your waring is equal to the error, not compile the OH.

Please call me again happy small Porter ~ again he-->onev ' Den wrote things, I just like him, how about?

Talk about Objective-c's warning.

Compiler control #pragma

Everyone says that in all pre-processing instructions, the #Pragma directive is probably the most complex, and it's about setting the state of the compiler or instructing the compiler to do some specific actions. #pragma指令对每个编译器给出了一个方法, given the unique characteristics of the host or operating system, while maintaining full compatibility with the C and C + + languages. By definition, the compilation instructions are proprietary to the machine or operating system and are different for each compiler.

The format is generally: #pragma Para. Where para is the parameter

Let's talk about iOS, the usual

#pragma mark

If a file code is very large, sometimes it is not easy to find a piece of logic, you can use #pragma mark!

such as this:

Figure 12

Figure 13

It's convenient to have your mark in the method navigator.

If you use "#pragma mark-" like this:

#pragma mark-
#pragma mark -#pragma mark 这里是applicationWillTerminate方法呀~- (void)applicationWillTerminate:(UIApplication *)application {    }

That's what happens.

Figure 14

Automatic separation of the open!!!

#pragma message ("")

Can output debug information

Control compiler behavior not too much explained

#pragma clang diagnostic push#pragma clang diagnostic ignored "clang parameters" #pragma clang diagnostic pop

Self-clang User manual

pragma very complex need you to the compiler bottom of very understanding, only when you develop some of the lower framework of the time can be more useful, I am a beginner, I do not fear who?

Other #line

When we say this, we'll start by looking at a predefined macro,line, and we've seen it in the custom nslog of the black Magic-Macro rookie takeoff manual.

The __line__ in the C language is used to indicate the position of the bank statement in the source file. The #line is a representation of the line number in the compiler that can change the current line, and the subsequent line number will change accordingly, such as

1 #include <stdio.h>2 main(){3     printf("%d\n",LINE);4 #line 100  5     printf("%d\n",LINE);6     printf("%d\n",LINE);7     };

The output is:

3100101
Finish

Precompiled directives in iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.