您的位置:首页 > 其它

auto register static extern 变量

2012-09-16 21:31 295 查看
mylib.h

#ifndef MYLIB_H_
#define MYLIB_H_

extern double  PI;

extern int acc_add(int n);

extern void print_city();

#endif /* MYLIB_H_ */


mylib.c

#include<stdio.h>
#include<stdlib.h>

//all external/global variables locate in data segment

double PI = 3.1415;  //external variable can be accessed form other file with "extern double PI;"

//not allow other file to access the static external variable
static char *city = "shanghai_beijing"; //static external variable can only be accessed in this file

int acc_add(int n){ //n is a local variable which locates in stack, after exe, it disappears
//local variable, located in stack, after function, it disappears, "auto" is usually omitted

//static local variable, which is initialized in compiling phase
//it locates in "data segment", after function, it is still there
//if not initialized apparently, compiler initiate it with 0 by default
static int total = 0;
printf("before exec, total = %d, n = %d\n", total, n);
total += n;
return total;
}

void print_city(){
puts(city);
}
// static variable
//1. static + local variable, its space exists all the execution time
//2. static + external/global variable, only can be accessed in this file


3. main.c

#include <stdio.h>
#include <stdlib.h>
#include "mylib.h"

int main(void) {
printf("acc_add(1) = %d\n", acc_add(1));
printf("acc_add(1) = %d\n", acc_add(1));

printf("PI = %f\n", PI);

print_city();
return EXIT_SUCCESS;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: