C ++如何正确初始化全局变量? [英] C++ How to properly initialize global variables?

查看:90
本文介绍了C ++如何正确初始化全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个小的学生项目,并且遇到了一些全局变量并且需要在一些源文件中使用的问题,但是我遇到了错误*未定义对variable_name *的引用.让我们创建三个源文件,例如:

I'm writing little student project and stuck with the problem that I have a few global variables and need to use it in a few source files, but I get the error *undefined reference to variable_name*. Let's create three source files for example:

tst1.h:

extern int global_a;
void Init();

tst1.cpp:

#include "tst1.h"
void Init(){
  global_a = 1;
}

tst2.cpp:

#include "tst1.h"
int main(){
  Init();
}

当我进行编译和链接时,这就是我得到的:

When I compile and link, that's what I get:

$ g++ -c tst1.cpp 
$ g++ -c tst2.cpp 
$ g++ tst2.o tst1.o
tst1.o: In function `Init()':
tst1.cpp:(.text+0x6): undefined reference to `global_a'
collect2: error: ld returned 1 exit status

如果我删除了 extern 语句,那么我遇到了另一个问题,请允许我显示:

If I remove the extern statement, then I get the other problem, let me show:

$ g++ -c tst1.cpp 
$ g++ -c tst2.cpp 
$ g++ tst2.o tst1.o
tst1.o:(.bss+0x0): multiple definition of `global_a'
tst2.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

但是我确实确实需要一些全局变量,例如我的小项目使用汇编代码,并且具有像 string rax =%rax%eax%ax%ah%al"之类的变量.应该通过不同的源文件引用.

But I really need some variables to be global, for example my little project works with assembly code, and have a variables like string rax = "%rax %eax %ax %ah %al"; which should be referenced through different source files.

那么,如何正确初始化全局变量?

So, how to properly initialize the global variables?

推荐答案

您仅声明了变量,但未定义变量.该记录

You only declared the variable but not defined it. This record

extern int global_a;

是声明而不是定义.要定义它,您可以在任何模块中编写

is a declaration not a definition. To define it you could in any module to write

int global_a;

或者最好通过以下方式定义函数init

Or it would be better to define function init the following way

int Init { /* some code */; return 1; }

并且在main函数之前的主模块中写入

and in main module before function main to write

int global_a = Init();

这篇关于C ++如何正确初始化全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆