Open In App

Linking Files having same variables with different data types in C

Last Updated : 23 May, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Suppose there are two codes foo1.c and foo2.c as below and here the task is to link foo1.c and foo2.c which have same variable name x but different data type i.e int in foo1.c and double in foo2.c.
Note that none of the variables is declared as extern.

What do you expect to be the output of the following command with given two programs?

$ gcc -o myprog foo1.c foo2.c
$ ./myprog




// foo1.c
#include<stdio.h>
void f(void);
int x = 38;
int y = 39;
  
int main() 
{
    f();
    printf("x = % d\n", x);
    printf("y = % d\n", y);
    return 0;
}





// foo2.c
double x;
void f() 
{
    x = 42.0;
}


Output:

x = 0
y = 1078263808

output

Explanation of Output: Output of the program looks unpredictable but reason is: In foo1.c, there are two variables x and y each having 4 bytes(total 8 bytes). In foo2.c there is x variable as double.
While execution, x in foo1 (4 bytes) is replaced by x in foo2 (8 bytes). Ultimately memory of x and y (total 8 bytes) in foo1 is overwritten by x in foo2 (8 bytes).

1078263808 value is floating point representation of 42 in double.

NOTE : x and y addresses in foo1.c are successive.

Related Article : External and Internal Linkages in C


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads