第十四章-static和extern

static和extern 对函数的作用

extern与函数

static与函数

代码举例

在main.c中调用one.c中定义的test函数。

one.c文件

#include <stdio.h>

// 声明一个内部函数
static void test2();

// 完整地定义一个外部函数
/*
extern void test()
{
    printf("调用了test函数\n");
}*/
// 默认情况下,所有的函数都是外部函数,所以可以省略extern
void test()
{
    printf("调用了test函数\n");
    
    test2();
}

// 定义一个内部函数
static void test2()
{
    printf("调用了test2函数\n");
}

one.h文件

#ifndef _ONE_
#define _ONE_
//extern void one(); extern可以省略
//外部函数
void test();
//内部函数
static void test2();
#endif

main.c文件
/*
// 完整地声明一个外部函数
// extern可以省略
//extern void test();
void test();
void test2();
 */
//上面用导入头文件代替
#include "one.h"

int main()
{
    //调用成功
    test();
    //编译成功,连接会报错,因为one.c中test2为内部函数
    test2();   
    return 0;
}
//不能重复定义外部函数
//void test()
//{
//    
//}
//可以重复定义内部函数
//static void test2()
//{
//
//}

static和extern 对变量的作用

static和extern 对全局变量的作用

extern对全局变量的作用

static对全局变量的作用

main.c文件

#include <stdio.h>
void test();
// 定义一个外部变量
// 这么多个a都是代表同一个a : one.c中的a/当前文件所有的a;
//int a;
//int a;
//int a;

// 声明一个外部变量(只是声明,还没有定义,要想真正使用,还得定义)
//extern int a;

// 定义一个内部变量,跟one.c中的b无关
static int b;

int main()
{
    //并不会影响one.c中b的值
    b = 10;
    //声明一个外部变量a(也可以写在函数内部,但是此时的a可是外部变量属于全局变量)
    //这里可不是修饰局部变量哦!!!
    extern int a;
    //可以使用,因为已经声明,但是没有定义,编译不会报错,连接会报错,必须有定义,跟函数一样
    a = 10;
    //打印 a 为10,b为0
    test();
    //打印a为20;
    printf("a的值是%d\n", a);
    
    return 0;
}
//定义一个外部变量(没有这一句连接会报错!!!)
int a;

one.c文件
#include <stdio.h>
int a;
static int b;
void test()
{
    printf("b的值是%d\n", b);
    printf("a的值是%d\n", a);
    a = 20;
}

static和extern 对局部变量的作用

static修饰局部变量

void test(){
    
    int a = 0;
    a++;
    //每一次调用都是1
    printf("a的值是%d\n", a); 
    
    static int b = 0;
    b++;
    //每一次调用,都会在上次的基础上+1
    printf("b的值是%d\n", b); 
}

int main(){
    for (int i = 0; i<100; i++) {
        test();
    }  
    return 0;
}
Table of Contents