C语言 函数同名宏的定义及注意事项

来源:互联网 发布:淘宝主营占比影响 编辑:程序博客网 时间:2024/04/29 03:22

为了实现跨平台,在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 <stdlib.h>(itoa函数定义所在头文件)。

 

文件清单:

transplant.h

 

#ifndef _TRANSPLANT_H_

    #define _TRANSPLANT_H_

    #include <stdlib.h>

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

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

    #endif
#endif

原创粉丝点击