Friday, April 23, 2010

Linker Puzzles

When static linker resolve the symbols at link time as follows rules applied:
Note: Linker always search for the symbol name from the symbol table.
Rule1: Multiple strong symbols are not allowed
Rule2: Given a strong symbol and multiple weak symbols, choose the strong symbol
Rule3: Given multiple weak symbols, choose any of the weak symbols

What is strong symbol and Weak symbol?
--- Strong symbols are those that have initialized.
exampls:
int x = 2;
float y = 3.2;
function()
{ }

---Weak symbols are those that are uninitialized.
examples:
int x;
float y;
char a;
static int a;

Now solve the as follows linker puzzles based on above information

1.
/*Module 1*/
int main()
{
return 0;
}

/*Module 2*/
static int main=1;
int f1()

2.
/*Module 1*/
int x;
int main()
{ return 0;
}


/*Module 2*/
float x;
int f1()
{
}

3.
/*Module 1*/
int x=1;
void main()
{
}

/*Module 2*/
int x;
4.
/*Module 1*/
int x=1;
void main()
{
}

/*Module 2*/
float x=1.0;


5.
/*Module 1*/
int x=1;
void main()
{
}

/*Module 2*/
int x =2;

Answers:
1. No error successfully build since main in module1 is strong but in module2 this is weak(as declared static)
2. No Error pic any one.
3. No error take strong symbol from module1.
4. Error like
ld: fatal: symbol `x' is multiply-defined:
(file /var/tmp//ccnY5GzB.o type=OBJT; file /var/tmp//ccfHCTBb.o type=OBJT);
ld: fatal: File processing errors. No output written to a.out
collect2: ld returned 1 exit status


5. Error like
ld: fatal: symbol `x' is multiply-defined:
(file /var/tmp//ccnY5GzB.o type=OBJT; file /var/tmp//ccfHCTBb.o type=OBJT);
ld: fatal: File processing errors. No output written to a.out
collect2: ld returned 1 exit status