C语言 我应该#include 什么来使用'htonl'?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3173648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What should I #include to use 'htonl'?
提问by Adrian
I want to use the htonlfunction in my ruby c extension, but don't want to use any of the other internet stuff that comes with it. What would be the most minimalistic file to #includethat is still portable? Looking through the header files on my computer, I can see that either machine/endian.hor sys/_endian.hwould let me use them, although I am not sure if that is a good idea.
我想htonl在我的 ruby c 扩展中使用该函数,但不想使用它附带的任何其他互联网内容。#include仍然可移植的最简约的文件是什么?查看我计算机上的头文件,我可以看到machine/endian.h或者sys/_endian.h让我使用它们,尽管我不确定这是否是一个好主意。
采纳答案by Matthew Flaschen
The standardheader is:
的标准报头是:
#include <arpa/inet.h>
You don't have to worry about the other stuff defined in that header. It won't affect your compiled code, and should have only a minor effect on compilation time.
您不必担心该标头中定义的其他内容。它不会影响您编译的代码,并且对编译时间的影响应该很小。
EDIT: You can test this. Create two files, htonl_manual.c
编辑:您可以对此进行测试。创建两个文件,htonl_manual.c
// non-portable, minimalistic header
#include <byteswap.h>
#include <stdio.h>
int main()
{
int x = 1;
x = __bswap_32(x);
printf("%d\n", x);
}
and htonl_include.c:
和 htonl_include.c:
// portable
#include <arpa/inet.h>
#include <stdio.h>
int main()
{
int x = 1;
x = htonl(x);
printf("%d\n", x);
}
Assemble them at -O1, then take the difference:
在 -O1 处组装它们,然后取差异:
gcc htonl_manual.c -o htonl_manual.s -S -O1
gcc htonl_include.c -o htonl_include.s -S -O1
diff htonl_include.s htonl_manual.s
For me, the only difference is the filename.
对我来说,唯一的区别是文件名。
回答by Jean-Fran?ois Fabre
On Windows, arpa/inet.hdoesn't exist so this answerwon't do. The include is:
在 Windows 上,arpa/inet.h不存在所以这个答案不会做。其中包括:
#include <winsock.h>
So a portable version of the include block (always better to provide one):
所以包含块的便携版本(总是最好提供一个):
#ifdef _WIN32
#include <winsock.h>
#else
#include <arpa/inet.h>
#endif
回答by R.. GitHub STOP HELPING ICE
If you don't want to include anything network-related, it's perfectly valid to declare htonlyourself. Just #include <stdint.h>to get uint32_tand use the following prototype:
如果您不想包含任何与网络相关的内容,那么声明您htonl自己是完全有效的。只是#include <stdint.h>为了获取uint32_t和使用以下原型:
uint32_t htonl(uint32_t);
uint32_t htonl(uint32_t);
Reference: POSIX: http://www.opengroup.org/onlinepubs/9699919799/functions/htonl.html
参考:POSIX:http: //www.opengroup.org/onlinepubs/9699919799/functions/htonl.html
You can also just implement your own by testing byte order (at compiletime) using unions. This doesn't require any odd ENDIAN macros or #ifdefs.
您也可以通过使用联合测试字节顺序(在编译时)来实现自己的。这不需要任何奇怪的ENDIAN 宏或#ifdefs。

