簡體   English   中英

我們應該在項目中包含的所有文件中聲明外部變量嗎?

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

我一直在用'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;
}

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

只有在聲明變量/函數時才需要使用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;
}

測試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