extern修饰全局变量正确用法和链接错误的解决方法
首先:extern声明的全局变量的作用范围是整个工程,我们通常在“.h”文件中声明extern变量之后,在其他的“.c”或者“.cpp”中都可以使用。extern扩大了全局变量的作用域范围,拓展到整个工程文件中。
我们注意的问题是如何使用extern修饰全局变量,可能在使用过程中出现了这样那样的问题,尤其是链接问题。
推荐的用法:
1.h文件中
extern int e_i;//全局变量的声明1.cpp或者1.c文件中
#include "1.h"
int e_i = 0;//全局变量的定义我们注意到,在声明extern变量之后一定要对变量进行定义,并且定义的作用域要相同。
例如,在自定义类的头文件StaticCounter.h
#pragma once
#include "stdio.h"
extern int e_i;
class StaticCounter
{
StaticCounter();
~StaticCounter();
}如果在class StaticCounter的构造函数中去定义int e_i=0;那么编译之后会有链接错误,这是因为作用域不同引起的,需要在class StaticCounter实现的cpp文件中的全局区域定义int e_i=0;
#include "stdafx.h"
#include "StaticCounter.h"
int e_i = 0;
StaticCounter::StaticCounter()
{
//int e_i = 0;链接错误
}
StaticCounter::~StaticCounter()
{
}不推荐的写法:
直接在1.h文件中
extern int e_i = 1;//声明定义放在一起这种写法,在gcc编译时会给出一个警告:warning: ‘e_i’ initialized and declared ‘extern’
在VS 2013中编译测试无法通过。
页:
[1]