外部变量能否跨文件引用(即多个文件操作同一变量)? 能,但必须声明
主文件定义一个外部变量
main.c MYSQL sqlstream; |
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 |