1

I know that .m files are where the implementation is and .h files have the method signatures, etc. When one wants to use a certain class in his class, then he imports the .h file. Preprocessor replaces the import .h file with the content of the .h file. What I don't understand is how come access to implementation become available from just preprocessor bringing the .h content? What is the runtime mechanism that allows this?

neo
  • 1,952
  • 2
  • 19
  • 39
  • 1
    You should learn how compiling and linking works. – bneely Feb 23 '14 at 20:38
  • 2
    @bneely Instead of providing a snide comment like that, why not link (hah) him to an appropriate introduction on the topic? http://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work – Richard J. Ross III Feb 23 '14 at 20:44
  • That was not intended as a snide comment; I agree that an appropriate link is the right thing to contribute here. – bneely Feb 23 '14 at 21:43

1 Answers1

5

Importing the .h file isn't actually what does that, so you're correct to be confused!

When a program is compiled, each file is compiled to an "object file", and those are all linked together into an executable program. It's this linking step that provides access to the implementation.

Similarly, any libraries you use need to be linked against (Xcode's project templates do this for you for Foundation, UIKit/AppKit, and other common libraries). This type of linkage is done partially at compile time, then finished dynamically when your app launches, so that it gets the version of the libraries included with the OS instead of the version you compiled with.

Importing the header simply lets the compiler know what things are in the linked library so that it can compile code that references them. If you look up the functionality you use dynamically instead of letting the compiler do it (via dlopen, dlsym, NSClassFromString, NSSelectorFromString, etc...), then you can use linked code without importing its header.

Catfish_Man
  • 41,261
  • 11
  • 67
  • 84