读书人

int a;是定义仍是声明

发布时间: 2013-01-21 10:15:38 作者: rapoo

int a;是定义还是声明?

#include <stdio.h>
int a;
int a = 1;

int main(void)
{
printf("a = %d\n",a);
}
在VC中不能成功,在CFree和linux下都能成功。

另外在linux下也做了另一个试验:

root@ubuntu:/home/hello# ls
hello.c hello-test.c hello-test.h
root@ubuntu:/home/hello# cat hello-test.c
#include <stdio.h>
volatile int a=1;

void puta(void)
{
printf("a = %d in hello-test\n",a);
}
root@ubuntu:/home/hello# cat hello-test.h
void puta(void);
root@ubuntu:/home/hello# cat hello.c
#include <stdio.h>
#include "hello-test.h"
int a;

int *p;

int *p2;


int *p3;
int main()
{
a = 2;
printf("a = %d\n*p = %p,*p2 = %p, *p3 = %p\n",a,p,p2,p3);
puta();
return 0;
}
root@ubuntu:/home/hello# gcc hello.c hello-test.c -o hello
root@ubuntu:/home/hello# ./hello
a = 2
*p = (nil),*p2 = (nil), *p3 = (nil)
a = 2 in hello-test
root@ubuntu:/home/hello#


从结果中可以看出,对hello.c中的a 进行修改实际就是对hello-test.c中的a进行修改。
那么请问int a;是声明吗????不分配内存吗????还是有其它原因???
求解ing!!!!!!!!!!!!!!!!!! C linux gcc
[解决办法]
在大括号之外的
int a;
是声明兼未初始化定义.
如果用gcc的话:

int x; /* C (Common) 声明(可能同时也定义)变量, 到了链接阶段, */
/* 1. 如果没在其他模块发现同名(D)符号,作为未初始化的全局变量, 放在BSS */
/* 2. 如果有在其他模块发现同名(D)符号,作为已初始化的全局变量, 放在数据段 */
int y = 1; /* D (Data) 定义变量,作为已初始化的全局变量, 放在数据段 */
extern int z;  /* U (Undefined), 声明变量, 到了链接阶段 */
/* 1. 如果在其他模块有且仅有一个类型(D)的同名符号,将此符号解析到此 */
/* —)符号,作为已初始化的全局变量, 放在数据段 */
/* 2. 如果在其他模块有两个或更多的类型(D)的同名符号,*/
/* 报告“重复定义”,链接失败 */
/* 3. 如果在其他模块未发现类型(D)的同名符号,但是至少有一个类型(C) */
/* 的同名符号, 将此符号解析到此(C)符号上,
/* 作为未初始化的全局变量, 放在BSS */

简单来说,
int x; 可以在多个模块,
int x = 1; 只能在一个模块
extern int x; 可以在多个模块, 且至少还需要在其他模块有一个 int x; 或 int x = 1;


读书人网 >C语言

热点推荐