\
    (defined(SMALLOC) && defined(SBRK_OK)) || \
    defined(BSDMALLOC)
#define MALLOC(x)      malloc(x)
#define FREE(x)        free(x)
#define REALLOC(x,y)    realloc(x,y)
#define CALLOC(x,y)    calloc(x,y)
 
#endif
 
/* smalloc - choice between replacement or wrapper */
#if defined(SMALLOC) && !defined(SYSMALLOC)
#  ifdef SBRK_OK   
#    define smalloc_malloc        malloc
#    define smalloc_free          free
#    define smalloc_realloc      realloc
#    define smalloc_calloc        calloc
#  else
#    define MALLOC(x)      smalloc_malloc(x)
#    define FREE(x)        smalloc_free(x)
#    define REALLOC(x,y)    smalloc_realloc(x,y)
#    define CALLOC(x,y)    smalloc_calloc(x,y)
#  endif
#endif
 
/* bsdmalloc - always a replacement */
#if defined(BSDMALLOC) && !defined(SYSMALLOC)
#  define bsdmalloc_malloc      malloc
#  define bsdmalloc_free        free
#  define bsdmalloc_realloc    realloc
#  define bsdmalloc_calloc      calloc
#endif
 
#define DXALLOC(x,tag,desc)    xalloc(x)
#define DMALLOC(x,tag,desc)    MALLOC(x)
#define DREALLOC(x,y,tag,desc)  REALLOC(x,y)
#define DCALLOC(x,y,tag,desc)  CALLOC(x,y)
 
另外在其他文件里有些零零散散宏定义,这所有的宏定义组合起来,让MudOS最终编译时拥有一套合适的内存分配方案。这两个文件(macro.h、malloc.h)的内容大致描述了选择不同的宏定义将会使用到哪些内存分配函数。
(注: 这些宏定义之间的联系实在是错综复杂,足足看了两天才搞清楚选择某个宏将会用到哪些函数。然而在C++里面,完全可以抛开这些宏定义,直接用模板来控制客户代码所使用的函数库,比如STL中的Allocator,这么做又不会损失执行效率,可见模板真是个不错的东西,难怪java、c#要添加这些功能。)
 
列举几个在MudOS源码中出现的比较奇怪的宏定义:
1.         
#if (defined(SYSMALLOC) + defined(SMALLOC) + defined(BSDMALLOC)) > 1
#error Only one malloc package should be defined
#endif
三个宏至少定义一个,否则报错。#error是我自己添加的,源代码为“!”,为什么源代码不用#error呢?
在#if语句里,可以使用大小比较符号:“>”、“<”、“==”比如下面这行代码:
#if defined(AA) || defined(BB)  || defined(CC)
就可以改写成:
#if (defined(AA) + defined(BB)  + defined(CC)) > 0
2.         
#if defined(BSDMALLOC) && !defined(SYSMALLOC)
#  define bsdmalloc_malloc      malloc
#  define bsdmalloc_free        free
#  define bsdmalloc_realloc    realloc
#  define bsdmalloc_calloc      calloc
#endif
如果定义了BSDMALLOC,而SYSMALLOC未定义,那么用malloc代替bsdmalloc_malloc。这是个非常奇怪的定义:假如编译过程中已有malloc函数的定义,那么用这里出现的替代将会导致程序编译出现重定义的错误。比如下面这个例子:
void func() { 
};
#define FUNC func
void FUNC() {    // !error: function 'void __cdecl func(void)' already has a body
};
或许作者压根就不想用bsdmalloc_malloc,如同注释里写的”always a replacement”,只是把已有代码里的bsdmalloc_malloc替换成系统内建的malloc。同样问题也出现在smalloc上。这里不对其深究,老实说这些龇牙咧嘴的宏定义很容易让人走火入魔的。
BSD malloc 

下一页 上一页
返回列表
返回首页
©2024 MUD游戏网_文字mud 电脑版
Powered by iwms