mikan's technical note

仕事&趣味で実験した小技の備忘録です(Linux,windows,DOS等)

MENU

【C言語】printfで実行した行番号を出力する

//
// 【printfで実行した行番号を出力する】※Solaris,RedHutで動作確認済
// (c) 2017 mikan
// ※使用にあたっては利用者の自己責任でお願いします。
//
#include <stdio.h>
#include <stdarg.h>
#include <errno.h>

// printfマクロ
#define DBGPRI(fmt, ...) debug_printf(__FILE__, __func__, __LINE__, fmt, ##__VA_ARGS__)

// printf関数
void debug_printf(const char *file, const char *func, const int line, const char *fmt, ...)
{
    printf("%s,%s(),%d,%d:", file, func, line, errno);

    va_list ap;
    va_start(ap, fmt);
    vfprintf(stdout, fmt, ap);
    va_end(ap);

    printf("\n");
}

int main()
{
  DBGPRI("start");              // Sun C 5.8 ... compile Warning, gcc ... compile OK
  DBGPRI("start %s", "");       // compile OK
  DBGPRI("start %s", "test");   // compile OK

  return 0;
}

【実行結果】
dbgpri.c,main(),23,0:start
dbgpri.c,main(),24,0:start
dbgpri.c,main(),25,0:start test