一次使用#pragma有什么危险? [英] What are the dangers of using #pragma once?

查看:95
本文介绍了一次使用#pragma有什么危险?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现代的C和C ++编译器支持非标准的#pragma once预处理程序指令,该指令的作用类似于经典的标头防护:

Modern C and C++ compilers support the non-standard #pragma once, preprocessor directive, which serve a similar purpose to the classic header guards:

#ifndef hopefully_unique_identifier_that_doesnt_hurt_the_code
#define hopefully_unique_identifier_that_doesnt_hurt_the_code
  // some code here
#endif

我知道,经典方法的一个问题是,一旦包含标头,就必须#undef标头保护宏再次包含它(对我来说,这是一个主要的代码气味,但这不在这里. #pragma once方法也会出现相同的问题,但是不可能多次包含标头.

One problem, I'm aware of, with the classic approach is that once you've included a header, you have to #undef the header guard macro to include it again (doing so, to me, is a major code-smell, but that's beside the point here). The same problem arises with the #pragma once approach, but without the possibility of allowing the header to be included more than once.

经典方法的另一个问题是,您可能会意外地在不相关的地方定义了相同的宏,因此要么没有按预期方式包括标头,要么做了我无法想象的其他讨厌的事情.在实践中,通过遵循某些约定(例如将宏基于类似UUID的对象(即,随机字符串)或(基于较不理想的方法),并基于文件名在宏中进行定义),可以很容易地避免这种情况.

Another problem with the classic-approach is that you may, accidentally, define the same macro in unrelated places, thus either not including the header as expected or doing some other nasty stuff, that I can't imagine. This is reasonably easy to avoid in practice, by keeping to certain conventions such as basing the macros to UUID-like objects (i.e. random strings) or (the less optimal approach), basing them on the name of the file, they are defined in.

在现实生活中,我很少遇到这些潜在的问题,因此我并不认为它们是主要问题.

I have only rarely experienced any of these, potential problems, in real life, so I don't really consider them to be major problems.

我可以用#pragma once想到的唯一潜在的现实生活问题是,这不是标准的事情-您所依赖的东西可能在任何地方都不可用,即使它存在于实践中,也无处不在(*).

The only potential real life problem I can think of with #pragma once, is that it's not a standard thing -- you're relying on something that may not be available everywhere, even if it is present, in practice, everywhere (*).

那么,除了我已经提到的那些问题之外,#pragma once还存在哪些潜在问题?我是否真的有信心在实践中到处都可以使用它?

So, what potential problems exist with #pragma once, besides the ones I've already mentioned? Am I having too much faith in having it available, in practice, everywhere?

(*),只有少数人使用的一些次要编译器,被排除在外.

(*) Some minor compiler that only a handful of people use, excluded.

推荐答案

使用#pragma once遇到的一个问题是当包含位于多个位置的相同文件时.对于#pragma once,它被认为与众不同,而对于#ifndef/#define保护器则没有.

One problem I have encountered with using #pragma once was when including the same file that is located at multiple locations. With #pragma once it is deemed different, not with #ifndef/#define guard.

这篇关于一次使用#pragma有什么危险?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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