链接和作用域2
header.h
#pragma once
#ifndef HEADER_H
#define HEADER_H
unsigned long returnFactorial(unsigned short num);
unsigned short headerNum = 5;
#endif
that.cpp
#include "header.h"
unsigned short thatNum = 8;
bool printMe = true;
unsigned long returnFactorial(unsigned short num)
{
unsigned long sum = 1;
for (int i = 1; i <= num; i++)
{
sum *= i;
}
if (printMe)
{
return sum;
}
else
{
return 0;
}
}
this.cpp
#include "header.h"
#include <iostream>
extern unsigned short thatNum;
static bool printMe = false;
int main()
{
unsigned short thisNum = 10;
std::cout << thisNum << "! is equal to " << returnFactorial(thisNum) << std::endl;
std::cout << thatNum << "! is equal to " << returnFactorial(thatNum) << std::endl;
std::cout << headerNum << "! is equal to " << returnFactorial(headerNum) << std::endl;
if (printMe)
{
std::cout << "小甲鱼真帅" << std::endl;
}
return 0;
}
这里编译后就会提示
说headerNum这个已经在that.cpp里面定义过了,可是明明已经在头文件里面写上那个防止编译的了,还是会这样,所以就是说在头文件里面尽量不要对变量赋值,只要声明就行了。如果一定要赋值的话,就写成static类型。如下:
header.h
#pragma once
#ifndef HEADER_H
#define HEADER_H
unsigned long returnFactorial(unsigned short num);
static const unsigned short headerNum = 5;
#endif
输出结果
ok,完美