【发布时间】:2018-12-22 08:54:16
【问题描述】:
我在编译我的代码时遇到了几个与“htonf”c++ 函数错误相关的错误。非常感谢您的帮助。
以下是错误:
错误 C2556 'long htonf(float)': 重载的函数仅在返回类型与 'unsigned int htonf(float)' 方面不同
错误 C2371 'htonf':重新定义;不同的基本类型 ecueHost
错误 C2065 'htonf':未声明的标识符
错误出现在下面的datapacket.cpp中
#include "str.h"
#include "DataPacket.h"
#include "exception.h"
#include "message.h"
#include "object.h"
#include "util.h"
#define MAX_DATA_LENGTH 4096
long htonf(float f)
{
long x;
x = *((long*)&f);
x = htonl(x);
return x;
}
float ntohf(long l)
{
float f;
l = ntohl(l);
f = *((float*)&l);
return f;
}
在“datapacket.h”头文件中包含的“winsock2.h”头文件中,“htonf”定义如下:
#ifndef htonf
__inline unsigned __int32 htonf ( float Value )
{
unsigned __int32 Tempval;
unsigned __int32 Retval;
Tempval = *(unsigned __int32*)(&Value);
Retval = _WS2_32_WINSOCK_SWAP_LONG
(Tempval);
return Retval;
}
#endif /* htonf */
在“datapacket.cpp”文件本身中,“htonf”也在这里声明
// Store a float to the datapacket
TDataPacket& TDataPacket::operator<<(float f)
{
long x = htonf(f);
return SerializingIn(&x, LONG_SIZE);
}
【问题讨论】:
-
线索在第二条错误信息
'htonf': redefinition;。这意味着您包含的一个(或多个)头文件以与您在datapacket.cpp中使用的方式不同的方式声明htonf。因此,请查看htonf的头文件并在此处发布您找到的任何内容。 -
您能否尝试创建一个minimal reproducible example 来向我们展示?您何时、何地以及如何声明这些功能?
-
顺便说一句,该代码非常可疑,因为它假定
float和long的大小相同,这不一定是正确的(尤其是在 64 位计算时代)。你是从哪里弄来的? -
顺便说一句,像这样的双关语会破坏strict aliasing。您需要遍历字节 (
char) 数组才能完全兼容。 -
@john 这是一个非常古老的代码,我正在尝试重新编译
标签: c++ visual-studio