Sam
Sam

Reputation: 149

How Object files get linked in C? Explain this particular situation

Why do they print different values. Please explain in details. One file is:

    /* boo.c */
#include <stdio.h>
char main;
void p2()
{
printf("0x%X\n", main);
}

Another file is:

/* foo6.c */ 
void p2(void);

int main()
{
    char ch = main;
    p2();
    printf("Main address is 0x%x\n",main);
    printf("Char value is 0x%x\n",ch);
    return 0;
}

I expected p2 and char ch to print same values, but they are printing very different values. Output is:

0x55
Main address is 0x401110
Char value is 0x10

I cannot conclude the reasons behind such values (Main and char values worked as expected, but not p2 output as I mentioned earlier)

Upvotes: 0

Views: 64

Answers (2)

Iłya Bursov
Iłya Bursov

Reputation: 24145

Its indeed undefined behavior, just to add - why do you see 0x55 from p2, look at dis-assembly:

p2:
...
0x40052a: movzx   eax,BYTE PTR [rip+0x17]        # 0x400548 <main>
...
main:
0x400548: push    rbp

gcc generates code which takes first byte at function main address, effectively it is opcode for push rbp, which is 0x55

you can rewrite p2 code like this to understand it better:

int main();
void p2() {
    char t = ((char*)&main)[0];
    printf("%x\n", t);
}

Upvotes: 0

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140196

char ch = main; just truncates the pointer to a char. Implementation defined, but you getting the lower 8-bits makes sense.

Now char main (uninitialized) in another compilation unit fools the compiler by memory-mapping a function pointer on a char directly, without any conversion: that's undefined behaviour.

(and the formats used by printf don't match the data types...)

try that: char main=12; you'll get a multiply defined symbol main...

Upvotes: 2

Related Questions