今天转载一篇《C程序采用模块化的编程思想》,那么全局变量,全局函数与防止头文件重复包含头文件#ifndef,#define,#endif怎么使用呢?
test.h
#ifndef TEST_H #define TEST_H extern int money; #endif
这里是对全局变量的声明,如果是定义一个新类,则放在#ifndef ... #define ... #endif 宏中,那么全局变量的声明呢?因为变量被声明多次也没有影响,所以放在宏外也没有影响,同样的其他的头文件,如果这些头文件中有#ifndef ... #define ... #endif 宏,则既可以放在宏内,也可以放在宏外。
test1.h
#include "test.h" #ifndef TEST1_H #define TEST1_H extern void print(); #endif
在这个头文件中,声明了一个全局函数。并且包含了test.h,所以在test1.cpp中就可以使用全局变量money了,不用调用extern(原因见c语言的模块化编程思想)。
test1.cpp
#include "test1.h" #include "test.h" #include <iostream> using namespace std; void print() { cout << money << endl; }
对全局函数进行定义
test.cpp
#include "test.h" #include "test1.h" #include <iostream> using namespace std; int money = 10; void main() { print(); }
定义全局变量,调用test1中的全局函数。
这个程序如果不用#ifndef ... #define ... #endif 宏,也没有错误,因为在头文件重复包含过程中,重复包含的是函数和变量声明没有影响。但是如果头文件中的是类的定义的话,则必须利用#ifndef ... #define ... #endif 宏,或者使用其他方法来使类不被重复定义。
总结:全局变量声明,全局函数声明,头文件不一定要放在#ifndef ... #define ... #endif 宏中,但类的定义必须放到#ifndef ... #define ... #endif 宏中。