首页 > 其他 > 详细

使用宏打印错误信息

时间:2020-12-11 14:13:05      阅读:33      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <stdio.h>
#include <err.h>

using namespace std;

// Prints warning message on stderr in the format:
// <progname>: FILE:LINE in FUNC: <fmt>: <errno_msg>
#define twarn(...) __twarn(__VA_ARGS__, "")

// Hack to quiet the compiler. When VA_ARGS in twarn() has one element,
// e.g. twarn("OOM"), its replaced with __twarn("OOM", ""),
// thus VA_ARGS is expanded to at least one element in warn().
#define __twarn(fmt, ...) \
    warn("%s:%d in %s: " fmt "%s", __FILE__, __LINE__, __func__, __VA_ARGS__)

// Prints warning message on stderr in the format:
// <progname>: FILE:LINE in FUNC: <fmt>
#define twarnx(...) __twarnx(__VA_ARGS__, "")

// See __twarn macro.
#define __twarnx(fmt, ...) \
    warnx("%s:%d in %s: " fmt "%s", __FILE__, __LINE__, __func__, __VA_ARGS__)



int main()
{
        twarn("error1");
        twarnx("error2");
        return 0;
}

输出

a.out: define.cpp:29 in main: error: Success
a.out: define.cpp:31 in main: twarnx

浅析

warn 输出 到标准错误并带有 errno 相关的错误信息

warnx 同 warn,但不带 errno 的错误信息

宏定义

gcc 编译时自带

 __FILE__      表示文件的名字
__LINE__      当前行数
__func__      当前函数
__VA_ARGS__    和 define 有关  与 ... 配套使用 代表的 define 中最有一个参数
#include <iostream>

#define PA(a,b,...)     printf("%d %d %s\n", a, b, __VA_ARGS__)



int main()
{
        PA(1,4,"hello");
        return 0;
}

输出

1 4 hello

 






使用宏打印错误信息

原文:https://www.cnblogs.com/sau-autumnwind/p/14119562.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!