Activate print messages on debug mode / Disable print statements on release mode in C++ linux
-
Hello!
I am looking for a best way to enable / disable the print messages in my application.
In my application, to help the debugging, I have std::cout's to print the messages.
In the release mode, I don't want to print them, as it is a overhead. However, I want to have them in debug mode.
What is the best way to handle this?
Suggestion much appreciated!
Thanks,
Kumara -
This sort of stuff is usually a job for preprocessor.
One way would be to simply wrap the prints in #ifdefs. This is a bit intrusive and makes code harder to read so a little wrapper could help here:#ifdef _DEBUG #define PRINTSTUFF(stuff) std::cout << (stuff); #else #define PRINTSTUFF(stuff) #endif //and then just: PRINTSTUFF("stuff")
This will expand to nothing in release mode so no overhead will be present.
-
This is excellent! Thank you!
To be clear, _DEBUG macro is defined by whom? Operating system? Is it available for all the operating systems?
Please help me out.
Thanks,
Kumara -
This was just an example and no ultimate solution. No, it has nothing to do with the OS. It's a compiler/toolchain specific thing. Some compilers (e.g. GCC) don't have a clear notion of a release/debug. They just have a bunch of flags like optimization and debug info generation to mix and match. In such cases it's just a toolchain preset of what a debug build means.
The above
_DEBUG
define is specific to MSVC. Other compilers useDEBUG
,NDEBUG
, other stuff or nothing at all. Unfortunately there's no standard that would define that. The only way to make sure is to define something yourself. For example if you're using qmake you could add something like this in the .pro file:debug { DEFINES += DEBUG_BUILD }
and then test for
DEBUG_BUILD
in the source code. -
Very clear explanation! Thank you again!
In case of qmake, it is pretty clear.
How about in case of a plain c++ code with a Makefile? Any suggestions please?
(I am loving the discussion. It is helping to understand lot. Thank you)
-
Hi,
You would create two different targets where you setup these flags then call e.g.
make release
-
Thanks Sam for Chris for great ideas.
I had put together made an test implementation.
I wrote a Makefile as
release: main.cpp g++ main.cpp -o booh debug: main.cpp g++ main.cpp -o booh -DDEBUG_ENABLE
Since release configuration at the top, that becomes default one. So, here in this case, release is by default.
And, when someone wants to enable debug messages, they would call "make debug", which defines a MACRO called DEBUG_ENABLE.
In the .cpp file,
#ifdef DEBUG_ENABLE #define PRINTDEBUG(debugString) std::cout << (debugString) << std::endl; #else #define PRINTDEBUG(debugString) #endif
So, based on configuration, Macro is either enabled or disabled.
Thanks!