zoukankan      html  css  js  c++  java
  • Keil c中自定义带可变参数的printf函数

    在嵌入式c中,往往采用串口打印函数来实现程序的调试,而在正式程序中一般是不需要这些打印代码的,通常做法是在这些调试用打印代码的前后设置一个宏定义块来实现是否启用这段代码,比如:

    // other user code ... 
    
    #ifdef USE_DEBUG
    printf("the monitor count is %d", count);
    #endif
    
    // other user code ... 

    如果定义了USE_DEBUG,则打印起作用;否则上述代码块不会被编译。

    但上述代码块存在一个问题,当需要打印的地方很多时,都需要写这么一段,程序代码会显得比较臃肿和繁琐;如果能自己定义一个类printf打印函数,在函数内实现上述代码块,这样代码是比较简便的,本文即实现该功能,自定义函数实现如下:

    #ifdef USE_DEBUG  
    
    #include <stdarg.h>    // 调用头文件
    #define bufsize 120    
    char buffer[bufsize];  // 待打印字符串缓存
    
    #endif
    
    // 自定义打印函数
    void envprintf(const char * str, ...)
    {    
      #ifdef USE_DEBUG
    
      va_list args;
      va_start(args, str);    
      vsnprintf(buffer,bufsize,str,args);        
      va_end(args);
      printf("%s
    ", buffer);
    
      #endif
    }

    上述代码中的vsnprintf函数将多变参数转换成字符串并保存至buffer中; 最后通过printf打印出来。 

    改进后程序中打印代码如下:

    // other user code ... 
    
    envprintf("the monitor count is %d", count);
    
    // other user code ... 

    总结:本文只是通过可变参数功能实现打印的一个示例,在程序代码中可以通过可变参数的系列功能宏定义与相关函数(比如vsnprintf、va_arg等)实现更多的应用。

  • 相关阅读:
    Linq聚合操作之Aggregate,Count,Sum,Distinct源码分析
    Linq分区操作之Skip,SkipWhile,Take,TakeWhile源码分析
    Linq生成操作之DefautIfEmpty,Empty,Range,Repeat源码分析
    Linq基础操作之Select,Where,OrderBy,ThenBy源码分析
    PAT 1152 Google Recruitment
    PAT 1092 To Buy or Not to Buy
    PAT 1081 Rational Sum
    PAT 1084 Broken Keyboard
    PAT 1077 Kuchiguse
    PAT 1073 Scientific Notation
  • 原文地址:https://www.cnblogs.com/raswin/p/10494196.html
Copyright © 2011-2022 走看看