C2129 static function declared but not defined 已定义的函数却报错未定义

目录

提出问题

问题分析

解决方案


提出问题

今天写毕设项目,发生了一个我无法理解的错误;

我在 a.h 中声明了一个static函数calcSIFTDescriptor,并在 a.cpp 中进行了定义;

当我在 main.cpp 中调用执行时报错

Severity	Code	Description	Project	File	Line	Suppression State
Error	C2129	static function 'void calcSIFTDescriptor(const cv::Mat &,cv::Point2f,float,float,int,int,float *)' declared but not defined	OpenCVSiftImplementation	e:\vsproj\opencvsiftimplementation\opencvsiftimplementation\opencvsiftimplementation.cpp	502	

说Error C2129 static function  declared but not defined,也就是说我声明了这个静态函数,却没有定义,而且是说在 main.cpp 中没有定义

当时我就蒙了,首先,明明就对声明的函数做了定义;其次,报错的位置怎么会出现在 main.cpp 中呢??



问题分析

经过搜索,在stackoverflow上找到了相同问题《function declared static but never defined》(https://stackoverflow.com/questions/15681442/function-declared-static-but-never-defined

I have a header file suppose abc.h, where i have function declaration as:

static int function1();

I have included this header file in abc.c and has defined the function and used it.

static int function1()
{
 < function definition>
}

After compiling I am getting warning:

warning: function1 declared static but never defined

最佳回答为

A static function can be declared in a header file, but this would cause each source file that included the header file to have its own private copy of the function, which is probably not what was intended.

Are u sure u haven't included the abc.h file in any other .c files?

Because declaring a function as static, requires the function to be defined in all .c file(s) in which it is included.

即是说:

当一个静态函数被声明的时候,所有引用这个静态函数所在头文件的源文件都需要单独对该函数做一次定义。

Good practice: Declare static functions in the source file they are defined in (please also provide prototype), since that's the only file they are visible in.

This way, the function is only visible to that file, such visibility issues can reduce possible code conflict!

这样做的好处就是静态函数只在所在 .c 源代码文件域内可见,可以避免代码冲突。



 同样可见于微软官网对Compiler Error C2129的解释

Compiler Error C2129

  • 09/15/2006
  • 2 minutes to read

static function 'function' declared but not defined

A forward reference was made to a static function that was never defined.

A function declared static must be defined within file scope. If the function is defined in another file, it should be declared with the keyword extern.



解决方案

将头文件中的 static 关键字换成 extern 关键字。

不过由于函数的声明extern关键词是可有可无的,因为函数本身不加修饰的话就是extern,所以也可以直接删除 static 关键字即可


C++博大精深,对关键词的理解仍需要巩固加强

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值