特殊使用C宏 [英] Peculiar use of C macros

查看:108
本文介绍了特殊使用C宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

读取C库的套接字接口的代码,我发现这个:

Reading the code of the C library's sockets interface, I found this:

/* Types of sockets.  */
enum __socket_type
{
   SOCK_STREAM = 1,     /* Sequenced, reliable, connection-based
               byte streams.  */
#define SOCK_STREAM SOCK_STREAM
   SOCK_DGRAM = 2,      /* Connectionless, unreliable datagrams
               of fixed maximum length.  */
#define SOCK_DGRAM SOCK_DGRAM
...

这个成语被全部用于/ socket.h。我只是好奇,这些宏的目的是什么?

This "idiom" is used all over bits/socket.h. I am just curious, what is the purpose of those macros?

推荐答案

这些常量只是 #define ,所以你看到的可能是为了保护你不要意外混合旧的和新的头文件。使用枚举来定义常量的优点是枚举成员往往在调试器中可用, #define 宏不要。

These constants used to just be #defines, so what you're seeing is probably there to protect you from accidentally mixing old and new header files. An advantage of using enum to define the constants is that enum members tend to be available in the debugger, and #define macros don't.

如果您(意外)包含一些其他头文件,也尝试 #define SOCK_STREAM ,您将收到一个编译器警告,而不是默认使用可能不正确的值。

If you were to (accidentally) include some other header file that also tries to #define SOCK_STREAM, you would get a compiler warning instead of silently using a possibly incorrect value.

查看 glibc git repo ,我发现特定的提交添加了 #define s,并带有这个注释:

Looking through a glibc git repo, I found the specific commit that added the #defines, with this comment:

* sysdeps/generic/socketbits.h: Also make SOCK_* constants available
as macros so that #ifdef works.
* sysdeps/unix/sysv/linux/socketbits.h: Likewise.

你有它。

这篇关于特殊使用C宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆