본문 바로가기

Development

[TRACE] C++ Debug를 위한 TRACE 찍기

Trace는 프로그램이 내가 생각하는 흐름대로 흘러가는지를 살펴볼 때 주로 쓰입니다.
주로 필요한 곳에 printf로 쓰는 경우가 많은데요, 이를 매크로로 지정해두면 조금더 편하게 사용할 수 있습니다.
예를 들면 이런 식으로 define을 합니다.

  1. #include "stdio.h"
  2. #define TRACE( _x, args...) printf("[%s:%d]\t"_x"\n", __FILE__, __LINE__, ##args)

그런 후에 test.h에 저장을 했습니다.
이제 이용을 해봅시다.

다음과 같은 파일을 test1.h에 저장하고

  1. #include "test.h"
  2.  
  3. int addOne(int a)
  4. {
  5.    int ret = a + 1;
  6.    TRACE("old : %d, new : %d", a, ret);
  7.    return ret;
  8. }

다음 파일을 test.cpp에 저장해서

  1. #include "test.h"
  2. #include "test1.h"
  3.  
  4. int main()
  5. {
  6.     for(int i=0;i<5;)
  7.     {
  8.         TRACE("i is %d", i);
  9.         i = addOne(i);
  10.     }
  11.     return 0;
  12. }

컴파일해서 실행해보았습니다.

haneul@haneul:~/test$ g++ test.cpp
haneul@haneul:~/test$ ./a.out
[test.cpp:8]    i is 0
[test1.h:6]     old : 0, new : 1
[test.cpp:8]    i is 1
[test1.h:6]     old : 1, new : 2
[test.cpp:8]    i is 2
[test1.h:6]     old : 2, new : 3
[test.cpp:8]    i is 3
[test1.h:6]     old : 3, new : 4
[test.cpp:8]    i is 4
[test1.h:6]     old : 4, new : 5

TRACE에서 지정한 __FILE__, __LINE__ 매크로가 각각 해당 소스 파일의 파일명과 라인 위치를 표시해주기 때문에 디버깅 정보로 사용하는데 큰 도움이 됩니다;

보통은

  1. #include "stdio.h"
  2. #ifdef _DEBUG
  3.     #define TRACE( _x, args...) printf("[%s:%d]\t"_x"\n", __FILE__, __LINE__, ##args)
  4. #else
  5.     #define TRACE( _x, args...)
  6. #endif

 이런식으로 해서 _DEBUG가 세팅 되어있을 때만 나타나도록 하는 경우도 많지요

haneul@haneul:~/test$ g++ test.cpp
haneul@haneul:~/test$ ./a.out
haneul@haneul:~/test$ g++ test.cpp -D_DEBUG
haneul@haneul:~/test$ ./a.out
[test.cpp:8]    i is 0
[test1.h:6]     old : 0, new : 1
[test.cpp:8]    i is 1
[test1.h:6]     old : 1, new : 2
...


자;; 열심히 디버깅 해봅시다 @_@


출처 : http://haneul.isloco.com/?page=11

'Development' 카테고리의 다른 글

[CListCtrl] MeasureItem  (0) 2009.01.13
[Utility] 유용한 유틸리티  (2) 2009.01.13
[Lex&Yacc] 정보  (0) 2009.01.08
[Visual Studio] 단축키  (0) 2009.01.08
[Visual Studio] Macro  (0) 2009.01.08