您的位置:首页 > 其它

关于头文件中为何要用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的问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: