简体   繁体   English

使用#ifndef 时具体定义的是什么

[英]What is it specifically that is being defined when using #ifndef

What is "ICT_TOOLS_H__"?什么是“ICT_TOOLS_H__”? Is it a header that I'm defining here, or is it a boolean, or an int of 1 or 0?它是我在这里定义的标头,还是一个布尔值,或者一个 1 或 0 的整数? Does the name have to be the same as the header file, or can it be a custom name?名称是否必须与头文件相同,或者可以是自定义名称? Also, do I use #ifndef if the header is included in multiple .cpp files, or should I use it even if it's only #included once?另外,如果标头包含在多个 .cpp 文件中,我是否使用 #ifndef,或者即使它只包含一次也应该使用它? When the compiler goes through the first time, does "ICT_TOOLS_H__" get defined and on every other pass through it doesn't recompile the header, preventing multiple compilations of the same header?当编译器第一次通过时,是否定义了“ICT_TOOLS_H__”,并且每次通过它时都不会重新编译头文件,从而防止对同一头文件进行多次编译?

#ifndef ICT_TOOLS_H__ //my proff said to start the name with "ICT_", its the programming department
#define ICT_TOOLS_H__


//implementation goes here

#endif

no it is a macro used for inclusion guard conditional inclusion so at first always this macro is not defined so the condition succeeds and the content is added to the source/header (where included) and in the second time the condition will fail so the content won't be added again.不,它是一个用于inclusion guard条件包含的宏,因此首先始终未定义此宏,因此条件成功并将内容添加到源/标题(包含时),第二次条件将失败,因此内容不会再添加了。

this is useful when having multiple source/header files where you can include a header twice or more.这在有多个源/头文件时很有用,您可以在其中包含两次或更多次的头文件。

//header.h

#ifndef MY_HEADER_H // the name can be anything 
#define MY_HEADER_H
// code here (some declarations)

int value;

#endif

//source.cpp

#include "header.h"
#include "header.h"

int main()
{
     value = 0; // for example

     return 0;
}

if you remove the inclusion guard then the content of header.h will be added twice so as a result two variables value are there and that is a compile-time-error (redefinition).如果删除包含保护,则header.h的内容将被添加两次,因此存在两个变量value ,这是一个编译时错误(重新定义)。

They are basically macros and are used for conditional compilation.它们基本上是宏,用于条件编译。 This is how they work the compile first checks if there is a defined macro called in your case ICT_TOOLS_H__ if it is not defined then the entire code between #ifndef and #endif will compile and as the next line indicates it will define that macro and will be a guard not to compile it again.这就是他们的工作方式,编译首先检查是否有在您的情况下调用的已定义宏 ICT_TOOLS_H__ 如果未定义,则 #ifndef 和 #endif 之间的整个代码将编译,下一行表示它将定义该宏并将小心不要再次编译它。

If a code compiles more than one time the c++ one definition rule is violated.如果代码编译不止一次,则违反了 c++ one 定义规则。 See here https://en.m.wikipedia.org/wiki/One_Definition_Rule .请参阅此处https://en.m.wikipedia.org/wiki/One_Definition_Rule

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

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