sourcecode

C에서 인쇄 매크로 디버그?

codebag 2023. 7. 22. 09:59
반응형

C에서 인쇄 매크로 디버그?

C에서 DEBUG 기호가 정의되었을 때만 인쇄되는 printf와 같은 매크로를 정의하는 적절한 방법은 무엇입니까?

#ifdef DEBUG
#define DEBUG_PRINT(???) ???
#else
#define DEBUG_PRINT(???) ???
#endif

어디?무엇을 작성해야 할지 잘 모르는 부분입니다.

나는 이 관용구를 꽤 많이 보았습니다.

#ifdef DEBUG
# define DEBUG_PRINT(x) printf x
#else
# define DEBUG_PRINT(x) do {} while (0)
#endif

다음과 같이 사용:

DEBUG_PRINT(("var1: %d; var2: %d; str: %s\n", var1, var2, str));

일부 오래된 C 컴파일러는 매크로의 변수를 지원하지 않기 때문에 추가 괄호가 필요합니다.

#ifdef DEBUG
#define DEBUG_PRINT(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false )
#else
#define DEBUG_PRINT(...) do{ } while ( false )
#endif

다음과 같은 것:

#ifdef DEBUG
#define DEBUG_PRINT(fmt, args...)    fprintf(stderr, fmt, ## args)
#else
#define DEBUG_PRINT(fmt, args...)    /* Don't do anything in release builds */
#endif

미파디 감사합니다, 파일 정보로 DEBUG_PRINT도 개선했습니다.

#define DEBUG 3

#if defined(DEBUG) && DEBUG > 0
 #define DEBUG_PRINT(fmt, args...) fprintf(stderr, "DEBUG: %s:%d:%s(): " fmt, \
    __FILE__, __LINE__, __func__, ##args)
#else
 #define DEBUG_PRINT(fmt, args...) /* Don't do anything in release builds */
#endif

최신 쨍그랑 소리로 테스트했습니다.

int main(int argc, char **args) {
    DEBUG_PRINT("Debugging is enabled.\n");    
    DEBUG_PRINT("Debug level: %d", (int) DEBUG);
}

출력:

DEBUG: debug.c:13:main(): Debugging is enabled.
DEBUG: debug.c:14:main(): Debug level: 3

DEBUG_PRINT의 다른 서명을 사용하면 다음과 같이 동일할 필요가 없습니다.

#ifdef DEBUG
#define DEBUG_PRINT printf
#else
#define DEBUG_PRINT(...)
#endif

이렇게 하면 디버그 모드에서 DEBUG_PRINT 호출이 printf로 대체됩니다.릴리스 시 이전에 사용된 모든 인수가 무시됩니다.

도움이 되길 바랍니다.

다음을 간단히 사용할 수 있습니다.

#ifdef DEBUG
    #define DEBUG_PRINT printf
#else
    #define DEBUG_PRINT
#endif

이 방법이 가장 마음에 듭니다. 이 방법은 릴리스 빌드에 ASM 지침을 추가하지 않기 때문입니다.

#define DEBUG
#ifdef DEBUG
#define  debug_printf(fmt, ...)  printf(fmt, __VA_ARGS__);
#else
#define debug_printf(fmt, ...)    /* Do nothing */
#endif

이것은 C와 C++ 모두에서 작동합니다! (앞의 공간은__VA_ARGS__C++에서 작동하려면 필요합니다!

주요 답변에서 구현에 약간의 사소한 오류가 있습니다.제 접근 방식은 다음과 같습니다.

#ifdef DEBUG
    #define DEBUG_PRINTF(...) printf("DEBUG: " __VA_ARGS__)
#else
    #define DEBUG_PRINTF(...) do {} while (0)
#endif

사용 예:

DEBUG_PRINTF("hello\n");

그리고 나서, 만약 내가 빌드하고 실행한다면,-DDEBUGC 빌드 옵션에서 다음과 같이 정의합니다.

# Build
gcc -Wall -Wextra -Werror -std=c11 -DDEBUG -o build/my_program \
my_program_tests.c my_program.c

# Run
build/my_program

그러면 다음 출력이 표시됩니다.

DEBUG: hello

하지만 내가 건축을 한다면,밖에서-DDEBUG컴파일러 C 옵션에서 정의하면 디버그 출력이 전혀 표시되지 않습니다.

기타 참고문헌

  1. 이것을 C++와 호환되도록 하는 수정 사항: https://stackoverflow.com/a/72777133/4561887 : 앞에 공백 추가__VA_ARGS__.사용하다"DEBUG: " __VA_ARGS__대신에"DEBUG: "__VA_ARGS__!

언급URL : https://stackoverflow.com/questions/1941307/debug-print-macro-in-c

반응형