Chinaunix首页 | 论坛 | 博客
  • 博客访问: 251535
  • 博文数量: 91
  • 博客积分: 4185
  • 博客等级: 上校
  • 技术积分: 855
  • 用 户 组: 普通用户
  • 注册时间: 2008-06-29 16:18
文章分类

全部博文(91)

文章存档

2014年(3)

2013年(1)

2012年(8)

2011年(2)

2010年(5)

2009年(68)

2008年(4)

我的朋友

分类: C/C++

2009-09-17 13:54:46

为了实现跨平台,在C语言中,可以通过宏对已经存在的函数进行重新定义。

例如,在Windows中,具有itoa这个api函数用于数字转换为字符串:

    #ifdef WIN32
        #define itoa(intSource, strTarget) itoa((intSource), (strTarget), 10);

    #else
        #define itoa(intSource, strTarget) sprintf((strTarget), "%d", (intSource));

    #endif
上面的宏定义中对Windows中的itoa函数进行了同名宏替换。

也就是说,在以后的编码过程中,itoa()中的参数只有两个,而不是原来的三个。

但上述同名宏替换需要注意一点:就是头文件的加载顺序。必须保证原函数所在头文件要在宏定义之前被加载,否则会报错。即在这段宏定义之前应先#include (itoa函数定义所在头文件)。

文件清单:

transplant.h

#ifndef _TRANSPLANT_H_

    #define _TRANSPLANT_H_

    #include

    #ifdef WIN32
        #define itoa(intSource, strTarget) itoa((intSource), (strTarget), 10);

    #else
        #define itoa(intSource, strTarget) sprintf((strTarget), "%d", (intSource));

    #endif
#endif


--------------------------------------------------------

在文件ctest.c中

#include

void hello();

#define hello() {printf("hello() macro.\n");}

int main()
{
    hello();

    return 0;
}

void hello()  /* 这里也被宏替换了! */
{
    printf("hello() function.\n");
}

阅读(2251) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~