【问题标题】:Should we declare extern variables in all the files included in a project?我们应该在项目中包含的所有文件中声明外部变量吗?
【发布时间】:2019-05-21 04:23:15
【问题描述】:

我一直在尝试使用 'extern' 关键字做一些事情。我写了这个基本功能,但我不确定为什么我的打印功能不起作用。请帮助我理解它。

test1.h

    #pragma once
    #include<iostream>
    using namespace std;
    extern int a;
    extern void print();


test1.cpp

    #include "test1.h"
    extern int a = 745;
    extern void print() {

        cout << "hi "<< a <<endl;
    }

test2.cpp

    #include"test1.h"
    extern int a;
    extern void print();
    int b = ++a;
    int main()
    {
        cout << "hello a is " << b << endl;
        void print();
        return 0;

    }

Actual output  :

    hello a is 746

Expected output:

    hello a is 746
    hi 746

【问题讨论】:

  • 来自上面的链接:"extern说明符只允许在变量和函数的声明中(类成员或函数参数除外)。它指定外部链接,技术上不影响存储持续时间,但它不能用于自动存储持续时间对象的定义中,因此所有外部对象都有静态或线程持续时间。另外,使用外部且没有初始化器的变量声明不是定义“
  • 这个问题与extern 无关——如果所有代码都在同一个文件中,您将观察到相同的缺失输出。在您最喜欢的 C++ 书籍中了解如何调用函数。
  • 顺便说一句:函数在 C++ 中默认为 extern

标签: c++ variables header extern


【解决方案1】:

test1.cpp

#include "test1.h"
int a = 745; //< don't need extern here
void print() { //< or here

    cout << "hi "<< a <<endl;
}

test2.cpp

#include"test1.h"
/* we don't need to redefine the externs here - that's
 what the header file is for... */
int b = ++a;
int main()
{
    cout << "hello a is " << b << endl;
    print(); //< don't redeclare the func, call it instead
    return 0;
}

【讨论】:

    【解决方案2】:

    只有在声明变量/函数时才需要使用 extern,并在包含头文件的 cpp 文件之一中定义变量。

    所以,你想做的是

    test1.h

    #pragma once
    #include<iostream>
    using namespace std;
    extern int a;
    extern void print();
    

    test1.cpp

    #include "test1.h"
    int a = 745;
    void print() {
    
        cout << "hi "<< a <<endl;
    }
    

    test2.cpp

    #include"test1.h"
    int b = ++a;
    int main()
    {
        cout << "hello a is " << b << endl;
        print();
        return 0;
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-11
      • 2011-01-15
      • 2011-05-14
      • 1970-01-01
      • 2014-08-07
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多