- C++中静态函数限制函数的链接性为本文件,用static限定符限定。
- C++要求在函数的声明和实现中均要用static进行限定,这在单文件程序中容易理解,在多文件程序中,我们往往书写如下:
#include <qDebug>
#include <asd.h>
int main()
{
qDebug() << plus(1,2);
return 0;
}
#ifndef ASD_H
#define ASD_H
static int plus(int a,int b);
#endif
#include <asd.h>
static int plus(int a,int b)
{
return (a + b);
}
- 这是有问题的,链接器会报错,说这个函数没有定义!

- 容易理解,main.cpp将asd.h文件include进来了后,在main.cpp中将会有static int plus(int a,int b);的声明,因此该函数的链接性被限制为main.cpp文件,但在main.cpp中并没有该函数的定义,所以链接器会报错!
- 所以我们把static函数的定义放在asd.h文件中,那么include到main.cpp后不就有定义了吗?
#include <qDebug>
#include <asd.h>
int main()
{
qDebug() << plus(1,2);
return 0;
}
#ifndef ASD_H
#define ASD_H
static int plus(int a,int b)
{
return (a + b);
}
#endif

- 我们看到链接通过,结果也是正确的。但这在多文件程序中成立吗?
#include <qDebug>
#include <asd.h>
#include <qwe.h>
int main()
{
qDebug() << plus(1,2);
qDebug() << func1(2,2);
return 0;
}
#ifndef ASD_H
#define ASD_H
static int plus(int a,int b)
{
return (a + b);
}
#endif
#include <asd.h>
#ifndef QWE_H
#define QWE_H
#include <asd.h>
int func1(int a,int b);
#endif
#include <qwe.h>
int func1(int a,int b)
{
return plus(a,b);
}

- 此时编译也通过了,结果也是正确的。但是将函数的定义放在头文件中,不是会由于多重包含导致同一函数有多个函数定义而导致链接失败吗?在这个例子中,asd.o文件中有plus函数,qwe.o文件中把asd.h文件包含了进来,也有plus函数。main.cpp文件依赖于这两个目标文件,为什么没有链接报错呢
- 因为静态函数被include进某个文件后,它的链接性就限定为这个文件。被include到其它文件后,它的链接性就被限定为其它文件,这两个文件之间的静态函数互不影响!!!!!
- 内联函数的定义与实现不能放在不同文件中,在多文件程序中放在头文件中。
- 总结:静态函数的作用域被限定为本文件,要用static限定,在多文件程序程序中,要把static函数的定义和实现都放在头文件中!!!!!!!!!!!!