<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

统计

  • 随笔 - 24
  • 文章 - 0
  • 评论 - 17
  • 引用 - 0

常用链接

留言簿(4)

随笔分类

随笔档案

相册

搜索

  •  

最新评论

阅读排行榜

评论排行榜

有关include guard的一个好帖子(收藏)
终于弄清楚了原来说的同一个头文件不能被两次或两次以上包含是针对同一个源文件而言的。借用80后的流行语,真是汉哪!

原贴地址:http://www.keil.com/forum/docs/thread10237.asp

作者 Per Westermark

The

#ifndef xx
#define xx
...
#endif

method is to make sure that a header file isn't included more than once from the same c file.

You can not - and normally don't want to - stop multiple c files from including the same header file.

A header file is included because:
1) You have specifically added a line #include "xx" or #include <xx> in the source file. Don't do that unless you want the file to be included :)
2) You are including one header file, that it it's turn (one or more steps away) includes another header file. But a header file should only contain a recursive #include if it really needs that other file for some declarations. Hence, you need to include it.

What does this mean?

If the header file must be seen by multiple source files, you can't use it to allocate global variables, since the linker would then complain about multiple sets of global variables with the same name. This can be solved with the following:

//globals.h
#ifndef _GLOBALS_H
#define _GLOBALS_H
#if defined MAIN
#define EXTERN
#else
#define EXTERN extern
#endif
...
EXTERN int my_global_variable;
#endif // _GLOBALS_H

// main.c
#define MAIN
#include "globals.h"
...
// misc.c
#include "globals.h"
...

In this case, only the inclusion in main.c will result in an "allocation" of global variables, because the #define EXTERN will be empty. All other source files that includes "globals.h" will just see the type information for the global variables.

posted on 2009-02-19 09:04 小葱蘸酱 阅读(957) 评论(2)  编辑 收藏 引用

评论

# re: 有关include guard的一个好帖子(收藏) 2009-02-19 21:19 陈梓瀚(vczh)

EXTERN的时候,如果刚好main没有引用它,那就链接错误了- -#
  回复  更多评论    

# re: 有关include guard的一个好帖子(收藏)[未登录] 2009-02-20 16:15 小葱蘸酱

@陈梓瀚(vczh)
欢迎评论!
只要在include "globals.h"前定义了MAIN,就不会联接错误,跟引用有什么关系呢?
  回复  更多评论    

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理