how a linker resolves linkage?

77 Views Asked by At

i have two translation units..

file1.c

#include<stdio.h>
#include<string.h>
extern char a[90];

int main(int argc,char ** argv){


//printf("%s ",a);

strcat(a,"y Code");
printf("%s",a);
return 0;
}

file2.c

char a[4]={'Q','u','i','r'};

by compilation and linking of project give no error but when i exceute the program it gives segmentation fault error(in Debug mode). i think that some how the linker resolves wrong link for identifier a in file1.c to definition a in file2.c, this happens when i also change the data type of a in file2.c(definition of a) how it is possible, what mechanism the linker uses to link identifiers in same or different translation units?

2

There are 2 best solutions below

0
On

You are getting a segmentation fault because you have defined char a[4] and you have extern char a[90]

You also need to enable warnings using -Wall, during linkage step compiler recognizes this variable, thus you get no error.

0
On

You may declare the object of incomplete type as in file1.c

extern char a[];

and then define it with complete type in file2.c

char a[4]={'Q','u','i','r'};

It means that the same array object can have incomplete type initially, but acquire a complete type later on. This doesn't, of course, mean that you can declare a as an int and then define it as a double. The only type-related freedom you have here is, again, to complete an incomplete type. No more.

Courtesy: Shouldn't declaration match its definition when array is involved?

However, you may want to refrain from concatenating to a char array of unknown length.