Должны ли мы объявлять внешние переменные во всех файлах, включенных в проект? - PullRequest
0 голосов
/ 21 мая 2019

Я пробовал несколько вещей с ключевым словом 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

Ответы [ 2 ]

0 голосов
/ 21 мая 2019

Вам нужно использовать 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;

}
0 голосов
/ 21 мая 2019

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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...