여러 파일 내의 전역 변수
공통 변수에 액세스해야하는 두 개의 소스 파일이 있습니다. 이를 수행하는 가장 좋은 방법은 무엇입니까? 예 :
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
'IT TIP' 카테고리의 다른 글
| Emacs Lisp를 사용하여 파일이 존재하는지 어떻게 확인할 수 있습니까? (0) | 2020.11.21 |
|---|---|
| 경고 (Selenium IDE) 내부의 확인 버튼을 클릭합니다. (0) | 2020.11.21 |
| 오류 메시지의 이유는 무엇입니까? (0) | 2020.11.21 |
| Bower 종속성 버전 충돌을 해결하는 방법은 무엇입니까? (0) | 2020.11.21 |
| Android 5.0 : 최근 앱 제목 색상을 변경하는 방법은 무엇입니까? (0) | 2020.11.21 |