test.h
#ifndef HEAD_H
#define HEAD_H
extern double pi;
#endif
test.cpp
#include"test.h"
double pi = 3.14;
int add(int x, int y)
{
return x + y;
}
main.cpp
#include<iostream>
#include<string>
#include"test.h"
using namespace std;
string str;
int iVal;
extern double pi;
extern int add(int, int);
int main()
{
const int iBufsize = 100;
string str("inter str");
string str2;
cout << "hello world." << endl;
cout << iVal << endl;
cout << str <<"|" << endl;
cout << str2 <<"|" << endl;
cout << "const int : " << iBufsize << endl;
cout << pi << endl;
cout << "-------------------" << endl;
int j = 100;
const int &ref1 = iBufsize;
const int &ref2 = j;
j = j + 1;
cout << ref1 << endl;
cout << ref2 << endl;
cout << add(ref1 , ref2) << endl;
return 0;
}
makefile
exe: main.o test.o
g++ main.o test.o -o exe
main.o: main.cpp test.h
g++ -c main.cpp
test.o: test.cpp test.h
g++ -c test.cpp
clean :
rm *.o exe
另外:当我们在头文件中定义了const变量后,每个包含该头文件的源文件都有自己的const变量,其名称和值是一样。但不是一个。因为const变量默认的作用域是定义它的文件,因此各个文件定义自己的const变量是合法的。
试了一下,如果在test.h中加入 const int iConst = 100 , 编译通过,运行通过
如果在test.h加入 int inonConst = 100; 编译报错: multiple definition of `inonConst'