简体   繁体   中英

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

I have been trying a few things out with 'extern' keyword. 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

#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;
}

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.

So, what you want to do is

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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