Debug クラス (C++/CLI)

Visual C++ アプリケーションで Debug を使うと、デバッグ ビルドとリリース ビルドで動作が変わりません。

解説

Trace の動作は Debug クラスの動作と同じですが、シンボル TRACE が定義されていることに依存します。 つまり、すべての Trace 関連コードに #ifdef を指定して、リリース ビルドでデバッグ動作が行われないようにする必要があります。

例: 常に出力ステートメントを実行する

説明

次の例では、/DDEBUG または /DTRACE を指定してコンパイルするかどうかに関係なく、常に出力ステートメントを実行します。

コード

// mcpp_debug_class.cpp
// compile with: /clr
#using <system.dll>
using namespace System::Diagnostics;
using namespace System;

int main() {
   Trace::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );
   Trace::AutoFlush = true;
   Trace::Indent();
   Trace::WriteLine( "Entering Main" );
   Console::WriteLine( "Hello World." );
   Trace::WriteLine( "Exiting Main" );
   Trace::Unindent();

   Debug::WriteLine("test");
}

出力

    Entering Main
Hello World.
    Exiting Main
test

例: #ifdef および #endif ディレクティブを使用する

説明

望ましい動作 (つまり、リリース ビルドの場合は "テスト" 出力が表示されない) にするには、#ifdef および #endif ディレクティブを使う必要があります。 次に示すのは、この修正を示すために、前のコード サンプルを変更したもので。

コード

// mcpp_debug_class2.cpp
// compile with: /clr
#using <system.dll>
using namespace System::Diagnostics;
using namespace System;

int main() {
   Trace::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );
   Trace::AutoFlush = true;
   Trace::Indent();

#ifdef TRACE   // checks for a debug build
   Trace::WriteLine( "Entering Main" );
   Console::WriteLine( "Hello World." );
   Trace::WriteLine( "Exiting Main" );
#endif
   Trace::Unindent();

#ifdef DEBUG   // checks for a debug build
   Debug::WriteLine("test");
#endif   //ends the conditional block
}

関連項目

C++/CLI (Visual C++) による .NET プログラミング