Debug formatted output----based on C language

Source: Internet
Author: User

Debug formatted output----based on C language 1. Using macro implementations

Example:

#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. Using functions to implement

Several key macros are used in the implementation process:

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

To use the vsnprintf () function

vsnprintf()头文件:#include <stdarg.h>函数原型:int vsnprintf(char *str, size_t size, const char *format, va_list ap);函数说明:将可变参数格式化输出到一个字符数组

Example:

#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;}
Summary

Through the above two methods can be implemented with debug output containing location information debugging information.

Debug formatted output----based on C language

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.