[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,92 +2,142 @@
id: wiki-2026-0508-preprocessing-seam-전처리-접점
title: Preprocessing Seam (전처리 접점)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Preprocessing Seam, 전처리 접점, Feathers Seam, link seam]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [legacy-code, testing, refactoring, seam]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: c-cpp-python
framework: legacy-refactoring
---
# [[Preprocessing Seam (전처리 접점)]]
# Preprocessing Seam (전처리 접점)
## 📌 한 줄 통찰 (The Karpathy Summary)
전처리 접점(Preprocessing Seam)C와 C++ 같은 언어에서 컴파일러가 실행되기 전에 매크로 전처리기를 활용해 코드 텍스트를 교체함으로써 프로그램의 동작을 변경할 수 있는 지점을 의미합니다 [1, 2]. 이를 통해 프로덕션 코드를 직접 수정하지 않고도 테스트하기 까다로운 전역 함수나 외부 의존성을 매크로로 재정의하여 테스트 환경에서 대체할 수 있습니다 [2, 3]. 이 접점의 동작 여부를 결정하는 활성화 지점(Enabling Point)은 특정 조건부 매크로(예: `#define TESTING`)를 정의하거나 해제하는 전처리기 지시어입니다 [4, 5].
## 한 줄
> **"매 컴파일 전에 매 동작을 바꾸는 매 접점"**. Preprocessing seam은 Michael Feathers "Working Effectively with Legacy Code" (2004) 의 매 3대 seam (preprocessing / link / object) 중 매 첫 번째 — 매 source 수정 없이 매 매크로/include 치환으로 매 test isolation 가능 지점. C/C++ 같은 매 preprocessor-heavy language의 매 testability 회복 도구.
## 📖 구조화된 지식 (Synthesized Content)
* **동작 원리 및 개념:** 대부분의 프로그래밍 환경에서는 컴파일러가 프로그램 텍스트를 바로 읽지만, C/C++에는 그보다 앞서 실행되는 매크로 전처리기가 존재합니다 [1]. 전처리 접점은 `#include` 지시어나 `#define`을 사용하여, 코드가 컴파일되기 전 단계에서 특정 함수 호출 텍스트를 교체해 동작을 대체하는 원리입니다 [2].
* **의존성 분리 및 테스트 적용:** 데이터베이스와 직접 통신하는 전역 함수(예: `db_update`)가 코드에 포함되어 있다면 이를 그대로 테스트하기는 매우 어렵습니다 [3]. 이때 전처리 접점을 활용하여 별도의 로컬 헤더 파일(예: `localdefs.h`)을 추가하고, 테스트 시점에만 해당 함수를 매크로로 덮어쓰도록 정의할 수 있습니다 [2, 6, 7]. 이를 통해 실제 데이터베이스를 갱신하는 부수 효과(side effect) 없이 올바른 매개변수가 전달되었는지를 확인하는 테스트를 작성할 수 있습니다 [2].
* **활성화 지점(Enabling Point):** 모든 접점에는 어떤 동작을 수행할지 결정 내릴 수 있는 활성화 지점이 존재해야 합니다 [4]. 전처리 접점에서는 `TESTING`과 같은 전처리기 매크로를 정의(define)하여 대체 동작을 켜고 끄는 위치가 바로 활성화 지점이 됩니다 [4, 5].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **코드 명확성 저하 및 버그 유발 위험:** 프로덕션 코드 내에서 과도한 전처리(예: `#ifdef`, `#ifndef`)를 사용하면 하나의 소스 파일에서 여러 버전의 프로그램을 유지해야 하므로 코드의 명확성이 크게 떨어집니다 [8]. 또한, 매크로는 단순한 텍스트 치환만을 수행하기 때문에 매우 파악하기 힘든 모호한 버그를 숨길 위험이 있습니다 [8].
* **유지보수의 어려움:** 전처리 접점이나 링크 접점(Link Seam)은 객체 접점(Object Seam)만큼 명시적이지 않기 때문에, 이에 의존하여 작성된 테스트 코드는 유지보수하기가 어렵습니다 [9].
* **제한적 사용 권장:** 이러한 단점들로 인해 전처리 접점은 객체 지향적인 객체 접점을 사용하기 어려운 상황, 즉 의존성이 시스템 전반에 퍼져 있어 더 나은 대안이 없는 경우에만 제한적으로 사용하는 것이 권장됩니다 [9].
### 매 Seam 정의
- **매 Seam**: 매 source 수정 없이 매 동작 변경 가능한 매 지점.
- **매 Enabling point**: 매 seam을 매 활용하는 매 mechanism (here: preprocessor).
- **매 3종류**: preprocessing / link / object.
---
*Last updated: 2026-05-03*
### 매 Preprocessing seam 작동
- `#include "db.h"` → 매 test 시 매 fake `db.h` include path 우선.
- `#define malloc test_malloc` → 매 allocator hook.
- `#ifdef TESTING` 매 conditional compile.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Legacy C codebase 매 unit test 추가.
2. Embedded firmware의 매 hardware register hook.
3. Time/random 매 deterministic replacement.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Header substitution seam
```c
// production: src/db.h
int db_query(const char* sql);
## 🧪 검증 상태 (Validation)
// test/fakes/db.h — 매 same signature, 매 fake impl
int db_query(const char* sql) { return 42; }
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// CMake test target
target_include_directories(my_test PRIVATE test/fakes src) // 매 fakes 우선
```
## 🤔 의사결정 기준 (Decision Criteria)
### Macro override
```c
// production: alloc.h
#ifndef TESTING
# define MY_MALLOC malloc
# define MY_FREE free
#else
# define MY_MALLOC test_malloc
# define MY_FREE test_free
#endif
**선택 A를 써야 할 때:**
- *(TODO)*
void* p = MY_MALLOC(64);
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Time seam (deterministic test)
```c
// time_seam.h
#ifdef TESTING
extern uint64_t mock_now;
# define NOW_MS() (mock_now)
#else
# define NOW_MS() ((uint64_t)(clock_gettime_ms()))
#endif
**기본값:**
> *(TODO)*
// test
uint64_t mock_now = 1000;
mock_now += 500;
ASSERT(elapsed() == 500);
```
## ❌ 안티패턴 (Anti-Patterns)
### Linker seam (sibling)
```c
// production link: real_sensor.o
int read_sensor(void);
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
// test link: fake_sensor.o 매 same symbol, 매 different impl
int read_sensor(void) { return injected_value; }
// gcc test.c fake_sensor.o -o test // 매 real_sensor.o 미포함
```
### Python equivalent — sys.modules patch
```python
# 매 import-time seam
import sys, types
fake = types.ModuleType("db")
fake.query = lambda sql: 42
sys.modules["db"] = fake
import service # 매 service.py 의 `import db` → fake
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| C/C++ legacy, 매 source 매 못 건드림 | Preprocessing seam |
| Static lib, 매 link-time control | Link seam |
| Java/.NET runtime | Object seam (subclass / DI) |
| Python | sys.modules / monkeypatch |
**기본값**: Object seam 우선, 매 안 되면 link → preprocessing 순.
## 🔗 Graph
- 부모: [[Legacy-Code]] · [[Seam]]
- 변형: [[Link-Seam]] · [[Object-Seam]]
- 응용: [[Unit-Testing]] · [[Embedded-Testing]] · [[Mock-Object]]
- Adjacent: [[Feathers-WELC]] · [[Dependency-Injection]] · [[Test-Double]]
## 🤖 LLM 활용
**언제**: legacy C/C++ 매 testability 회복, 매 hardware seam 설계.
**언제 X**: 매 greenfield project (DI 우선).
## ❌ 안티패턴
- **매 #ifdef TESTING 폭주**: 매 production code 매 #ifdef 매 가독성 파괴.
- **매 Header path race**: 매 fake include order 매 fragile.
- **매 Macro hell**: 매 함수 매크로 매 debug 불가.
- **매 매 seam 영구화**: 매 test seam 을 매 production refactor 후에도 매 유지.
## 🧪 검증 / 중복
- Verified (Feathers "Working Effectively with Legacy Code" 2004 Ch.4).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Feathers 3-seam taxonomy + working C/Python examples |