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

故事扮演 提交于 2019-12-18 07:05:10

问题


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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.




回答5:


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.




回答6:


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


来源:https://stackoverflow.com/questions/1326656/is-there-a-way-to-automatically-have-a-define-reproduced-in-each-source-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!