본문 바로가기
코딩/C++

전역변수, static 변수, 내부 연결, 외부 연결

by sonysame 2024. 2. 19.

1. 범위 지정 연산자 (::)

변수 앞에 붙이면 전역변수 사용을 의미

#include <iostream>

using namespace std;

int value = 123;

int main() {
	int value = 1;
	cout << ::value << endl; //123
	cout << value << endl; //1
	return 0;
}

 

2. static 변수

static 변수: OS로부터 받은 메모리가 static

초기화는 한번만 이루어짐

#include <iostream>

using namespace std;

void doSomething() {
	static int a = 1;
	++a;
	cout << a << endl;
}

int main() {
	doSomething(); //2
	doSomething(); //3
}

 

전역변수를 다른 cpp 파일에서 사용할 수 있다 -> (external linkage)
하지만, static 전역변수는 다른 cpp파일에서 사용할 수 없다 -> (internal linkage)

 

3. forward declaration, extern 변수

<예시1>

 

extern 변수는 다른 파일의 전역 변수를 사용하고자 할 때 사용함

 

main.cpp

#include <iostream>
using namespace std;

static int g_a = 1;

//forward declaration
extern void doSomething(); //extern은 생략가능
extern int a;


int main() {
	doSomething();
	cout << a << endl;
	return 0;
}

 

a.cpp

#include <iostream>

int a = 123;

void doSomething() {
	using namespace std;
	cout << "Hello " << endl;
}

 

For functions, as mentioned earlier, if you declare a function at file scope (outside of any function) without using extern, it is already assumed to have external linkage by default.

 

<예시2>

main.cpp와 test.cpp의 Constants::pi의 주소가 같음!

 

MyConstant.h

#pragma once

namespace Constants {
	extern const double pi;
	extern const double gravity;

}

 

main.cpp

#include <iostream>
#include "MyConstant.h"

using namespace std;

void doSomething();
int g_x(1);

int main() {
	cout << "In main.cpp file "<< Constants::pi << " " << &Constants::pi << endl;
	doSomething();
	return 0;
}

g_x가 const int나 static int로 선언이 되어있으면, external linkage가 불가능하다!

 

test.cpp

#include <iostream>
#include "MyConstant.h"

using namespace std;
extern int g_x;

void doSomething() {
	using namespace std;
	cout << "In test.cpp file " << Constants::pi << " " << &Constants::pi << endl;
	cout << g_x << endl;
}

 

MyConstant.cpp

namespace Constants {
	extern const double pi(3.141592);
	extern const double gravity(9.8);
}

 

'코딩 > C++' 카테고리의 다른 글

입력받는 법  (0) 2024.02.22
namespace, auto, trailing, 암시적 형변환, 명시적 형변환  (0) 2024.02.21
비트플래그, 비트마스크  (0) 2024.02.17
const  (0) 2024.02.17
namespace  (0) 2024.02.16