終于弄清楚了原來(lái)說(shuō)的同一個(gè)頭文件不能被兩次或兩次以上包含是針對(duì)同一個(gè)源文件而言的。借用80后的流行語(yǔ),真是漢哪!
原貼地址:
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.