简体   繁体   中英

Runtime how to determine Debug or release mode in visual studio c++

I am doing my school assignment. During debug mode I would like to turn on my console mode and during release turn off console.

I have try marco as recommended in stackoverflow but it is not working. I am using visual studio 2012 (empty project c++)

#if DEBUG
 //doing something
#else
 //Release mode doing something
#endif

#if DEBUG will only work if you define DEBUG via the compiler options.

By default, DEBUG is not defined, but _DEBUG is. Try #if defined(_DEBUG) , or change your compiler options (via Project Properties / Configuration Properties / C/C++ / Preprocessor / Preprocessor Definitions) to define DEBUG .

#if DEBUG will resolve itself at compile time not at run time.

NDEBUG is pretty standard macro defined in release mode. And I think Visual studio defines _DEBUG macro when in debug mode.

In any case you can define your own macros in Visual Studio

Go to Project->Properties->Configuration Properties->C/C++->Preprocessor -> Preprocessor Definitions There you can add macros for your project in the build configuration you have chosen.

From your comments it seems that tproblem you're running into is getting a console window open and connected to stdout (having little to do with DEBUG vs. RELEASE builds).

See the MS Support Article INFO: Calling CRT Output Routines from a GUI Application for a working example of how to have a GUI program open a console and direct stdout to it:

#include <stdio.h>
#include <io.h>
#include <fcntl.h>

// ...

int hCrt;
FILE *hf;

AllocConsole();
hCrt = _open_osfhandle(
    (long) GetStdHandle(STD_OUTPUT_HANDLE),
    _O_TEXT
    );
hf = _fdopen( hCrt, "w" );
*stdout = *hf;
int i = setvbuf( stdout, NULL, _IONBF, 0 );
puts("hello world");

Actually, on further testing, your simpler technique of using freopen("CONOUT$","w",stdout); works too. For some reason in my initial tests it didn't seem to work. You may need to also have the setvbuf() call to avoid buffering problems.

For C# the constants DEBUG works fine, Just make sure that in the project properties it is enabled.

Go to project properties (by right clicking on your project in solution explorer), then select build option on right side of the window and check the define DEBUG constant checkbox.

Then you can use code like this.

#if DEBUG

// debug mode

#else

//release mode

#endif

This is for Visual studio 2019:

#ifdef _DEBUG
// do something in a debug build
#else
// do something in a release build
#endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM