How to enable a piece of code with a macro by change to debug or release

Jul 5, 2021 at 12:04pm
Hello guys I have a short question, that I need to understand. I just want to enable a piece of code in the entire project that works only in debugging mode. so I want like a macro let's say:

1
2
3
#if DEVELOPMENT
     // code here..
#endif // DEVELOPMENT 


so that code will only be active on Debugging.
So.. where do I have to define #DEVELOPMENT 1 to work with the compiler when I change it to Debug and #DEVELOPMENT 0 when I change to Release mode ?
.. Thank you.
Jul 5, 2021 at 12:21pm
Well for MSVS, there is the pre-defined macro _DEBUG which is defined as 1 when the /LDd, /MDd, or /MTd compiler option is set. Otherwise it's undefined.

See https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=msvc-160

So you can say:

1
2
3
#ifdef _DEBUG
    // code for debug mode goes here
#endif 

Jul 5, 2021 at 12:21pm
I use as IDE Code Blocks if this matter.. (forgot to specify).
Jul 5, 2021 at 12:25pm
Hello mif,

In this case what I usually do is:
1
2
3
4
5
6
7
8
9
#define DEBUG
// Other #includes

int main()
{
#ifdef DEBUG
    // Code here
#endif
}

Then you can put a comment on the "#define" line and uncomment when you need it.

Andy
Jul 5, 2021 at 12:52pm
Ahh.. okay .. That's only for MSVS..
Thank's Andy I work in that way .. but I saw ppl. doing that I didn't realize is only a MSVS pre-defined macro.
So last think .. can someone add a defined macro such as seeplus said. manually ?
Or I have to resign and use as I did before.. and Andy said.
Jul 5, 2021 at 1:03pm
Hello Mif,

Just write it as #define _DEBUG 1 .

If you find your-self using this or others put them in a header file and include the header file.

It should not matter where it is defined just that it is defined and the header file would be included in the source code before any of the macros would be used.

Andy

Edit:
Last edited on Jul 5, 2021 at 1:10pm
Jul 5, 2021 at 1:08pm
Ahh Okay.. thanks Andy..
Jul 5, 2021 at 1:29pm
I think I found something about it when selecting from compiler debug or release mode which is this:
1
2
3
4
5
#ifdef DEBUG_PROCESS
#define DEVELOPMENT 1
#else
#define DEVELOPMENT 0
#endif // DEBUG_PROCESS 


I think this will set the DEVELOPMENT 1 when debugging or else false.
Jul 5, 2021 at 1:35pm
You can define the macro on the command line. For g++:
g++ -DDEBUG=1 -o myfile myfile.cpp


Depending on your build environment, there should be a way to define it when doing a development build and leave it out when doing a production build.

The advantage of defining it on the command line is that you don't have to worry about forgetting to define it in some file, or defining it in one file and leaving it out in another.
Jul 5, 2021 at 1:54pm
Ahh okay.. perfect. I set that in the command line arguments.. and it's working nice.. :)

Thanks dhayden.. and thank you all.. for your time.
Topic archived. No new replies allowed.