簡體   English   中英

幫助我的printf功能

[英]Help with my printf function

出於調試目的,我想有一個printf_debug函數,它的功能就像標准的printf函數一樣,但只有在#DEFINE DEBUG為真時才會打印

我知道我必須使用varagrs(...),但我不知道如何實現它。

提前致謝。

更容易#define它。 像這樣的東西:

#ifdef DEBUG
#define printf_debug printf
#else
#define printf_debug while(0)printf
#endif

我不知道你想要達到的目標。 如果您只想在定義DEBUG執行代碼塊,請使用預處理器指令#ifdef

#include <stdio.h>
#include <stdarg.h>
#define DEBUG

void printf_debug(const char *format, ...) {
  #ifdef DEBUG
  va_list args;
  va_start(args, format);
  vprintf(format, args);
  va_end(args);
  #endif /* DEBUG */
}

您不需要使用vargs,宏將起作用。 這是一個例子,它也會打印功能和行號:

#ifdef DEBUG
#define printf_debug(fmt, args...) printf("%s[%d]: "fmt, __FUNCTION__, __LINE__, ##args)
#else
#define printf_debug(fmt, args...)
#endif

這里的## args將被args列表替換,它類似於vargs在函數調用中的作用。

您必須使用va_arg宏,它們用於訪問可變參數變量。 一個有用的鏈接: http//www.cppreference.com/wiki/c/other/va_arg 引用是針對C ++的,但這些宏也可以在C中使用。

在實際實現中,您可以使用#ifdef塊中的可變參數放置代碼。

但是,如果你正在尋找對printf的常規調用,依賴於DEBUG一個簡單的#define可以作為別名。

僅限C99編譯器!

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug(...) printf(__VA_ARGS__)
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}

說實話,不需要varidic宏你可以很容易地把它寫成:

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug printf
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}

考慮到這一點,調試信息應該轉到stderr以免干擾stdout,所以這個應該受到青睞:

#include <stdio.h>

#define DEBUG

#ifdef DEBUG
 #define debug(...) fprintf(stderr, __VA_ARGS__)
#else
 #define debug while(0)
#endif

int main(int argc, char *argv[])
{
    debug("Only shows when DEBUG is defined!\n");
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM