Steven Keith
Steven Keith

Reputation: 1799

Is there a way to automatically have a #define reproduced in each source file

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?

Upvotes: 3

Views: 1543

Answers (6)

uuu777
uuu777

Reputation: 901

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

Upvotes: 2

JXG
JXG

Reputation: 7403

You could put the #defines 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.

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 791869

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 #includes 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.

Upvotes: 5

Martin B
Martin B

Reputation: 24140

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 #defines in that forced include file.

Upvotes: 5

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

Compiler option?

Yes, you can customize a list of defines in the project properties (either under “Preprocessor” or “Advanced,” as far as I remember). These defines will be present in each source file.

Upvotes: 1

sharptooth
sharptooth

Reputation: 170499

You could insert that #define into stdafx.h or common.h or any other header file that gets included into each source file.

Upvotes: 2

Related Questions