본문 바로가기

PL/C & C++

[C++] extern, static

static은 해당 파일 안에서만 사용

extern은 파일 외부에서도 사용 가능

 

C++ 04.03 - 전역 변수와 링크 (Global variable and linkage)

04.03 - 전역 변수와 링크 (Global variable and linkage) 함수 내부에서 정의된 변수를 지역 변수(local variable)라고 한다. 지역 변수는 블록 스코프(정의된 블록 내에서만 접근 가능)가 있고 자동 주기(정의

boycoding.tistory.com

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)'을 해야 한다.