I'd like the following to appear in every source file in my Visual C++ 2005 solution:
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
Is there a way of doing this without manually copying it in? Compiler option?
The command line option /D
can be used to define preprocessor symbols. I don't know, though, whether it can also be used to define macros with arguments, but it should be an easy matter to test that.
Edit: Failing that, the /FI
option ("force include") should allow you to do what you want. Quoting the MSDN documentation:
This option has the same effect as specifying the file with double quotation marks in an #include directive on the first line of every source file [...] .
You can then put your #define
s in that forced include file.
I'd advise against using this #define
. Re-defining new
is not portable and if you do it in this way then you prevent anything subsequently using a placement new
from working. If you 'force' this #define
before a file's manually #include
s take effect then you risk incompatibilities between library header files and their source files and you will get 'surprise' errors in library files that use placement new
(frequently template/container classes).
If you are going to redefine new
, then make it explicit and leave it in the source.
You could insert that #define
into stdafx.h or common.h or any other header file that gets included into each source file.
Compiler option?
Yes, you can customize a list of define
s in the project properties (either under “Preprocessor” or “Advanced,” as far as I remember). These define
s will be present in each source file.
You could put the #define
s into an h
file, but without putting the #ifndef
guard in the h
file. Then #include
the file in each of your source files.
I am not endorsing redefining new
, BTW.
You can just define your own global new operator somewhere in your code and compile it conditionally. Do not forget to include all 4 variations of new( plain and array one with and without nothrow) and two variations of delete(plain and array one). There is a whole chapter on the matter in my copy of Effective C++, Third Edition (Chapter 8)
#ifdef MYDEBUG
void* operator new(std::size_t size) { <your code here> }
void operator delete(void* p) { <your code here> }
#endif