static은 해당 파일 안에서만 사용
extern은 파일 외부에서도 사용 가능
static과 extern 키워드를 이용한 내부/외부 링크 (Internal and external linkage via the static and extern keywords)
변수는 스코프(scope)와 주기(duration) 외에도 링크(linkage)라는 세 번째 속성이 있다. 링크는 같은 이름의 여러 식별자가 같은 식별자를 참조하는지를 결정한다.
링크가 없는 변수는 정의된 제한된 범위에서만 참조할 수 있다. 지역 변수가 링크가 없는 변수의 예이다. 이름은 같지만 다른 함수에서 정의된 지역 변수는 링크가 없다. 각 변수는 독립적이다.
내부 링크가 있는 변수를 static 변수라고 한다. static 변수는 변수가 정의된 소스 파일 내에서 어디서나 접근할 수 있지만, 소스 파일 외부에서는 참조할 수 없다.
외부 링크가 있는 변수를 extern 변수라고 한다. extern 변수는 정의된 소스 파일과 다른 소스 파일 모두에서 접근할 수 있다.
하나의 파일 내에서만 접근할 수 있는 전역 변수를 생성하려면 다음과 같이 static 키워드를 사용한다:
static int g_x; // g_x is static, and can only be used within this file
int main()
{
return 0;
}
마찬가지로 전역 변수를 외부에서도 접근할 수 있게 만들려면 extern 키워드를 사용하면 된다:
extern double g_y(9.8); // g_y is external, and can be used by other files
// Note: those other files will need to use a `forward declaration` to access this external variable
// We'll discuss this in the next section
int main()
{
return 0;
}
extern 키워드를 통한 변수 전방 선언 (Variable forward declarations via the extern keyword)
다른 소스 파일에서 선언된 외부 전역 변수를 사용하려면 '변수 전방 선언(variable forward declarations)'을 해야 한다.
'PL > C & C++' 카테고리의 다른 글
[C++] 암시적 형 변환 (Implicit type conversion) (0) | 2023.04.06 |
---|---|
[C++] thread, async 차이점 (0) | 2023.04.06 |
[C++] 전처리문 (0) | 2023.04.06 |
[C++] lambda 표현식 (0) | 2023.03.16 |
[C&C++] undefined reference to~ /cpp 파일에서 c 파일 불러오기 (0) | 2022.06.22 |