전역 변수 앞에 정적 키워드를 언제 사용합니까?
누군가 헤더 파일에 정의 된 전역 변수 나 상수 앞에 static 키워드를 사용해야 할 때를 설명 할 수 있습니까?
예를 들어 다음과 같은 헤더 파일이 있다고 가정 해 보겠습니다.
const float kGameSpriteWidth = 12.0f;
static앞에 있어야할까요 const? 사용에 대한 몇 가지 모범 사례는 무엇입니까 static?
static일반적으로 좋은 파일에 로컬 변수를 렌더링합니다 . 예를 들어이 Wikipedia 항목을 참조하십시오 .
헤더 파일에 전역 변수를 정의 하면 안됩니다 . .c 소스 파일에서 정의해야합니다.
전역 변수가 하나의 .c 파일에만 표시되도록하려면이를 정적으로 선언해야합니다.
전역 변수가 여러 .c 파일에서 사용되는 경우이를 정적으로 선언해서는 안됩니다. 대신 필요한 모든 .c 파일에 포함 된 헤더 파일에서 extern을 선언해야합니다.
예:
example.h
extern int global_foo;foo.c
#include "example.h" int global_foo = 0; static int local_foo = 0; int foo_function() { /* sees: global_foo and local_foo cannot see: local_bar */ return 0; }bar.c
#include "example.h" static int local_bar = 0; static int local_foo = 0; int bar_function() { /* sees: global_foo, local_bar */ /* sees also local_foo, but it's not the same local_foo as in foo.c it's another variable which happen to have the same name. this function cannot access local_foo defined in foo.c */ return 0; }
예, 정적을 사용합니다.
.c다른 .c모듈 에서 개체를 참조해야하는 경우가 아니면 항상 파일 에서 정적을 사용하십시오 .
정적 .h파일을 포함 할 때마다 다른 개체를 생성하므로 파일에서 정적을 사용하지 마십시오 .
헤더 파일에 대한 경험 법칙 :
- 변수를로 선언하고
extern int foo;해당 초기화를 단일 소스 파일에 넣어 번역 단위간에 공유되는 수정 가능한 값을 얻습니다. static const int foo = 42;인라인 될 수있는 상수를 얻기 위해 사용
static 전역 변수 앞에는이 변수가 정의 된 컴파일 모듈 외부에서이 변수에 액세스 할 수 없음을 의미합니다.
예를 들어 다른 모듈의 변수에 액세스하고 싶다고 상상해보십시오.
foo.c
int var; // a global variable that can be accessed from another module
// static int var; means that var is local to the module only.
...
bar.c
extern int var; // use the variable in foo.c
...
이제 var정적 이라고 선언 하면 foo.c컴파일되는 모듈을 제외하고 어디에서나 액세스 할 수 없습니다 .
모듈은 현재 소스 파일 과 포함 된 모든 파일입니다. 즉, 해당 파일을 개별적으로 컴파일 한 다음 함께 연결해야합니다.
정적 키워드하는 C에서 사용되는 제한 함수 또는 변수의 표시 는 번역 유닛이 . 번역 단위는 개체 파일이 생성되는 C 컴파일러에 대한 최종 입력입니다.
The correct mechanism for C++ in anonymous namespaces. If you want something that is local to your file, you should use an anonymous namespace rather than the static modifier.
global static variables are initialized at compile-time unlike automatic
참고URL : https://stackoverflow.com/questions/1856599/when-to-use-static-keyword-before-global-variables
'IT TIP' 카테고리의 다른 글
| 내 앱의 Android 알림 설정에 연결하는 방법이 있나요? (0) | 2020.11.22 |
|---|---|
| Lodash를 사용하여 값별로 개체 배열 정렬 (0) | 2020.11.22 |
| 자바-JDBC 대안 (0) | 2020.11.22 |
| 파이썬 distutils를 설치하는 방법 (0) | 2020.11.22 |
| 파이썬에서 '어떤'동등한 기능 (0) | 2020.11.22 |