null
vuild_
Nodes
Flows
Hubs
Login
MENU
Notifications
Login
☆ Star
헤더 파일 (Header Files)
#c
#c-lang
#intermediate
#multi-file
#header
@devpc
|
2026-03-29 12:57:40
|
GET /api/v1/nodes/58?nv=2
History:
v2 (2026-03-29) (Latest)
v1 (2026-03-29)
0
Views
5
Calls
# 헤더 파일 (Header Files) ## 선언과 정의의 분리 C 프로젝트가 커지면 코드를 여러 파일로 나눕니다. | 파일 | 역할 | 내용 | |------|------|------| | `.h` (헤더) | **선언(declaration)** | 타입, 함수 프로토타입, 매크로 | | `.c` (구현) | **정의(definition)** | 함수 본문, 변수 초기화 | ``` project/ ├── student.h ← 선언 ├── student.c ← 구현 └── main.c ← 사용 ``` --- ## 헤더 파일 구조 ```c // student.h #ifndef STUDENT_H #define STUDENT_H #include <stdio.h> // 헤더에서 필요한 것만 포함 // 타입 정의 typedef struct { char name[50]; int age; float gpa; } Student; // 함수 선언 (프로토타입) void student_print(const Student *s); void student_set(Student *s, const char *name, int age, float gpa); int student_compare_gpa(const Student *a, const Student *b); #endif // STUDENT_H ``` --- ## 구현 파일 ```c // student.c #include "student.h" // 자신의 헤더 먼저 #include <string.h> // 구현에 필요한 헤더 void student_print(const Student *s) { printf("%-10s %3d %.1f\n", s->name, s->age, s->gpa); } void student_set(Student *s, const char *name, int age, float gpa) { strncpy(s->name, name, sizeof(s->name) - 1); s->name[sizeof(s->name) - 1] = '\0'; s->age = age; s->gpa = gpa; } int student_compare_gpa(const Student *a, const Student *b) { if (a->gpa > b->gpa) return 1; if (a->gpa < b->gpa) return -1; return 0; } ``` --- ## 사용 파일 ```c // main.c #include "student.h" // 프로젝트 헤더: 큰따옴표 #include <stdio.h> // 시스템 헤더: 꺾쇠괄호 int main(void) { Student s1, s2; student_set(&s1, "Alice", 20, 3.8f); student_set(&s2, "Bob", 22, 3.5f); student_print(&s1); student_print(&s2); int cmp = student_compare_gpa(&s1, &s2); printf("GPA 비교: %d\n", cmp); // 1 (s1 > s2) return 0; } ``` --- ## #include 경로 규칙 ```c #include <stdio.h> // 시스템/표준 라이브러리 헤더 (컴파일러 경로에서 검색) #include "student.h" // 프로젝트 헤더 (현재 디렉터리에서 먼저 검색) #include "utils/math.h" // 상대 경로 ``` --- ## 헤더에 포함할 것 vs 포함하지 말 것 ```c // ✅ 헤더에 포함할 것 typedef struct { ... } MyType; // 타입 정의 void func(MyType *p); // 함수 선언 #define MAX_SIZE 100 // 매크로 extern int g_count; // 전역 변수 선언 (extern) // ❌ 헤더에 포함하지 말 것 int g_count = 0; // 변수 정의 → .c 파일에 void func(MyType *p) { ... } // 함수 정의 → .c 파일에 static int s_val; // static 변수 정의 → .c 파일에 ``` --- ## 헤더 포함 순서 권장 사항 (Google C++ Style 기반) ```c // 1. 자신의 헤더 (구현 파일에서) #include "student.h" // 2. 시스템 헤더 #include <stdio.h> #include <stdlib.h> #include <string.h> // 3. 프로젝트 내 다른 헤더 #include "utils.h" ``` --- ## 컴파일 명령 ```bash # 각 파일을 개별 컴파일 후 링크 gcc -c student.c -o student.o gcc -c main.c -o main.o gcc student.o main.o -o program # 한 번에 컴파일 gcc student.c main.c -o program ``` --- ## 정리 | 개념 | 내용 | |------|------| | `.h` 파일 | 타입, 함수 선언, 매크로 | | `.c` 파일 | 함수 정의, 변수 정의 | | `#include "..."` | 프로젝트 헤더 | | `#include <...>` | 시스템 헤더 | | Include guard | 중복 포함 방지 (`#ifndef` / `#pragma once`) | ---
// COMMENTS
ON THIS PAGE