C语言通过宏屏蔽系统的差异
起因
前一段时间,阅读了WRK(压力测试工具)的源码,里面用ae(一个简单事件驱动),大名顶顶的Redis也是在用ae屏蔽的各个平台的差异(Linux的epoll/Bsd的kqueue/Solaris的evport).1. 通过宏引入不同针对平台的c文件
/*抽象*/
/* Include the best multiplexing layer supported by this system.
* The following should be ordered by performances, descending. */
#ifdef HAVE_EVPORT
#include "ae_evport.c"
#else
#ifdef HAVE_EPOLL
#include "ae_epoll.c"
#else
#ifdef HAVE_KQUEUE
#include "ae_kqueue.c"
#else
#include "ae_select.c"
#endif
#endif
#endif
2. 宏是怎么来的
#ifndef CONFIG_H
#define CONFIG_H
//根据编译器内置的针对系统的宏去定义宏
//1.如果是FreeBSD和Mac系统就动议HAVE_KQUEUE
#if defined(__FreeBSD__) || defined(__APPLE__)
#define HAVE_KQUEUE
//2. 如果是Linux 就定义HAVE_EPOlL
#elif defined(__linux__)
#define HAVE_EPOLL
//3. 如果是Solaris,就定义HAVE_EVPORT,还引入对应的头文件
#elif defined (__sun)
#define HAVE_EVPORT
#define _XPG6
#define __EXTENSIONS__
#include <stropts.h>
#include <sys/filio.h>
#include <sys/time.h>
#endif
#endif /* CONFIG_H */
3. 如何屏蔽系统平台的差异
#include "ae.h" //***通过该文件,声明函数原型,然后在下边 通过宏判断不同平台的实现,在该平台c文件中实现函数原型
#include "zmalloc.h"
#include "config.h"
/*抽象*/
/* Include the best multiplexing layer supported by this system.
* The following should be ordered by performances, descending. */
#ifdef HAVE_EVPORT
#include "ae_evport.c"
#else
#ifdef HAVE_EPOLL
#include "ae_epoll.c"
#else
#ifdef HAVE_KQUEUE
#include "ae_kqueue.c"
#else
#include "ae_select.c"
#endif
#endif
#endif
秋风
2021-08-31