views:

2009

answers:

6

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

  • Using the /D compiler switch, which can be specified in the project properties. You need to ensure it is defined for both Release and Debug builds, which I often forget to do.
  • By defining it macro style before you include the relevant STL headers, or, for total coverage, in stdafx.h:

    #define _SCL_SECURE_NO_WARNINGS

Both of these methods work fine but I wondered if there was any argument for favouring one over the other?

+2  A: 

If you have a header that is included in all others (like that stdafx.h), you should put that there. The compiler command line switch is used usually for build options, that are not always set, like NDEBUG, UNICODE and such things. While your macro would essential always be set.

That might sound arbitrary. And indeed, some might say other things. At the end, though, you have to decide what fits your situation.

Johannes Schaub - litb
+5  A: 

The /D option is generally used when you want to define it differently on different builds (so it can be changed in the makefile)

If you will "always" want it set the same way, use #define.

James Curran
+3  A: 

By putting them in your project file you maintain a close association between the platform specific warnings and the platform, which seems correct to me.

If they're in the code, they're always in the code whether or not it's appropriate for the platform. You don't need it for GCC or possibly future versions of Visual C++. On the other hand, by having it in the code, it's more obvious that it's there at all. If you move (copy) the code, it'll be easier to remember to move that define with it.

Pros and Cons each way. YMMV.

luke
+1  A: 

If you do put them in your code, remember to ifdef them properly:

#ifdef _MSC_VER
#define _SCL_SECURE_NO_WARNINGS
#endif

This will keep your code portable.

JesperE
Defining a symbol usually doesn't hurt when moved to a different platform, even if it doesn't do anything. A simple comment would be just as effective.
Mark Ransom
In this case, definitely no, but in the general case I think it is prudent to have compiler-specific defines inside proper ifdef/endif pairs.
JesperE
+1  A: 

In general I prefer putting #define's in the code as opposed to using the /D compiler switch for most things because it seems to be more intuitive to look for a #define than to check compiler settings.

John Dibling
A: 

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

The way this is done is:

/p:DefineConstants="MY_MACRO1;MY_MACRO2"

The result of doing this is:

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