1)外部函数:如果在当前文件中定义的函数允许在其它文件访问、调用,就称为“外部函数”。C语言规定,不允许有同名的外部函数。2)内部函数:如果在当前文件中定义的函数只能在内部使用,就称为“内部函数”。C语言对顶不同的源文件可以有同名的内部函数,并不互相干扰。
one.c
#include <stdio.h>
void one(){
printf("this is method one()\n");
}
void two(){
printf("this is method two()\n");
}
void three(){
printf("this is method three()\n");
}one.h
#ifndef __C__one_h #define __C_one_h void one(); void two(); void three(); #endiffirst.c
#include <stdio.h>
#include "one.h"
int main(){
one();
two();
three();
return 0;
}
从上面的例子看出,one.c中定义的函数时可以被其他源文件访问的。其实有时候,我们想定义一个“内部函数”,不能被其他源文件访问的函数。只需使用static关键字修饰函数即可。备注:1)将上面的one函数用static关键字修饰一下,发现在链接的时候报错。2)在编译阶段:编译器只检测单个源文件的语法是否不合理,并不测函数有没有定义;只有在链接的时候才会检测这个函数存不存在,也就是有没有被定义。3)所谓编译:就是单独检查每个源文件的语法是否合理,并不检查每个源文件之间的关联关系,一个源文件编译成功后就会生成一个目标文件。所谓链接:就是检查目标文件的关联关系,将相关联的目标文件组合在一起,生成可执行文件。
#include <stdio.h>
static void test();
int main(int argc, const char * argv[])
{
test();
return 0;
}
static void test() {
printf("调用了test函数");
}
#include <stdio.h>
int a=10;
int main(){
extern int a; //表示引用全局变量,其实是多次一举,这行是多余的
a=12; //为全部变量重新赋值
printf("%d\n",a);
return 0;
}
int a;
//执行成功#include <stdio.h>
int a=10; //全局变量
int main(){
int a =12;//局部变量,和全部变量a之间没有任何关系
printf("%d\n",a);
return 0;
}
int a;
#include <stdio.h>
int a;
void one(){
printf("%d\n",a);
}first.c
#include <stdio.h>
int a ;
void one();
int main(){
a =12;
one();
return 0;
}1)extern可以用来引入一个全局变量。2)默认情况下,一个变量是可以供多个源文件共享的,也就是说,多个源文件中同名的全局变量都代表着同一个变量。3)如果在定义全局变量的时候加上static关键字,那么该全局变量仅限于定义该变量的源文件。与其它源文件中的同名变量互不干扰。
原文:http://blog.csdn.net/z18789231876/article/details/43530719