本文介绍了在main()与全局中定义extern变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下头文件,如果在主体内部定义了"a",则会收到警告未使用的变量'a'"和链接器错误未定义对'a'的引用.

Given the following header file, if 'a' is defined inside the main body, I get a warning "unused variable 'a'" and linker error "undefined reference to 'a'.

header.h:

#ifndef HEADER_H
#define HEADER_H

#include <iostream>

extern int* a;

void f()
{
    std::cout<<*a <<std::endl;
    return;
}

#endif

main.cpp:

#include "header.h"

int main()
{
    int* a = new int(10);

    f();
}

但是,如果在main()之外定义了"a",则程序将无错误地链接,并且f()会按预期工作(打印10).为什么是这样?

However, if 'a' is defined outside of main(), the program links with no errors and f() works as expected (prints 10). Why is this?

示例:

int* a = new int(10);

int main()
{
    f();
}

推荐答案

您需要学习有关名称绑定的知识,它确定了两个具有相同名称的声明是相关的.定义变量时在一个函数中,其名称没有链接;即它所指的实体与程序中的任何其他实体都不同.

You need to learn about name binding, which determines how twodeclarations of the same name are related. When you define a variablewithin a function, its name has no linkage; i.e. the entity it refers tois distinct from any other entity in the program.

更笼统地说:声明(从这个意义上讲,定义也是声明)将符号与实体和对象相关联(在在这种情况下,声明会声明一个变量),一个函数,一个引用,类型或您可以在C ++中声明的任何其他内容.无论同一名称的不同声明与同一实体相关联是否由它们的 linkage 定义. C ++可以识别三个不同类型的链接:

More generally: a declaration (and in this sense, a definition is also adeclaration) associates a symbol with an entity—an object (inwhich case, the declaration declares a variable), a function, areference, a type or anything else you can declare in C++. Whetherdifferent declarations of the same name associate with the same entityor not is defined by their linkage. C++ recognizes threedifferent types of linkage:

  • 外部链接,其中该实体可以通过其他转换单位中的声明来引用,

  • external linkage, in which the entity can be referred to by declarations in other transation units,

内部链接,其中该实体可以由同一翻译单元中的其他声明引用

internal linkage, in which the entity can be referred to by other declarations in the same translation unit,

无链接,其中任何其他声明都不能引用该实体.

and no linkage, in which the entity cannot be referred to by any other declaration.

在块范围内声明的变量(即局部变量)没有链接,除非它们被明确声明为extern(和本地声明为extern的变量不能为定义).所以int amain声明(并定义)一个独立于任何实体的实体程序中的其他a.在命名空间范围内声明的变量具有外部链接,除非将它们声明为static,否则在这种情况下,它们有内部联系;当您在命名空间范围内定义int a时,它具有外部链接,因此是指您与之声明相同的实体extern int a在标题中.

Variables declared at block scope (i.e. local variables) have nolinkage, unless they are explicitly declared extern (and a localvariable declared extern cannot be a definition). So the int a inmain declares (and defines) an entity which is independent of anyother a in the program. Variables declared in namespace scope haveexternal linkage, unless they are declared static, in which case theyhave internal linkage; when you define int a at namespace scope, ithas external linkage, and so refers to the same entity you declared withextern int a in the header.

这篇关于在main()与全局中定义extern变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 14:03