test.h
#ifndef TEST_H_
#define TEST_H
//常量声明和定义采取这种方法即可
const int a = 20; //不报错,因为const变量链接属性默认是内部链接,就算两个cpp文件都引用了该.h文件,也不会出现重复定义的错误。
//extern const int b = 20;//这个报错,因为加上extern之后链接属性就是外部链接了,当被多个.cpp文件包含时则会导致重定义。
extern const int b; //改成这个不报错,所以用extern只声明变量,而在test.cpp定义这个变量
#endif
test.cpp
#include "test.h"
const int b = 3;//定义b,如果只在test.h里用extern声明了,而没有定义,那么因为在main.cpp使用了变量b,就会出现链接错误
main.cpp
#include "test.h"
#include <iostream>
using namespace std;
int main()
{
cout << b << endl;
return 0;
}