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

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

本文关键字:文件 声明 变量 外部 包含 是否 项目 我们      更新时间:2023-10-16

我一直在尝试使用'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

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

您仅在声明变量/函数时才需要使用外部,并在其中一个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;
}