【问题标题】:Running into c++ visual studio compiler error "htonf" while compiling the program编译程序时遇到 c++ Visual Studio 编译器错误“htonf”
【发布时间】: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 来向我们展示?您何时、何地以及如何声明这些功能?
  • 顺便说一句,该代码非常可疑,因为它假定 floatlong 的大小相同,这不一定是正确的(尤其是在 64 位计算时代)。你是从哪里弄来的?
  • 顺便说一句,像这样的双关语会破坏strict aliasing。您需要遍历字节 (char) 数组才能完全兼容。
  • @john 这是一个非常古老的代码,我正在尝试重新编译

标签: c++ visual-studio


【解决方案1】:
Error C2556 'long htonf(float)': overloaded function differs only by return type from 'unsigned int htonf(float)'

此错误消息完全解释了它。

你有:

__inline unsigned __int32 htonf ( float Value ) 

在winsock2.h中,和

long htonf(float f)

在 datapacket.cpp 中。您最简单的解决方案是更改 datapacket.cpp 中 htonf() 的定义以匹配您在 winsock2.h 中的定义,并根据需要调整实现以反映新的返回类型。

首先,long 是有符号的,而unsigned __int32 是无符号的,其次,即使它们在 MSVC 下大小相同,__int32long 也不是可互换的数据类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多