多文件编译 extern static 普通全局变量

一、extern

函数的extern是默认设置

主要针对variable

 

extern int a;仅做声明不做定义 解决了在.h文件中定义全局变量导致的重定义问题

/*test.h*/
extern int a;

/*a.cpp*/
#include "test.h"
int a = 2;


/*b.cpp*/
#include <iostream>
#include "test.h"
using namespace std;

int main()
{
    cout<<a<<endl;
    return 0;
}


/*makefile*/
main: a.cpp b.cpp
	g++ a.cpp b.cpp -o main

./main 输出2 //注意 main函数只能定义一次

 

二、static

static int a; 同时完成declaration和definition

在不同的文件中引用,空间是重新分配的,这也就解决了重定义的问题

/*test.h*/
static int a = 2;
void fun();

/*a.cpp*/
#include "test.h"
#include <iostream>
using namespace std;

void fun()
{
    a = 3;
    cout<<a<<endl;
}




/*b.cpp*/
#include <iostream>
#include "test.h"
using namespace std;

int main()
{
    fun();
    cout<<a<<endl;
    return 0;
}

输出

3

2

Tips:

全局变量不能在函数外赋值

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值