C++/Tips

[C++] Extern

메리사츠 2021. 1. 5. 15:21

1. Extern in File[외부링크]

=> Extern은 메모리 할당 없이 해당 변수의 Type을 compiler에게 알려주는 역할이다.[정의는 1회]

=> Extern은 정의된 파일 외에도 다른 Cpp에서 선언한 extern 변수를 사용할 수 있다.

=> 다만 외부링크를 위한 Extern의 경우 함수 내에서 사용하는 것이 아닌, 함수 외부에서 선언되어야 한다.

#include<iostream>
using namespace std;

extern int a; // Extern을 통한 전역선언

int main()
{
	return 0;
}

=> 좀 특이한 점이 있는데, 중복 선언을 해도 에러가 안나는 케이스가 존재한다

//fileA.cpp
int i = 42; // 선언 및 정의

//fileB.cpp
extern int i; // 선언만 가능. A의 변수와 같음

//fileC.cpp
extern int i; // 선언만 가능. A의 변수와 같음

//fileD.cpp
int i = 43; // Error! A에서 이미 정의되었기 때문에 정의 불가능
extern int i = 43; // 동일하게 이미 정의되었기 때문에 정의 불가능

//출처 : https://docs.microsoft.com/ko-kr/cpp/cpp/extern-cpp?view=msvc-160

=> 만일 extern 변수를 바로 정의하고 싶다면, extern const를 사용하면 된다.

//fileA.cpp
extern const int i = 42; // 정의

//fileB.cpp
extern const int i; // only 선언. FileA와 동일함

//출처 : https://docs.microsoft.com/ko-kr/cpp/cpp/extern-cpp?view=msvc-160

 

++ Static 선언과 extern을 선언한 경우, Static이 이긴다..

//fileA.cpp
static const int a = 10; // Static 선언

//fileB.cpp
extern const int a; // 선언 OK

int main()
{
	cout << a << endl; // 엑세스 불가로 인한 Error
    return 0;
}