简体   繁体   English

C ++预处理程序定义

[英]C++ Preprocessor definitions

could anyone define what is a STRAY DEFINITION? 谁能定义什么是杂散定义? .the second questionis: I'm reading "Teach yourself c++ in 21 days" in the book he said we should not define the term DEBUG. 第二个问题是:我读的是他的书中的“ 21天自学c ++”,他说我们不应该定义DEBUG一词。 I want to know why? 我想知道为什么吗?

First part of the question: 问题的第一部分:

A stray definition is a preprocessor definition that changes the behavior of some other code (or the actual code), which most likely won't be intentional. 杂散定义是一个预处理器定义,它可以更改某些其他代码(或实际代码)的行为,这很可能不是故意的。 For example, you could write a header file and use the following line: 例如,您可以编写一个头文件并使用以下行:

#define main is_awesome

This won't have any direct impact in your header file, possibly not even in your code, but someone else including this header file in a file containing the function int main(int argc, char **argv) will run into problems, because this stray definition will change that function's name into int is_awesome(int argc, char **argv) and suddenly there is no longer a main entry point for the application! 这不会对您的头文件产生任何直接影响,甚至可能对您的代码也没有任何直接影响,但是包含此头文件的其他人在包含int main(int argc, char **argv)函数的文件中会遇到问题,因为这个错误的定义会将函数的名称更改为int is_awesome(int argc, char **argv) ,突然之间,该应用程序不再是main入口点!

In a similar way the macro DEBUG can cause such problems. 以类似的方式,宏DEBUG可能会导致此类问题。 Typically, DEBUG should only be defined by the compiler itself, based on whether it's building debug code or not (based on your compiler you might have to set it yourself as well). 通常, DEBUG仅应由编译器本身定义,这取决于它是否在构建调试代码(根据您的编译器,您可能还必须自行设置它)。 If you're defining DEBUG somewhere on your own, you might trigger debug code even though you're actually creating a release build. 如果您要在某个地方定义DEBUG ,则即使您实际上是在创建发行版,也可能触发调试代码。

In general, such bugs or issues can be really hard to track down, especially if you don't know how to have a look at the preprocessed code (you can't see the problems/errors in your base code and most likely line numbers reported will be off as well). 通常,很难发现此类错误或问题,特别是如果您不知道如何查看预处理的代码(您看不到基本代码和最可能的行号中的问题/错误)时,尤其如此。报告也将关闭)。


How to avoid this? 如何避免这种情况? Three simple rules that will make your life and that of others a lot easier: 三个简单的规则将使您和他人的生活更加轻松:

  • Only use preprocessor definitions when you really have to (eg to control code inclusion at compile time). 仅在确实需要时才使用预处理程序定义(例如,在编译时控制代码包含)。
  • Always clean up ( #undef ) preprocessor definition you don't need outside your header file. 始终清理头文件之外不需要的预处理器定义( #undef )。
  • If you have to use some global preprocessor definition, make it's name unique, eg by prepending your library or project name. 如果您必须使用某些全局预处理器定义,请使其名称唯一,例如,在您的库或项目名称之前添加。 Eg rather than defining DEBUG you could use MYLIB_DEBUG . 例如,您可以使用MYLIB_DEBUG而不是定义DEBUG

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM