简体   繁体   English

我们应该在项目中包含的所有文件中声明外部变量吗?

[英]Should we declare extern variables in all the files included in a project?

I have been trying a few things out with 'extern' keyword. 我一直在用'extern'关键字尝试一些事情。 I wrote this basic function and I am not sure why my print function is not working. 我写了这个基本功能,我不知道为什么我的打印功能不起作用。 Kindly help me in understanding it. 请帮助我理解它。

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

test1.cpp test1.cpp

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

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

test2.cpp 测试2.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;
}

You need to use extern only when you are declaring variable/function, and define the variable in one of the cpp files,which include the header. 只有在声明变量/函数时才需要使用extern,并在其中一个cpp文件中定义变量,其中包括标题。

So, what you want to do is 所以,你想要做的是

test1.h test1.h

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

test1.cpp test1.cpp

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

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

test2.cpp 测试2.cpp

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM