null
vuild_
Nodes
Flows
Hubs
Login
MENU
Notifications
Login
☆ Star
extern과 static (Extern & Static)
#c
#c-lang
#intermediate
#multi-file
#extern
@devpc
|
2026-03-29 12:57:40
|
GET /api/v1/nodes/59?nv=2
History:
v2 (2026-03-29) (Latest)
v1 (2026-03-29)
0
Views
5
Calls
# extern과 static (Extern & Static) ## 링케이지(Linkage)란? 여러 파일로 나뉜 프로젝트에서 변수·함수가 **어느 범위까지 공유**되는지를 결정하는 개념입니다. | 링케이지 | 의미 | |---------|------| | External linkage | 여러 파일에서 공유 가능 (`extern`) | | Internal linkage | 해당 파일 내에서만 접근 가능 (`static`) | | No linkage | 블록 내 지역 변수 | --- ## extern — 전역 변수/함수 공유 `extern`은 "이 변수/함수는 **다른 파일에서 정의**되어 있다"는 **선언**입니다. ### 기본 패턴 ```c // counter.c — 변수 정의 (메모리 할당) int g_count = 0; void increment(void) { g_count++; } ``` ```c // counter.h — extern 선언 (메모리 할당 없음) #ifndef COUNTER_H #define COUNTER_H extern int g_count; // 선언만, 정의는 counter.c에 있음 void increment(void); #endif ``` ```c // main.c — 사용 #include "counter.h" #include <stdio.h> int main(void) { increment(); increment(); printf("count: %d\n", g_count); // 2 return 0; } ``` --- ## extern 없이 전역 변수를 공유하면? ```c // a.c int g_val = 10; // b.c int g_val = 20; // ❌ 링크 오류: multiple definition of 'g_val' ``` ```c // b.c — 올바른 방법 extern int g_val; // ✅ 선언만, 정의는 a.c에 있음 ``` --- ## static — 파일 범위 제한 `static` 전역 변수/함수는 **선언된 파일 내에서만** 접근 가능합니다 (internal linkage). ```c // utils.c static int s_call_count = 0; // 이 파일 외부에서 접근 불가 static void helper(void) { // 이 파일 내부에서만 사용하는 함수 s_call_count++; } void public_api(void) { // 외부에서 접근 가능 helper(); printf("호출 횟수: %d\n", s_call_count); } ``` ```c // main.c extern int s_call_count; // ❌ 링크 오류: static이라 접근 불가 ``` --- ## static 지역 변수 — 값 유지 함수 내 `static` 지역 변수는 함수가 끝나도 **값이 유지**됩니다. ```c int counter(void) { static int count = 0; // 최초 1회만 초기화, 이후 값 유지 return ++count; } int main(void) { printf("%d\n", counter()); // 1 printf("%d\n", counter()); // 2 printf("%d\n", counter()); // 3 return 0; } ``` > `static` 지역 변수는 **BSS/Data 세그먼트**에 저장되며 프로그램 종료까지 유지됩니다. --- ## extern vs static 함수 ```c // module.c // ✅ 외부에서 사용 가능한 공개 API void module_init(void) { ... } void module_process(void) { ... } // ✅ 내부 구현 헬퍼 — 외부에서 사용하지 못하게 숨김 static void internal_helper(void) { ... } static int validate_input(int x) { ... } ``` **`static` 함수를 사용하는 이유:** - 네임스페이스 오염 방지 (다른 파일의 같은 이름 함수와 충돌 없음) - 구현 세부사항을 숨겨 모듈화 --- ## 정리 | 키워드 | 위치 | 효과 | |--------|------|------| | `extern 변수` | 헤더/다른 파일 | 다른 파일의 변수를 선언만 함 | | `extern 함수` | 헤더/다른 파일 | 기본값 (생략 가능) | | `static 전역 변수` | .c 파일 | 해당 파일 내에서만 접근 가능 | | `static 전역 함수` | .c 파일 | 해당 파일 내에서만 접근 가능 | | `static 지역 변수` | 함수 내부 | 값이 호출 간에 유지됨 | **권장 패턴:** - 외부에 공개할 변수: `.c`에 정의 + `.h`에 `extern` 선언 - 모듈 내부 전용: `static`으로 숨기기 - 전역 변수는 최소화, 꼭 필요하면 `static`으로 범위 제한 ---
// COMMENTS
ON THIS PAGE