本文介绍了全局变量实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我撰写以下程式时:
档案1:
#include <stdio.h>
int global;
void print_global1() {
printf("%p\n", &global);
}
文件2:
#include <stdio.h>
char global;
void print_global2() {
printf("%p\n", &global);
}
文件3:
void print_global1();
void print_global2();
int main()
{
print_global1();
print_global2();
return 0;
}
输出:
$ ./a.out
0x804a01c
0x804a01c
这是我的问题:
- 为什么链接器实现int global和char global变量:
- 编译器如何不抱怨(不是
-Wall -Wextra -ansi
...) / li>
- 全局变量的大小如何管理(int和char的大小不同)
- Why are the linker implementing "int global" and "char global" as the same global variable:
- How come the compiler does not complain (not the smallest warning with
-Wall -Wextra -ansi
...) - How are the size of the global variable managed (the size of int and char are different)
PS:第二个问题是架构/编译器相关,所以让我们把int大小为32位的gcc或Visual C ++(for C)。
PS: The second question is architecture/compiler related, so lets take the gcc or Visual C++ (for C) with the int size as 32 bits
编辑:THIS不是C ++的问题为C!
THIS IS NOT A QUESTION FOR C++ BUT for C!
我使用gcc版本4.4.1和Ubuntu 9.10,这里是编译控制台输出:
I use gcc version 4.4.1 and on Ubuntu 9.10, Here is the compilation console output:
$ ls
global_data1.c global_data2.c global_data.c
$ gcc -Wall -Wextra -ansi global_data*.c
$ ./a.out
0x804a01c
0x804a01c
or
$ gcc -Wall -Wextra -ansi -c global_data*.c
$ gcc -Wall -Wextra -ansi global_data*.o
$ ./a.out
0x804a01c
0x804a01c
推荐答案
gcc
不报告任何错误/警告。但 g ++
会。
gcc
does not report any error/warnings. But g++
does.
EDIT:
看起来C允许暂定定义
在您的情况下,全局定义都是暂定的,在这种情况下,选择链接器看到的第一个。
char global = 1; // no more tentative...but explicit.
Now if you compile like before, the tentative def in file1 will be ignored.
Make both the def explicit by:
int global = 1; // in file1
char global = 1; // in file2
now neither can be ignored and we get the multiple def error.
这篇关于全局变量实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!