ios - Linker error if .m is imported in header files -


why importing .m files lead linker errors?

ps: if find question small [or abstract] answered, please post in comments. i'll try post few scenarios. but, general behavior ios developers familiar with.

here simplified overview of build process. input of compiler called "translation unit". translation unit .m file, contents of included / imported header files pasted it. compiles each translation unit separately object file (.o). each object file has symbol table containing symbols defined in associated translation unit. @ stage symbol name can referenced generated code. linker's job associate address each symbol, , replace each reference symbol in generated code address, produce final executable. in object file's symbol table can have symbols either defined or undefined. undefined symbol symbol referenced in object file, not defined inside it. linker need find suitable definition in object file later in process. defined symbol means object file provides symbol's definition. when linker encounters such symbol in object file's symbol table, can assign address. if later on finds object file defined (global) symbol of same name, stops duplicate symbol error.

let's take example of following .m files:

a.m:

int my_global; 

b.m:

#include "a.m"  my_global = 3; 

the compiler sees 2 following translation units:

a:

int my_global; 

b:

int global; my_global = 3; 

it treats them separately, , emits a.o , b.o both have symbol my_global defined symbol in symbol table. when linker encounters second of two, complain duplicate symbol.

to solve issue can create header file called a.h containing external declaration of my_global, , include b.m:

a.h

extern int my_global; 

b.m

#include "a.h"  my_global = 3; 

the b translation unit this:

extern int my_global;  my_global = 3; 

now symbol undefined in b.o, , linker resolve symbol defined in a.o.

for more linkers do, can read this excellent article.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -