C ++ Header Guard语法和标题位置 [英] C++ Header Guard Syntax and Header Placement

查看:126
本文介绍了C ++ Header Guard语法和标题位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是标题防护的正确语法和用法.例如,如果我在C ++代码中包含一些通用库,那么我可以像下面所示的那样制作标题保护程序吗?另外,从我可以在头文件中找到的文档中,建议将头防护放置在头文件中.我正在使用Microsoft Visual Studio.我可以仅将标题保护程序和#include文件放置在主源文件中吗?还是这是不好的做法?我知道您可以使用#pragma充当标头保护.但是,这不是受支持的标准,因此我试图避免使用它.

My question is on proper syntax and usage of header guards. For example if I am including a few common libraries in my C++ code can I make a header guard like what is shown below? Also, from the documentation I could find on header files it was suggested to put your header guard in a header file. I am using Microsoft Visual Studio. Can I just place my header guard and #include files in my main source file? Or is this a bad practice? I know you can use #pragma to function as a header guard. However, this is not a supported standard so I am trying to avoid using it.

#ifndef HEADER_GUARD
#define HEADER_GUARD
#include <iostream> 
#include <fstream>  
#include <string>
#include <iomanip>
#endif

任何帮助将不胜感激!

推荐答案

您不应在源代码(.cpp)文件中编写标题保护.

You should not write the header guard in source code (.cpp) file.

我们也应避免使用双头保护器使用double在C ++中包括警卫队

We should avoid the double header guard as well The use of double include guards in C++

标头保护程序是为了避免在代码编译期间多次包含标头文件.

Header guard is to avoid multiple time inclusion of header file during compilation of code.

此外,在添加#include文件时,请记住,我们不应在此处添加不需要的文件.例如考虑源文件是否要求 #include< iostream> 但您将其包含在头文件中的情况,则应避免这种情况.此类情况 #include< iostream> 仅在源文件中.

Also, while adding the #include file, keep in mind that we should not add the unwanted files there. e.g. Consider case if source file requires to #include <iostream> but you included in header file then this should be avoided. Such case #include <iostream> in source file only.

#pragma一旦,但这不是语言标准,它不能保证何时从远程位置和不同的磁盘引用文件.

#pragma once is supported by many compilers but it's not language standard and it do not guarantee when file are referenced from remote location and different disks.

这篇关于C ++ Header Guard语法和标题位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆