<分区>
Possible Duplicate:
C/C++: Static function in header file, what does it mean?
When to put static function definitions in header files in C?
在头文件中使用静态函数的优缺点是什么?
<分区>
Possible Duplicate:
C/C++: Static function in header file, what does it mean?
When to put static function definitions in header files in C?
在头文件中使用静态函数的优缺点是什么?
最佳答案
假设您在头文件中实现它,每次包含您的头文件时,该函数都会被复制。这意味着生成的二进制文件更重、不良做法以及调试和维护的整体噩梦。
如果只是在头文件中定义,则需要在每个C文件中实现。
编辑
编辑 2 这是您可能会遇到的陷阱
static.h
#ifndef _STATIC_H_
#define _STATIC_H_
#include <stdio.h>
static void printer(void);
void nonStatic (void);
#endif
a.c
#include "static.h"
static void printer(void)
{
printf ("half the truth : 21\n");
}
int main (void) {
printer();
nonStatic();
}
b.c
#include <stdio.h>
#include "static.h"
static void printer (void)
{
printf("Truth : 42\n");
}
void nonStatic(void)
{
printf ("Non static\n");
printer();
}
看看这段代码,你从 2 个不同的位置调用“打印机”,你会得到不同的行为:
D:\temp>gcc -o temp.exe a.c b.c && temp
half the truth : 21
Non static
Truth : 42
在这个小例子中很明显,当隐藏在一个大软件中时真的很棘手
关于c - 在头文件中使用静态函数的优缺点是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11390702/