Debug格式化輸出----基於C語言

來源:互聯網
上載者:User

標籤:stdarg.h   clu   --   markdown   __file__   body   data   mes   原型   

Debug格式化輸出----基於C語言1. 使用宏實現

舉例:

#include <stdio.h>#define ECHO_COLOR_NONE         "\033[0;0m"#define ECHO_COLOR_GREEN        "\033[0;32m"#define debug(fmt, args...)               printf(ECHO_COLOR_GREEN"Debug: " fmt "(file: %s, func: %s, line: %d)\n"ECHO_COLOR_NONE, ##args, __FILE__, __func__, __LINE__);
// 測試程式int main(void){     int data = 10;     debug("This is a test, data = %d", data);     printf("OK\n");     return 0;}
2. 使用函數實現

在實現過程中要用到幾個關鍵宏:

#include <stdarg.h>va_list argp;va_start(argp, fmt);va_end(argp);

要用到vsnprintf()函數

vsnprintf()標頭檔:#include <stdarg.h>函數原型:int vsnprintf(char *str, size_t size, const char *format, va_list ap);函數說明:將可變參數格式化輸出到一個字元數組

舉例:

#include <stdio.h>#include <stdarg.h>#define ECHO_COLOR_NONE         "\033[0;0m"#define ECHO_COLOR_GREEN        "\033[0;32m"#define debug_print(message, ...)   debug_msg(message, __FILE__, __func__, __LINE__, ##__VA_ARGS__)void debug_type(char *fmt, char *file, const char *func, int line, va_list argp){     char buffer[128] = { 0 };      vsnprintf(buffer, sizeof(buffer), fmt, argp);     printf(ECHO_COLOR_GREEN"Debug: %s(file: %s, func: %s, line: %d)\n"ECHO_COLOR_NONE, buffer, file, func, line);}void debug_msg(char *fmt, char *file, const char *func, int line, ...){     va_list arg_list;     va_start(arg_list, line);     debug_type(fmt, file, func, line, arg_list);     va_end(arg_list);}
// 測試程式int main(void){     int data = 10;     debug_print("This is a test, data = %d", data);     printf("OK\n");     return 0;}
小結

通過以上兩種方法就可以實現用debug輸出含有位置資訊的調試資訊。

Debug格式化輸出----基於C語言

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.