extern在c ++中的用法 [英] The usage of extern in c++

查看:251
本文介绍了extern在c ++中的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解'extern'是如何工作的。
我搜索了谷歌,但似乎没有特殊的例子我尝试

I've having difficulty understanding how 'extern' works. I've searched Google but there doesn't seem to be the particular example case I'm trying

如果我有一个文件main.cpp引用one.h
,在它里面有一个名为LIST1的列表(这是一个100×100的双数组)
所以我有双列表List1 [100] [100];

If i have a file main.cpp which references one.h and in it i have a list named LIST1 (which is a double array of 100 x 100) so I have double List1[100][100];

如何在one.cpp中使用此列表?

how can i use this list in one.cpp please?

extern double LIST1[100][100]

不工作:/

main.cpp:

#include "one.h"

extern double LIST1[100][100];

one.cpp:

void one::useList()
{
for(j = 0; j < 100; j++)
   {
     for(i = 0; i < 100; i++)
    {
         LIST1[j,i] = 0.5;
    }
 }
}

我得到的错误:


1> main.obj:error LNK2001:未解析的外部符号double(*
LIST1)[100](?LIST1 @@ 3PAY0GE @ NA)

1>main.obj : error LNK2001: unresolved external symbol "double (* LIST1)[100]" (?LIST1@@3PAY0GE@NA)


推荐答案

在命名空间范围的变量声明总是一个定义,除非你把 extern 那么它只是一个声明。

A variable declaration at namespace scope is always a definition unless you put extern on it; then it's just a declaration.

C ++中的一个重要规则是,不能有多个具有相同名称的对象的定义。如果你的头文件只包含 double LIST1 [100] [100]; ,这将工作,只要你只有一个翻译单元。但是,一旦您在多个翻译单元中包含头文件,您就有多个定义 LIST1 。你已经违反了规则!

An important rule in C++ is that you can't have multiple definitions of objects with the same name. If your header file just contained double LIST1[100][100];, this would work as long as you only ever included it in one translation unit. But as soon as you include the header file in multiple translation units, you have multiple definitions of LIST1. You've broken the rule!

因此,要从多个翻译单元访问全局变量,您需要确保头文件中只有一个声明。我们这样做 extern

So to have a global variable accessible from multiple translation units, you need to make sure there is only a declaration in the header file. We do this with extern:

extern double LIST1[100][100];

但是,您不能仅仅包含头部并尝试使用此对象,因为没有定义然而。这个 LIST1 声明只是说这个类型的数组存在于某个地方,但是我们实际上需要定义它来创建对象。因此,在单个翻译单元(通常是您的 .cpp 文件之一)中,您需要输入:

However, you cannot just include the header and try to use this object because there isn't a definition yet. This LIST1 declaration just says that an array of this type exists somewhere, but we actually need to define it to create the object. So in a single translation unit (one of your .cpp files usually), you will need to put:

double LIST1[100][100];

现在,您的 .cpp 文件可以包括头文件,只有得到声明。在你的程序中有多个声明是完全正确的。您的 .cpp 文件中只有一个将具有此定义。

Now, each of your .cpp files can include the header file and only ever get the declaration. It's perfectly fine to have multiple declarations across your program. Only one of your .cpp files will have this definition.

这篇关于extern在c ++中的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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