static和extern修饰连接属性

1. static修饰全局变量或函数,表示其只能在所在文件中使用

extern修饰变量,表示其来自于其他文件

---------------------------------------

[root@localhost cpp]# cat source.c

#include<stdio.h>

static int height = 8848; // can only be used in this file

double pi = 3.14; //can be accessed from other file under the same project

int getHeight(){ // can be accessed from other file under the same project

return height;

}

--------------------------------------------

[root@localhost cpp]# cat main.c

#include<stdio.h>

int getHeight(); //or: external int getheight;

//extern double pi;

double getArea(double diameter){

extern double pi; // putting it here is also ok

return pi * diameter * diameter / 4;

}

int main(){

int height = getHeight();

printf("Height = %d\n", height);

double diameter = 2;

double area = getArea(diameter);

printf("diameter = %f, area = %f\n", diameter, area);

return 0;

}

-------------------------------------------

编译执行:

[root@localhost cpp]# gcc source.c main.c -o main

[root@localhost cpp]# ./main

Height = 8848

diameter = 2.000000, area = 3.140000

==========================================

2. extern的另外用法是当C和C++混合编程时,如果c++调用的是c源文件定义的函数或者变量,那么要加extern来告诉编译器用c方式命名函数:

文件A.cpp调用source.c里面的变量i和函数callme()

extern "C" //在c++文件里调用c文件中的变量

{

int j;

void callme();

}

int main()

{

callme();

}

二,static法则:

A、若全局变量仅在单个C文件中访问,则可以将这个变量修改为静态全局变量,以降低模块间的耦合度;

B、若全局变量仅由单个函数访问,则可以将这个变量改为该函数的静态局部变量,以降低模块间的耦合度;

C、设计和使用访问动态全局变量、静态全局变量、静态局部变量的函数时,需要考虑重入问题;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值