对全局变量使用extern的正确方法是什么? [英] What is the correct way of using extern for global variables?
本文介绍了对全局变量使用extern的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
文件a.cc
int a = 0;
文件b.cc
#include "a.cc"
文件main.cc
#include "b.cc"
extern int a;
int main() {
}
g++ -c a.cc
g++ -c b.cc
g++ main.cc a.o b.o
error: multiple definitions of a
推荐答案
您包括 .cc
或 .cpp
)文件,这是错误的。不要那样做。您需要一个标题,并在其中放置 extern int a;
:
You include a .cc
(or .cpp
) files, which is wrong. Do not do that. You need a header, and in that put the extern int a;
:
// a.h
// include guards omitted
extern int a;
// a.cc
#include "a.h"
int a;
// b.cc
#include "a.h"
// main.cc
#include "a.h"
int main(){
// use a
}
这篇关于对全局变量使用extern的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文