Extern
다른 파일이나 나중에 같은 파일에서 정의된 변수나 함수를 선언할 때 사용
해당 변수(함수)는 어딘가에 정의되어있으니 그걸 찾아서 써라!
extern 변수
다른 파일에서 정의된 변수에 접근하려면 extern 을 사용
// 파일 : extern.main.c
#include <stdio.h>
extern int sharedCounter;
void incrementCounter() {
sharedCounter++;
}
int main() {
printf("Initial counter value: %d\n", sharedCounter);
incrementCounter();
printf("Counter value after increment: %d\n", sharedCounter);
return 0;
}
C
복사
// 파일 : extern.couter.c
int sharedCounter = 0;
C
복사
extern 함수
함수는 extern이 default값 → 함수를 static 없이 선언한다면 전체 프로그램에서 접근 가능
// extern.func1.c
#include <stdio.h>
extern int sharedCounter;
// 실제로는 extern 키워드 생략 가능(그러나 명시적으로 쓰는게 컨벤션)
extern void incrementCounter();
int main()
{
printf("Initial counter value: %d\n", sharedCounter);
incrementCounter();
printf("Counter value after increment: %d\n", sharedCounter);
return 0;
}
C
복사
// extern.func2.c
int sharedCounter = 0;
void incrementCounter() {
sharedCounter++;
}
C
복사
Static
변수
함수 내에서의 static 변수
•
로컬 변수지만, 메모리에 한 번만 할당되고 값을 유지
•
프로그램 종료까지 메모리에 적재된 채 유지
(함수가 끝나도 사라지지 않고 다음 호출 때도 이전 값 유지)
void counter()
{
static int cnt = 0; // 딱 한 번만 초기화
cnt++;
printf("%d\n", cnt);
}
int main()
{
counter(); // 1
counter(); // 2
return 0;
}
C
복사
함수 밖(파일 범위)에서의 static 변수
•
해당 파일 내부에서만 접근 가능
•
다른 파일에서는 접근 불가 → 모듈화/캡슐화에 유리
◦
링크 단위 제한(internal linkage)
// main.c
static int global_count = 0; // main.c 내부에서만 접근 가능
C
복사
함수
파일 범위에서의 static 변수와 마찬가지로, static 함수 또한 선언된 파일 내부에서만 접근 가능
// static.var.c
#include <stdio.h>
extern int globalVariable;
extern int add(int a, int b);
int main()
{
printf("%d\n", globalVariable);
printf("%d\n", add(1, 2));
return 0;
}
C
복사
// static.ref.c
int globalVariable = 42;
static int add(int x, int y)
{
return x + y;
}
C
복사
static 함수 결과 : static 함수이므로 외부에서 함수에 접근 불가
참고 자료



