g++中使用pragma once,被告知废弃了(obsolete)了。

james_razor 2003-03-19 05:33:22
有什么方法防止头文件被反复引用?
除了
#if !defined()
#define
#endif
的方法?
...全文
1552 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
james_razor 2003-03-20
  • 打赏
  • 举报
回复
可是使用#if !defined()的方式,必须要定义一个从未定义过的标识,vc6中采用类名加上一个128位随机数的方式,太麻烦了。
TopCat 2003-03-20
  • 打赏
  • 举报
回复
呵呵,那是VC的“古怪”做法,一般做法是利用文件名自身就可以了。
比如你的文件是myheader.h
那么,就#ifndef MYHEADER_H

这样在绝大多数情况下是够用的,毕竟文件名不能重复。
如果你的文件跨目录并且同名(不过按照一般的做法,这种做法并不推荐),那自己找一个解决方法应该也不难。
zhouzhaohan 2003-03-19
  • 打赏
  • 举报
回复
GNU CPP supports two more ways of indicating that a header file should be read only once. Neither one is as portable as a wrapper `#ifndef', and we recommend you do not use them in new programs.

In the Objective-C language, there is a variant of `#include' called `#import' which includes a file, but does so at most once. If you use `#import' instead of `#include', then you don't need the conditionals inside the header file to prevent multiple inclusion of the contents. GCC permits the use of `#import' in C and C++ as well as Objective-C. However, it is not in standard C or C++ and should therefore not be used by portable programs.

`#import' is not a well designed feature. It requires the users of a header file to know that it should only be included once. It is much better for the header file's implementor to write the file so that users don't need to know this. Using a wrapper `#ifndef' accomplishes this goal.

In the present implementation, a single use of `#import' will prevent the file from ever being read again, by either `#import' or `#include'. You should not rely on this; do not use both `#import' and `#include' to refer to the same header file.

Another way to prevent a header file from being included more than once is with the `#pragma once' directive. If `#pragma once' is seen when scanning a header file, that file will never be read again, no matter what.

`#pragma once' does not have the problems that `#import' does, but it is not recognized by all preprocessors, so you cannot rely on it in a portable program.

TopCat 2003-03-19
  • 打赏
  • 举报
回复
#pragma是编译器相关的,当然不推荐使用了,在没有“正统C++”的方法出台前,我认为

#ifndef 还是最正规的解决之道。
wwlxmai 2003-03-19
  • 打赏
  • 举报
回复
why?
james_razor 2003-03-19
  • 打赏
  • 举报
回复
2 jonnyyu
why what?
jonnyyu 2003-03-19
  • 打赏
  • 举报
回复
问一下,why?
james_razor 2003-03-19
  • 打赏
  • 举报
回复
哦?
你不觉得这样太烦了吗?
我对比vc6和.net生成的代码,vc6是用#if !define……
.net是用#pragma once,还以为#pragma once有优势呢
能告诉我为什么废弃#pragma once吗?
zhouzhaohan 2003-03-19
  • 打赏
  • 举报
回复
地球人都用你说的方法,为什么还要用别的呢?
#pragma once 是已经过时了
james_razor 2003-03-19
  • 打赏
  • 举报
回复
帖子掉的太快了,推一下

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧