在1.7节中,提前定义和声明。我们提到一个标识符只能定义一次。因此一个标识符定义两次就会上报编译错误。
int main()
{
int x; // this is a definition for identifier x
int x; // compile error: duplicate definition
return 0;
}
类似的,一个程序中的函数如果定义两次也会上报错误。
#include <iostream>
int foo()
{
return 5;
}
int foo() // compile error: duplicate definition
{
return 5;
}
int main()
{
std::cout << foo();
return 0;
}
虽然这些程序很容易修复(删掉重复的定义即可),当有头文件的时候,非常容易出现一个头文件被多次引用的情况出现问题。看下面的例子:
math.h
int getSquareSides()
{
return 4;
}
geometry.h
#include "math.h"
main.cpp
#include "math.h"
#include "geometry.h"
int main()
{
return 0;
}
表面上看起来程序编译会报错,根本原因是math.h中有一个定义,而我们在main.cpp中引用了两次math.h。下面是真正发生的情况:首先,#include “math.h” 会把getSquareSides复制到文件中一次。