Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable defined with the same name in the so library

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?

like image 732
Neelansh Mittal Avatar asked Oct 31 '22 16:10

Neelansh Mittal


1 Answers

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 #included in file1.c.

like image 67
Jay Avatar answered Nov 15 '22 06:11

Jay