extern的一点知识

extern.c

#include <stdio.h>
int main()
{
    extern int i;//测试与全局变量同名的局部变量是否可以被extern声明
    //int i = 11;
    printf("%d",i);
    int i = 11;
    getchar();
}

另一C文件如下:

extern1.c

int i = 12;

VS2012编译,出错:

1>c:\users\longtuoei\documents\visual studio 2012\projects\。。。\。。。\extern.cpp(9): error C2086: “int i”: 重定义
1>c:\users\longtuoei\documents\visual studio 2012\projects\。。。\。。。\extern.cpp(5) : 参见“i”的声明

结论:

  不能用extern将与全局变量同名的局部变量扩大范围

 

 

#include <stdio.h>

int main()
{
    extern int i;
    printf("%d",i);
    int i = 11;
    printf("\n %d",i);
    getchar();
}
int i = 12;

 

1>c:\users\longtuoei\documents\visual studio 2012\projects\。。。\。。。\extern.cpp(7): error C2086: “int i”: 重定义
1>          c:\users\longtuoei\documents\visual studio 2012\projects\。。。\。。。\extern.cpp(5) : 参见“i”的声明

 

#include <stdio.h>

int main()
{
    extern int i;
    printf("%d",i);
    int i = 11;
    printf("\n %d",i);
    getchar();
}
//int i = 12;

1>c:\users\longtuoei\documents\visual studio 2012\projects\。。。\。。。\extern.cpp(7): error C2086: “int i”: 重定义
1>          c:\users\longtuoei\documents\visual studio 2012\projects\。。。\。。。\extern.cpp(5) : 参见“i”的声明

 

#include <stdio.h>

int main()
{
    extern int i;
    printf("%d",i);
    //int i = 11;
    getchar();
}
int i = 12;

正确

 

#include <stdio.h>

int main()
{
    extern int i = 1;
    printf("%d",i);
    //int i = 11;
    getchar();
}
int i = 12;

1>c:\users\longtuoei\documents\visual studio 2012\projects\。。。\。。。\extern.cpp(5): error C2205: “i”: 不能对带有块范围的外部变量进行初始化

posted @ 2014-03-24 23:09  longtuoei  阅读(217)  评论(0)    收藏  举报