我想知道以下场景中的行为:
//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.
}如果进程X调用库的函数func(),会发生什么?
发布于 2014-09-19 23:18:21
在file1.c中,您定义了
int a;它告诉编译器在编译单元中为a分配内存,对a的所有引用都将由编译器(而不是链接器)在那里解析。所以file1看到了自己的a,file1看到了自己的a。如果您使用了,请使用
extern int a;在file1中,编译器会将此符号的解析推迟到链接器,然后在file2.c外部解析a。
因为file2是一个共享对象,所以如果假设变量a被其他文件使用,那么file2.so可能会附带一个file2.h,它将包含下面的代码行
extern int a;这个file2.h就是file1.c中的#included。
发布于 2014-09-19 22:59:19
做个测试。这么简单。
file2中的a与func链接,因此file1中的a不会受到影响。它们是不同的两个变量。
https://stackoverflow.com/questions/25936790
复制相似问题