好奇的探索者,理性的思考者,踏实的行动者。
Table of Contents:
防止头文件被重复引入
* 1) 使用宏定义避免重复引入
#ifndef _NAME_H
#define _NAME_H
//头文件内容
#endif
* 2) 使用#pragma once避免重复引入
目前,几乎所有常见的编译器都支持#pragma once
指令
* 3) 使用_Pragma操作符
C99 标准中新增加了一个和 #pragma
指令类似的 _Pragma("once")
,其可以看做是 #pragma
的增强版,不仅可以实现 #pragma
所有的功能,更重要的是,_Pragma
还能和宏搭配使用。
//student_li.h
#ifndef _STUDENT_LI_H
#define _STUDENT_LI_H
namespace Li { //小李的变量定义
class Student {
public:
void display();
};
}#endif
//student_li.cpp
#include "student_li.h"
#include <iostream>
void Li::Student::display() {
std::cout << "Li::display" << std::endl;
}
//student_han.h
#ifndef _STUDENT_HAN_H
#define _STUDENT_HAN_H
namespace Han { //小韩的变量定义
class Student {
public:
void display();
};
}#endif
//student_han.cpp
#include "student_han.h"
#include <iostream>
void Han::Student::display() {
std::cout << "han::display" << std::endl;
}
//main.cpp
#include <iostream>
#include "student_han.h"
#include "student_li.h"
int main() {
Li::Student stu1;
stu1.display();
Han::Student stu2;
stu2.display();return 0;
}
1) 将const常量定义在.h头文件中
//demo.h
#ifndef _DEMO_H
#define _DEMO_H
const int num = 10;
#endif
//main.cpp
#include <iostream>
#include"demo.h"
int main() {
std::cout << num << std::endl;
return 0;
}
2) 借助extern先声明再定义const常量
//demo.h
#ifndef _DEMO_H
#define _DEMO_H
extern const int num; //声明 const 常量
#endif
//demo.cpp
#include "demo.h" //一定要引入该头文件
const int num =10; //定义 .h 文件中声明的 num 常量
//main.cpp
#include <iostream>
#include "demo.h"
int main() {
std::cout << num << std::endl;
return 0;
}
3) 借助extern直接定义const常量
//demo.cpp
extern const int num =10;
//main.cpp
#include <iostream>
extern const int num;
int main() {
std::cout << num << std::endl;
return 0;
}