IT TIP

여러 파일 내의 전역 변수

itqueen 2020. 11. 21. 08:31
반응형

여러 파일 내의 전역 변수


공통 변수에 액세스해야하는 두 개의 소스 파일이 있습니다. 이를 수행하는 가장 좋은 방법은 무엇입니까? 예 :

source1.cpp :

int global;

int function();

int main()
{
    global=42;
    function();
    return 0;
}

source2.cpp :

int function()
{
    if(global==42)
        return 42;
    return 0;
}

global 변수의 선언은 static, extern이어야합니까, 아니면 두 파일에 포함 된 헤더 파일 등에 있어야합니까?


전역 변수는 extern두 소스 파일 모두에 포함 된 헤더 파일에서 선언 된 다음 해당 소스 파일 중 하나에서만 정의되어야합니다.

common.h

extern int global;

source1.cpp

#include "common.h"

int global;

int function(); 

int main()
{
    global=42;
    function();
    return 0;
}

source2.cpp

#include "common.h"

int function()
{
    if(global==42)
        return 42;
    return 0;
}

모듈 source1.cpp에 대한 인터페이스를 설명하는 "헤더 파일"을 추가합니다.

source1.h

#ifndef SOURCE1_H_
#define SOURCE1_H_

extern int global;

#endif

source2.h

#ifndef SOURCE2_H_
#define SOURCE2_H_

int function();

#endif

이 변수를 사용하는 각 파일에 #include 문을 추가하고 변수를 정의하는 (중요).

source1.cpp

#include "source1.h"
#include "source2.h"

int global;     

int main()     
{     
    global=42;     
    function();     
    return 0;     
}

source2.cpp

#include "source1.h"
#include "source2.h"

int function()            
{            
    if(global==42)            
        return 42;            
    return 0;            
}

While it is not necessary, I suggest the name source1.h for the file to show that it describes the public interface to the module source1.cpp. In the same way source2.h describes what is public available in source2.cpp.


In one file you declare it as in source1.cpp, in the second you declare it as

extern int global;

Of course you really don't want to be doing this and should probably post a question about what you are trying to achieve so people here can give you other ways of achieving it.

참고URL : https://stackoverflow.com/questions/3627941/global-variable-within-multiple-files

반응형