VS2005 与 gcc 中可变参数宏

1 篇文章 0 订阅
1 篇文章 0 订阅
#include <stdio.h>
#include <stdarg.h>

int my_printf(const char * fmt, ...)
{
    int r_sn;
    int r = 0;
    va_list args;
    char printf_buf[256];

    va_start(args, fmt);
    r_sn = vsnprintf(printf_buf + r, sizeof(printf_buf), fmt, args);
    va_end(args);

#ifdef WIN32
	// VS2005 中, 如果缓冲区 < 字符串长, 返回 -1 
    if (r_sn < 0)
    {
        r_sn = sizeof(printf_buf);
    }
#endif

    // 因为下面要加字符串结束标志 0 ,所以此处 -1
    r += (r_sn >= sizeof(printf_buf)) ? (sizeof(printf_buf) - 1): r_sn;

    printf_buf[r] = 0; // 添加 0 表明字符串结束

    printf("%s\n",printf_buf); // 此处加一个 \n 以换行

    return r;
}


#if 0  // gcc version 4.4.3

// GCC , 以下三种形式都是正确的,个人感觉前两种好些,因为毕竟还有 fmt 参数:)
#define LOG(fmt...)           my_printf(fmt) 
//#define LOG(fmt , args...)    my_printf(fmt, ##args)
//#define LOG(...)              my_printf(__VA_ARGS__) 

// GCC, 下面的形式对于 LOG("This is LOG"); 来说是错误的
//      因宏展开后变为: my_printf("This is LOG", );
//      在逗号后面没有参数,故 gcc 会报错
//#define LOG(fmt, ...)         my_printf(fmt, __VA_ARGS__) 

#else  // VS2005

// VS2005 , 以下两种形式都是正确的
#define LOG(fmt, ...)         my_printf(fmt, __VA_ARGS__) 
//#define LOG(...)              my_printf(__VA_ARGS__) 

#endif


int main(void)
{
    LOG("This is LOG");
    LOG("This is LOG = %d", 12);
    LOG("This is LOG = %s", "string");

    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值