I wanted to know the behavior in the following scenario:-
//file1.c : Main file of a user-space process,say Process X.
int a; //GLobal variable in file1.c
func(); //Library function
//file2.c :Part of .so used by Process X.
int a;
void func()
{
a=0;//Access variable a.
}
If the Process X calls the function func()
of the library, what will happen?
In file1.c
you have defined
int a;
which tells the compiler to allocate memory for a
in that compilation unit, an all references to a
will be resolved there by the compiler (and not the linker). So file1
sees its own a
and file1
sees its own a
. If you had instead, used
extern int a;
in file1
then the compiler will defer resolution of this symbol to the linker, and then a
will be resolved outside of file2.c
.
Since file2
is a shared object, if variable a
is supposed to be used by other files, then file2.so
would likely come with a file2.h
, which would have the line
extern int a;
and this file2.h
would then be #include
d in file1.c
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With