关于头文件中为何要用static
2010-01-28 16:56
155 查看
static在头文件中使用的意义:
举个例子:
#ifndef __debug_h
#define __debug_h
#include <sys/types.h>
#include <syslog.h>
#include <stdarg.h>
#include <stdio.h>
static int __verbose = 0;
#define __have___verbose 1
static int __daemon = 0; /* is program daemon? */
#define __have___daemon 1
static int __debug = 0;
#define __have___debug 1
#ifdef __cplusplus
extern "C"{
#endif
static void _debug(const char* fmt, ...)
{
va_list arg;
char buf[8192];
va_start(arg,fmt);
vsnprintf(buf,8192,fmt,arg);
#ifdef DEBUG
if(__daemon){
syslog(LOG_DEBUG|LOG_USER,buf);
}else{
fputs(buf,stdout);
}
#endif
}
static void _verbose(const char* fmt,...)
{
va_list arg;
char buf[8192];
if(!__verbose)
return;
va_start(arg,fmt);
vsnprintf(buf,8192,fmt,arg);
if(__daemon){
syslog(LOG_DEBUG|LOG_USER,buf);
}else{
fputs(buf,stdout);
}
}
#ifdef __cplusplus
}
#endif
#endif
为何上面的都用static 来修饰呢?
如果没有static
当有两个文件a.c 和 b.c
如果a.c b.c都用到了debug.h
那么
debug.h + a.c ===> a.o
debug.h + b.c ===> b.o
gcc a.o b.o -o target
时,a.o和b.o中都同时有__debug,__daemon,__verbose,和_debug,_verbose
的定义,所以链接的时候就回出现multi-definition,为了避免这个
用static声明后,即使有同名的函数或变量出现,但由于static的局部性
不会影响到其他到模块,所以这就很好的避免了上面的multi definition的问题
举个例子:
#ifndef __debug_h
#define __debug_h
#include <sys/types.h>
#include <syslog.h>
#include <stdarg.h>
#include <stdio.h>
static int __verbose = 0;
#define __have___verbose 1
static int __daemon = 0; /* is program daemon? */
#define __have___daemon 1
static int __debug = 0;
#define __have___debug 1
#ifdef __cplusplus
extern "C"{
#endif
static void _debug(const char* fmt, ...)
{
va_list arg;
char buf[8192];
va_start(arg,fmt);
vsnprintf(buf,8192,fmt,arg);
#ifdef DEBUG
if(__daemon){
syslog(LOG_DEBUG|LOG_USER,buf);
}else{
fputs(buf,stdout);
}
#endif
}
static void _verbose(const char* fmt,...)
{
va_list arg;
char buf[8192];
if(!__verbose)
return;
va_start(arg,fmt);
vsnprintf(buf,8192,fmt,arg);
if(__daemon){
syslog(LOG_DEBUG|LOG_USER,buf);
}else{
fputs(buf,stdout);
}
}
#ifdef __cplusplus
}
#endif
#endif
为何上面的都用static 来修饰呢?
如果没有static
当有两个文件a.c 和 b.c
如果a.c b.c都用到了debug.h
那么
debug.h + a.c ===> a.o
debug.h + b.c ===> b.o
gcc a.o b.o -o target
时,a.o和b.o中都同时有__debug,__daemon,__verbose,和_debug,_verbose
的定义,所以链接的时候就回出现multi-definition,为了避免这个
用static声明后,即使有同名的函数或变量出现,但由于static的局部性
不会影响到其他到模块,所以这就很好的避免了上面的multi definition的问题
相关文章推荐
- 关于当前控制文件丢失为何只能作不…
- 关于头文件中的 static inline函数
- 关于static函数能不能在其他文件中使用的问题
- 关于为何Myeclipse里面有改动但是deploy到tomcat后tomcat内的相关文件没有变动
- C语言学习4: 函数返回值与传入参数,关于函数值传递和类型隐性转换,变量不同的作用域,static变量,多文件编译例如两个C文件,显示函数调用语句跳转,递归,斐波那契数列,多文件编译相同变量的问题。
- 关于头文件中的 static inline函数
- 关于从Eclipse导入项目到android studio中R文件丢失,会自动导import static com.baidu.location.b.g.R;
- 关于头文件中的 static inline函数
- 关于vue项目中static文件下的静态文件找不到的问题
- 关于头文件中的 static inline函数
- 关于禁止js文件缓存问题
- 关于acm C++一些常用函数和头文件
- 关于动态生成WML文件的一个Java实例(4)
- 积分项目关于 文件上传
- 关于c#文件操作Streamwriter,streamreader的使用
- 关于java打包成jar文件的问题
- 关于Java static 与继承的执行顺序
- 关于使用FileStream读写文件
- 关于Unity中的特殊文件目录和资源管理(专题四)
- unix下关于替换文件中^M字符