外部变量和声明

 

   外部变量的生命周期:由程序执行(不是函数)开始,至程序结束

    外部变量能否跨文件引用(即多个文件操作同一变量)? 能,但必须声明
主文件定义一个外部变量
main.c

MYSQL sqlstream; 
又添加了一个.c文件, 引用在主文件定义的外部变量
generatedatafile.c
 报错 
[macg@localhost mysqltmp]$ make
gcc -c generatedatafile.c
generatedatafile.c: In function datafile
generatedatafile.c:16: error: mqlstream undeclared (first use in this function) 
解决: 跨文件外部变量必须声明
vi generatedatafile.c
extern MYSQL sqlstream;  
[macg@localhost mysqltmp]$ make
gcc -c liu.c
gcc -c generatedatafile.c
gcc -g main.o liu.o generatedatafile.o -o liu -L /usr/lib/mysql -lmysqlclient -lz   



   两种外部变量声明
  • 函数内声明
用于函数内引用"定义在函数下面的外部变量"
main()
{
extern int a;        
}
  • 函数外声明
用于跨文件引用 别的文件定义的外部变量
extern MYSQL sqlstream 

  
   同一文件中,外部变量引用和定义确实有作用域问题,必须定义在前面,应用在后面, 因为程序上从上到下顺序执行的
下面就是一段出错的外部变量定义:
$ vi test.c
#include <stdio.h>
main()
{
ttt=7;
menu();

printf("from main ttt is %d",ttt);
}
menu()
{
printf("ttt is %d/n",ttt);

}

int ttt;    
$gcc -o test test.c -lcomm
test.c: In function main()
test.c:6: error: ttt undeclared (first use in this function)
test.c:6: error: (Each undeclared identifier is reported only once
test.c:6: error: for each function it appears in.)
test.c: In function menu()
test.c:16: error: ttt undeclared (first use in this function)   
但能否变量定义在后面呢? 也可以,但前面的变量引用必须增加变量声明(实际更烦琐,不如把函数定义在前面)
$ vi test.c
#include <stdio.h>
main()
{
extern int ttt;
ttt=7;

menu();

printf("from main ttt is %d",ttt);
}

menu()
{
extern int ttt;
printf("ttt is %d/n",ttt);

}

int ttt;
$ gcc -o test test.c -lcomm
$ ./test
ttt is 7
--------1
--------2
--------3
--------4
input slot: ------->3
from main ttt is 7   

  

    与外部变量不同,函数的引用和定义,在同一文件中没有前后问题,函数作用域是整个文件
#include <stdio.h>
main()
{
int rowCount,colCount,i,j,ret,test;
char a[5],b[5],s[80];

menu();
printf("input slot: ------->");
scanf("%s",a);
while (!checknumber(a)) scanf("%s",a);
}

menu()
{
printf("--------1/n");
printf("--------2/n");
printf("--------3/n");
printf("--------4/n");
}
$ gcc -o test test.c –lcomm    
$ ./test
--------1
--------2
--------3
--------4
input slot: ------->3    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值