在so库中定义具有相同名称的全局变量

时间:2022-05-14 09:07:12

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?

如果进程X调用库的函数func(),会发生什么?

2 个解决方案

#1


2  

In file1.c you have defined

在file1。c你定义

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

它告诉编译器在编译单元中为a分配内存,对a的所有引用将由编译器(而不是链接器)解析。因此file1看到了它自己的a, file1看到了它自己的a。

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.

在file1中,编译器将把这个符号的解析延迟给链接器,然后在file2.c之外解析a。

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

由于file2是一个共享对象,如果其他文件应该使用变量a,那么file2。所以很可能会有文件2。h,这是直线。

extern int a;

and this file2.h would then be #included in file1.c.

这file2。h将被#包含在file1.c中。

#2


0  

have a test. so easy.

有一个测试。如此简单。

a in file2 is linked with func, so a in file1 won't be affected. they are different two variables.

在file2中的a与func链接,因此在file1中不会受到影响。它们是两个不同的变量。

#1


2  

In file1.c you have defined

在file1。c你定义

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

它告诉编译器在编译单元中为a分配内存,对a的所有引用将由编译器(而不是链接器)解析。因此file1看到了它自己的a, file1看到了它自己的a。

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.

在file1中,编译器将把这个符号的解析延迟给链接器,然后在file2.c之外解析a。

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

由于file2是一个共享对象,如果其他文件应该使用变量a,那么file2。所以很可能会有文件2。h,这是直线。

extern int a;

and this file2.h would then be #included in file1.c.

这file2。h将被#包含在file1.c中。

#2


0  

have a test. so easy.

有一个测试。如此简单。

a in file2 is linked with func, so a in file1 won't be affected. they are different two variables.

在file2中的a与func链接,因此在file1中不会受到影响。它们是两个不同的变量。