c++ extern 示例

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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值