当前位置:编程学习 > C/C++ >>

C语言个人进阶

争取把自己的一点一滴记下来-
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 */
 


摘自 阿毛小猪
 
补充:软件开发 , C语言 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,