欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C语言个人进阶

程序员文章站 2023-08-24 16:49:56
争取把自己的一点一滴记下来- 1. 跨平台开发 1) 头文件包含 通过define开关包含不同的库,定义函数类型 #ifndef win32 #include "...

争取把自己的一点一滴记下来-
1. 跨平台开发
1) 头文件包含
通过define开关包含不同的库,定义函数类型
#ifndef win32
#include "socket_posix.h"
#else  /* win32 */
#include "socket_win32.h"
#endif  /* !win32 */
结尾应该注明if适用情况。
 
2) 替换函数
#undef  errno
#define errno  wsagetlasterror()
#define read(fd, buf, size)  recv(fd, buf, size, 0)
 
2. 常用宏
今天看到非常漂亮的一个应用:
 利用宏##实现了ipv4和ipv6地址信息的初始化

#define fill_sockaddr(af_inet, sockaddr_in, sin, s,             \
                      host, port, count, addrlen, addrs)        \
  do                                                            \
    {                                                           \
      struct sockaddr_in *addr;                                 \
      int i;                                                    \
                                                                \
      addrlen = sizeof(struct sockaddr_in);                     \
                                                                \
      addr = (struct sockaddr_in *) calloc(count, addrlen);     \
      for (i = 0; i < count; ++i)                               \
        {                                                       \
          addr[i].sin##_family = af_inet;                       \
          addr[i].sin##_port = port;                            \
          memcpy(&addr[i].sin##_addr.s##_addr,                  \
                 addr(host, i), host->h_length);                \
        }                                                       \
                                                                \
      addrs = (char *) addr;                                    \
    }                                                           \
  while (0)
 
#define fill_sockaddr(host, port, count, addrlen, addrs)        \
  fill_sockaddr(af_inet, sockaddr_in, sin, s,                   \
                host, port, count, addrlen, addrs)
 
#ifdef af_inet6
#define fill_sockaddr6(host, port, count, addrlen, addrs)       \
  fill_sockaddr(af_inet6, sockaddr_in6, sin6, s6,               \
                host, port, count, addrlen, addrs)
#endif  /* af_inet6 */
 


摘自 阿毛小猪