programing tip

Win32 앱에서 디버그 출력 창에 인쇄하려면 어떻게해야합니까?

itbloger 2020. 9. 16. 07:25
반응형

Win32 앱에서 디버그 출력 창에 인쇄하려면 어떻게해야합니까?


Visual Studio 2005에로드 한 win32 프로젝트가 있습니다. Visual Studio 출력 창에 항목을 인쇄하고 싶지만 평생 어떻게해야할지 모르겠습니다. 나는 'printf'와 'cout <<'을 시도했지만 내 메시지는 완고하게 인쇄되지 않습니다.

Visual Studio 출력 창에 인쇄하는 특별한 방법이 있습니까?


사용할 수 있습니다 OutputDebugString. OutputDebugString빌드 옵션에 따라 OutputDebugStringA(char const*)또는에 매핑되는 매크로입니다 OutputDebugStringW(wchar_t const*). 나중의 경우 함수에 넓은 문자열을 제공해야합니다. 와이드 문자 리터럴을 만들려면 L접두사를 사용할 수 있습니다 .

OutputDebugStringW(L"My output string.");

일반적으로 다음과 같이 _T매크로와 함께 매크로 버전을 사용합니다 .

OutputDebugString(_T("My output string."));

프로젝트가 UNICODE 용으로 빌드되도록 구성된 경우 다음으로 확장됩니다.

OutputDebugStringW(L"My output string.");

UNICODE를 위해 빌드하지 않는 경우 다음으로 확장됩니다.

OutputDebugStringA("My output string.");

프로젝트가 GUI 프로젝트 인 경우 콘솔이 표시되지 않습니다. 프로젝트를 콘솔로 변경하려면 프로젝트 속성 패널로 이동하여 다음을 설정해야합니다.

  • " linker-> System-> SubSystem "에서 " Console (/ SUBSYSTEM : CONSOLE) "값
  • " C / C ++-> 전 처리기-> 전 처리기 정의 "에서 " _CONSOLE "정의를 추가하십시오.

이 솔루션은 고전적인 " int main () "진입 점이 있는 경우에만 작동합니다 .

그러나 내 경우 (openGL 프로젝트)와 같은 경우에는 더 잘 작동하므로 속성을 편집 할 필요가 없습니다.

AllocConsole();
freopen("CONIN$", "r",stdin);
freopen("CONOUT$", "w",stdout);
freopen("CONOUT$", "w",stderr);

printf 및 cout은 평소와 같이 작동합니다.

창을 만들기 전에 AllocConsole을 호출하면 콘솔이 창 뒤에 나타나고 나중에 호출하면 앞에 나타납니다.


real콘솔에 인쇄하려면 링커 플래그를 사용하여 표시해야합니다 /SUBSYSTEM:CONSOLE. 추가 콘솔 창은 성가 시지만 디버깅 목적으로 매우 유용합니다.

OutputDebugString 디버거 내에서 실행될 때 디버거 출력에 인쇄합니다.


_RPT N () 및 _RPTF N () 보고를 위해 VC ++ 런타임 매크로 사용을 고려하십시오.

CRTDBG.H에 정의 된 _RPTn 및 _RPTFn 매크로를 사용하여 디버깅을위한 printf 문 사용을 대체 할 수 있습니다. 이러한 매크로는 _DEBUG가 정의되지 않은 경우 릴리스 빌드에서 자동으로 사라 지므로 #ifdefs로 묶을 필요가 없습니다.

예...

if (someVar > MAX_SOMEVAR) {
    _RPTF2(_CRT_WARN, "In NameOfThisFunc( )," 
         " someVar= %d, otherVar= %d\n", someVar, otherVar );
}

또는 VC ++ 런타임 함수 _CrtDbgReport, _CrtDbgReportW를 직접 사용할 수 있습니다.

_CrtDbgReport 및 _CrtDbgReportW는 디버그 보고서 파일, 디버그 모니터 (Visual Studio 디버거) 또는 디버그 메시지 창의 세 가지 다른 대상으로 디버그 보고서를 보낼 수 있습니다.

_CrtDbgReport 및 _CrtDbgReportW는 printf 또는 wprintf 함수에 정의 된 동일한 규칙을 사용하여 argument [n] 인수를 형식 문자열로 대체하여 디버그 보고서에 대한 사용자 메시지를 만듭니다. 그런 다음 이러한 함수는 디버그 보고서를 생성하고 reportType에 대해 정의 된 현재 보고서 모드 및 파일을 기반으로 대상을 결정합니다. 보고서가 디버그 메시지 창으로 전송되면 파일 이름, lineNumber 및 moduleName이 창에 표시되는 정보에 포함됩니다.


소수 변수를 인쇄하려면 다음을 수행하십시오.

wchar_t text_buffer[20] = { 0 }; //temporary buffer
swprintf(text_buffer, _countof(text_buffer), L"%d", your.variable); // convert
OutputDebugString(text_buffer); // print

코드를 변경하지 않고 (또는 최소한의 변경으로) printf를 광범위하게 사용한 기존 프로그램의 출력을 확인해야하는 경우 다음과 같이 printf를 재정의하고 공통 헤더 (stdafx.h)에 추가 할 수 있습니다.

int print_log(const char* format, ...)
{
    static char s_printf_buf[1024];
    va_list args;
    va_start(args, format);
    _vsnprintf(s_printf_buf, sizeof(s_printf_buf), format, args);
    va_end(args);
    OutputDebugStringA(s_printf_buf);
    return 0;
}

#define printf(format, ...) \
        print_log(format, __VA_ARGS__)

Win32 프로젝트는 콘솔 프로젝트가 아닌 GUI 프로젝트 일 수 있습니다. 이로 인해 실행 가능한 헤더에 차이가 발생합니다. 결과적으로 GUI 프로젝트는 자체 창을 열어야합니다. 하지만 콘솔 창일 수 있습니다. 호출 AllocConsole()하여 작성하고 Win32 콘솔 함수를 사용하여 작성하십시오.


나는 이것을 직접 할 방법을 찾고 있었고 간단한 해결책을 찾았습니다.

I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:

Project -> Properties -> Linker -> System -> Subsystem

And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.

Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.

So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.

The starting part of your program should now look something like this:

#include <iostream>

using namespace std;

// Main function for the console
int main(){

    // Calling the wWinMain function to start the GUI program
    // Parameters:
    // GetModuleHandle(NULL) - To get a handle to the current instance
    // NULL - Previous instance is not needed
    // NULL - Command line parameters are not needed
    // 1 - To show the window normally
    wWinMain(GetModuleHandle(NULL), NULL,NULL, 1); 

    system("pause");
    return 0;
}

// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    // This will display "Hello World" in the console as soon as the GUI begins.
    cout << "Hello World" << endl;
.
.
.

Result of my implementation

Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.


You can also use WriteConsole method to print on console.

AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);

참고URL : https://stackoverflow.com/questions/1333527/how-do-i-print-to-the-debug-output-window-in-a-win32-app

반응형