验证步骤
head_file1.h的内容如下:
#ifndef _HEAD_FILE1_H
#define _HEAD_FILE1_H
#define MAX 100
#endif/*** _HEAD_FILE1_H*/
head_file2.h的内容如下:
#ifndef _HEAD_FILE2_H
#define _HEAD_FILE2_H
#define MAX 200
#endif/*** _HEAD_FILE2_H*/
test_headfile.cpp的内容如下:
#include<iostream>
#include"head_file1.h"
#include"head_file2.h"
using namespace std;
int main()
{
cout<<"Max is "<< MAX <<".\n"<<endl;
return 0;
}
编译test_headfile.cpp:g++ -o test_headfile test_headfile.cpp
运行test_headfile结果如下:
Max is 200.
结论
.cpp文件包含的多个头文件中有相同的定义时,以包含的最后一个头文件为准。
在C++中,由于头文件head_file1.h和head_file2.h分别定义了MAX宏,导致在test_headfile.cpp中出现重复定义。通过预处理器避免此问题,编译并运行显示MAX为200。
2551

被折叠的 条评论
为什么被折叠?



