最近看C++ primer
关于#ifndef防止头文件的重复处理有这么一句话,"只要不存在两个必须包含的头文件要检查一个同名的预处理器常量这样的情形这个策略就能够很好地运作 ",比较不理解,特列两个例子.
/**/
/* test1.h */
#ifndef TEST1_H
#define TEST1_H
#include < iostream >
using namespace std;
#define DEBUG 6
#endif
/**/ /* test2.h */
#ifndef TEST2_H
#define TEST2_H
#include < iostream >
using namespace std;
#define DEBUG 7
#endif
/**/ /* test.cpp */
#include < iostream >
using namespace std;
#include " test1.h "
#include " test2.h "
int main()
... {
cout<<DEBUG;
return 1;
}
#ifndef TEST1_H
#define TEST1_H
#include < iostream >
using namespace std;
#define DEBUG 6
#endif
/**/ /* test2.h */
#ifndef TEST2_H
#define TEST2_H
#include < iostream >
using namespace std;
#define DEBUG 7
#endif
/**/ /* test.cpp */
#include < iostream >
using namespace std;
#include " test1.h "
#include " test2.h "
int main()
... {
cout<<DEBUG;
return 1;
}
此时结果为 6,test2.h并未执行.
另外一个例子:
/**/
/* test1.h */
#ifndef TEST1_H
#define TEST1_H
#include < iostream >
using namespace std;
#define DEBUG1 1
#endif
/**/ /* test2.h */
#ifndef TEST1_H
#define TEST2_H
#include < iostream >
using namespace std;
#define DEBUG2 2
#endif
/**/ /* test.cpp */
#include < iostream >
using namespace std;
#include " test1.h "
#include " test2.h "
int main()
... {
cout<<DEBUG1<<endl;
cout<<DEBUG2<<endl;
}
#ifndef TEST1_H
#define TEST1_H
#include < iostream >
using namespace std;
#define DEBUG1 1
#endif
/**/ /* test2.h */
#ifndef TEST1_H
#define TEST2_H
#include < iostream >
using namespace std;
#define DEBUG2 2
#endif
/**/ /* test.cpp */
#include < iostream >
using namespace std;
#include " test1.h "
#include " test2.h "
int main()
... {
cout<<DEBUG1<<endl;
cout<<DEBUG2<<endl;
}
此时就有了问题,编译时会有问题:
error C2065: 'DEBUG2' : undeclared identifier.
个人觉得上面两个例子应该和此命题相关.