Defining macros in Visual Studio - / D or #define?

Recently, when porting some STL code to VS2008, I wanted to disable the warnings generated by std::copy by defining a new flag _SCL_SECURE_NO_WARNINGS . You can do this in two ways:

  • Using the / D compiler, which can be specified in the project properties. You have to make sure that it is defined for both Release and Debug versions, which I often forget to do.
  • Having defined this macro style before including the appropriate STL headers or, for general coverage, in stdafx.h:

    #define _SCL_SECURE_NO_WARNINGS

Both of these methods work fine, but I wondered if there is any argument in favor of the fact that it supports each other?

+4
source share
6 answers

The / D option is usually used when you want to define it differently in different assemblies (so you can change it in the makefile)

If you always want it installed the same way, use #define.

+10
source

By placing them in a project file, you maintain a close relationship between specific platform warnings and the platform, which seems right to me.

If they are in code, they are always in code, regardless of whether it is suitable for the platform. You do not need this for GCC or, possibly, future versions of Visual C ++. On the other hand, having it in code, it is more obvious that it is there at all. If you move (copy) the code, it will be easier to remember the movement defining with it.

Pros and cons every way. YMMV.

+5
source

If you have a header that is included in all the rest (e.g. stdafx.h), you should put it there. The compiler command line switch is typically used for build options that are not always set, such as NDEBUG, UNICODE, etc. Although your macro should always be installed.

It may sound arbitrary. And indeed, some might say other things. In the end, however, you must decide what suits your situation.

+2
source

If you put them in your code, remember whether they find them correctly:

 #ifdef _MSC_VER #define _SCL_SECURE_NO_WARNINGS #endif 

This will keep your code portable.

+1
source

In general, I prefer to put #define in code rather than use the / D compiler for most things, because it seems more intuitive to look for #define than to check the compiler settings.

+1
source

/ D is not a valid flag for msbuild.exe (at least the version I'm using is v2.0.50727).

How it's done:

 /p:DefineConstants="MY_MACRO1;MY_MACRO2" 

The result of this:

 Target CoreCompile: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /define:MY_MACRO1;MY_MACRO2 ... 
+1
source

All Articles