[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,94 +2,220 @@
|
||||
id: wiki-2026-0508-link-seam-링크-접점
|
||||
title: Link Seam (링크 접점)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Link Seam, Linker 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, seam, refactoring]
|
||||
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: cpp
|
||||
framework: none
|
||||
---
|
||||
|
||||
# [[Link Seam (링크 접점)]]
|
||||
# Link Seam (링크 접점)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
링크 접점(Link Seam)은 소스 코드를 직접 수정하지 않고 프로그램의 동작을 변경하거나 대체할 수 있는 접점(Seam)의 한 종류로, 프로그램 빌드 프로세스의 링킹(Linking) 단계에서 발생합니다 [1]. 언어의 컴파일 또는 빌드 시스템이 외부 코드를 연결하는 방식을 활용하여, 테스트 시 프로덕션 코드 대신 테스트용 스텁(Stub)이나 가짜(Fake) 라이브러리를 연결하도록 유도합니다 [1, 2]. 이는 특히 타사 라이브러리처럼 변경하기 어려운 전역적인 의존성을 끊어내고 코드를 독립적으로 테스트할 수 있게 만드는 데 유용하게 활용됩니다 [2].
|
||||
## 매 한 줄
|
||||
> **"매 linker 의 symbol resolution 을 test 의 enabling point 로 활용"**. Michael Feathers, *Working Effectively with Legacy Code* (2004) — 매 source code 변경 없이 link-time 의 symbol substitution 으로 dependency 를 break 하는 seam. C/C++ 의 native 기법, 2026 에서는 매 dynamic library injection (LD_PRELOAD), test double linking, 또는 Bazel/CMake test target 분리 로 활용.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **동작 원리와 언어별 구현 방식:** 링크 접점은 소스 코드가 중간 표현(Intermediate Representation)으로 컴파일된 후, 링커(Linker)나 동적 링킹 시스템에 의해 외부 참조가 해결되는 과정을 이용합니다 [1].
|
||||
* **C/C++의 정적 링킹(Static Linking):** C나 C++과 같이 별도의 링커를 사용하는 언어에서는 대체하고자 하는 클래스나 함수를 위한 별도의 테스트용 라이브러리를 생성한 뒤, 빌드 스크립트를 수정하여 프로덕션 라이브러리 대신 해당 테스트 라이브러리를 링크하는 방식으로 구현할 수 있습니다 [1, 2].
|
||||
* **Java의 동적 링킹(Dynamic Linking):** Java와 같은 언어에서는 컴파일러가 이면에서 링킹을 수행합니다 [1]. 이 경우 `classpath` 환경 변수를 조작하여 시스템이 원래의 클래스 대신 다른 디렉토리에 배치된 동명(同名)의 테스트용 클래스를 먼저 찾도록 함으로써 링크 접점을 활용할 수 있습니다 [3, 4].
|
||||
* **활성화 지점 (Enabling Point):** 링크 접점의 동작을 결정짓는 활성화 지점은 항상 프로그램 소스 코드 **외부**에 위치합니다 [5]. 환경 변수 설정(`classpath` 등), 빌드 스크립트(makefile 등), 또는 배포 스크립트 등 코드 밖의 구성 요소를 통해 테스트용 동작과 프로덕션 동작 중 어떤 것을 사용할지 결정합니다 [4-6].
|
||||
* **의존성 분리와 감지 (Separation and Sensing):** 코드베이스 전반에 걸쳐 타사 그래픽 라이브러리와 같은 의존성이 깊게 퍼져 있을 때 링크 접점은 매우 강력한 도구가 됩니다 [2, 7]. 테스트를 위해 단순히 아무 동작도 하지 않는 빈 함수를 만들어 의존성을 분리(Separation)할 수도 있고, 더 나아가 큐(Queue)와 같은 데이터 구조를 추가해 함수 호출 내역과 전달된 파라미터를 기록함으로써 코드의 내부 상태를 테스트에서 검증할 수 있도록 감지(Sensing)하는 용도로도 활용할 수 있습니다 [2, 8].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **인지의 어려움:** 링크 접점의 활성화 지점이 소스 코드 텍스트 외부(예: 빌드 스크립트나 실행 환경)에 존재하기 때문에, 개발자가 이러한 접점이 사용되고 있다는 사실을 명확히 알아차리기 어려울 수 있습니다 [5].
|
||||
* **환경 관리의 복잡성:** 링크 접점을 사용할 때는 테스트 환경과 프로덕션 환경 간의 차이를 매우 명확하게 관리해야만 배포나 테스트 과정에서 혼란이 발생하는 것을 방지할 수 있습니다 [9].
|
||||
* **유지보수의 한계와 사용 원칙:** 객체 지향 언어에서는 객체 접점(Object Seam)이 가장 명시적이고 권장되는 방식입니다 [10]. 링크 접점이나 전처리 접점(Preprocessing Seam)은 객체 접점에 비해 명시적이지 않으며, 이에 의존하는 테스트 코드는 유지보수하기 까다로울 수 있습니다 [10]. 따라서 이러한 접점들은 의존성이 시스템 전반에 퍼져 있어 객체 접점을 사용하기 등 더 나은 대안이 없는 경우에 한해 제한적으로 사용해야 합니다 [10].
|
||||
### 매 Feathers 의 3 seam types
|
||||
1. **Preprocessing seam**: `#define`, `#ifdef` 의 compile-time substitution.
|
||||
2. **Link seam**: linker 의 symbol resolution 의 test/prod binary 분리.
|
||||
3. **Object seam**: virtual function / interface 의 polymorphic dispatch.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-03*
|
||||
### 매 Link seam 의 enabling mechanism
|
||||
- 매 production code 와 test code 가 동일 header / function signature 를 share.
|
||||
- 매 production binary 는 real implementation `.o` link.
|
||||
- 매 test binary 는 fake/stub implementation `.o` link.
|
||||
- 매 source 파일 변경 없이 매 dependency 의 substitute.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. C/C++ legacy code 의 testability 도입 (most classic use case).
|
||||
2. System call wrapping (LD_PRELOAD 의 fake `gettimeofday`).
|
||||
3. Hardware abstraction layer (HAL) 의 test build.
|
||||
4. Mock library injection (e.g., FFF in C, googlemock 의 link-time mock).
|
||||
5. Embedded system unit testing on host.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 1. C link seam (canonical)
|
||||
```c
|
||||
// time_provider.h
|
||||
#ifndef TIME_PROVIDER_H
|
||||
#define TIME_PROVIDER_H
|
||||
long current_time_ms(void);
|
||||
#endif
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
// production: time_provider_real.c
|
||||
#include <time.h>
|
||||
long current_time_ms(void) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
|
||||
}
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
// test: time_provider_fake.c
|
||||
static long fake_now = 0;
|
||||
long current_time_ms(void) { return fake_now; }
|
||||
void set_fake_time(long t) { fake_now = t; }
|
||||
|
||||
## 🧬 중복 검사 (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
|
||||
// Production link
|
||||
// gcc app.c time_provider_real.c -o app
|
||||
// Test link
|
||||
// gcc test_app.c time_provider_fake.c -o test_app
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 2. CMake target 분리
|
||||
```cmake
|
||||
# CMakeLists.txt
|
||||
add_library(time_real STATIC time_provider_real.c)
|
||||
add_library(time_fake STATIC time_provider_fake.c)
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
add_executable(app main.c)
|
||||
target_link_libraries(app PRIVATE time_real)
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
add_executable(app_test test_main.c)
|
||||
target_link_libraries(app_test PRIVATE time_fake)
|
||||
add_test(NAME app_test COMMAND app_test)
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### 3. Bazel test seam
|
||||
```python
|
||||
# BUILD
|
||||
cc_library(
|
||||
name = "time_real",
|
||||
srcs = ["time_provider_real.c"],
|
||||
hdrs = ["time_provider.h"],
|
||||
)
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
cc_library(
|
||||
name = "time_fake",
|
||||
srcs = ["time_provider_fake.c"],
|
||||
hdrs = ["time_provider.h"],
|
||||
testonly = True,
|
||||
)
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
cc_binary(name = "app", srcs = ["main.c"], deps = [":time_real"])
|
||||
cc_test(name = "app_test", srcs = ["test_main.c"], deps = [":time_fake"])
|
||||
```
|
||||
|
||||
### 4. LD_PRELOAD (runtime link seam)
|
||||
```c
|
||||
// fake_malloc.c
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <stddef.h>
|
||||
|
||||
static int allocation_count = 0;
|
||||
int get_alloc_count(void) { return allocation_count; }
|
||||
|
||||
void *malloc(size_t size) {
|
||||
static void *(*real_malloc)(size_t) = NULL;
|
||||
if (!real_malloc) real_malloc = dlsym(RTLD_NEXT, "malloc");
|
||||
allocation_count++;
|
||||
return real_malloc(size);
|
||||
}
|
||||
|
||||
// Compile: gcc -shared -fPIC fake_malloc.c -ldl -o libfakemalloc.so
|
||||
// Run: LD_PRELOAD=./libfakemalloc.so ./my_program
|
||||
```
|
||||
|
||||
### 5. Weak symbol seam (GCC)
|
||||
```c
|
||||
// production_default.c
|
||||
__attribute__((weak)) int sensor_read(void) {
|
||||
return read_real_sensor();
|
||||
}
|
||||
|
||||
// test_override.c
|
||||
int sensor_read(void) {
|
||||
return 42; // strong symbol overrides weak
|
||||
}
|
||||
|
||||
// Test build links test_override.c → uses fake.
|
||||
// Prod build doesn't link test_override.c → uses weak default.
|
||||
```
|
||||
|
||||
### 6. FFF (Fake Function Framework, C)
|
||||
```c
|
||||
#include "fff.h"
|
||||
DEFINE_FFF_GLOBALS;
|
||||
|
||||
// Header declares: void send_packet(const char* data);
|
||||
FAKE_VOID_FUNC(send_packet, const char*);
|
||||
|
||||
void test_send(void) {
|
||||
RESET_FAKE(send_packet);
|
||||
do_thing();
|
||||
assert(send_packet_fake.call_count == 1);
|
||||
}
|
||||
// Link test binary with fakes instead of real send_packet.
|
||||
```
|
||||
|
||||
### 7. Migration to object seam (preferred long-term)
|
||||
```cpp
|
||||
// 매 link seam 은 stepping stone
|
||||
// 매 long-term: interface + DI 로 evolve
|
||||
class TimeProvider {
|
||||
public:
|
||||
virtual long now_ms() = 0;
|
||||
virtual ~TimeProvider() = default;
|
||||
};
|
||||
|
||||
class RealTimeProvider : public TimeProvider {
|
||||
long now_ms() override { /* real */ }
|
||||
};
|
||||
|
||||
class FakeTimeProvider : public TimeProvider {
|
||||
public:
|
||||
long fake_now = 0;
|
||||
long now_ms() override { return fake_now; }
|
||||
};
|
||||
// Now no link tricks needed — just inject.
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Legacy C code, 매 interface 도입 어려움 | Link seam. |
|
||||
| C++ codebase, 매 refactor 가능 | Object seam (virtual / interface). |
|
||||
| System call / library function 의 mocking | LD_PRELOAD link seam. |
|
||||
| Embedded HAL의 host testing | Link seam (fake HAL implementation). |
|
||||
| Modern code, full DI | Object seam — link seam 불필요. |
|
||||
| Single-binary monolith 의 sub-module test | Link seam 또는 build target 분리. |
|
||||
|
||||
**기본값**: 새 C/C++ 코드는 매 object seam 으로 시작. Link seam 은 매 legacy 의 testability rescue tool.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Seam (Legacy Code)]] · [[Working Effectively with Legacy Code]]
|
||||
- 변형: [[Preprocessing Seam]] · [[Object Seam]]
|
||||
- 응용: [[Test Doubles]] · [[Hardware Abstraction Layer]] · [[LD_PRELOAD]]
|
||||
- Adjacent: [[Dependency Injection]] · [[Mock Object]] · [[Weak Symbols]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: legacy C/C++ codebase 의 unit test 도입, system call mocking, embedded HAL host test.
|
||||
**언제 X**: 매 modern dynamic language (Python/JS/Ruby — monkey patch 충분), 매 fresh codebase (object seam 이 cleaner).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Production binary 에 test fake 누설**: 매 build target separation 실패 시 매 prod 가 fake link. 매 strict CMake/Bazel target 분리.
|
||||
- **Symbol collision**: 매 multiple translation unit 에서 동일 symbol — undefined behavior.
|
||||
- **LD_PRELOAD 의 prod 사용**: 매 debugging 도구로만, 매 production deploy 의 anti-pattern.
|
||||
- **Header/source mismatch**: 매 fake 가 매 signature 변경 의 stale — 매 ABI mismatch crash.
|
||||
- **Link seam 의 영구화**: 매 stepping stone, 매 object seam 으로 evolve 의 missing.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Feathers, *Working Effectively with Legacy Code* 2004, Ch.4 "The Seam Model").
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Feathers seam taxonomy + CMake/Bazel/LD_PRELOAD modern application |
|
||||
|
||||
Reference in New Issue
Block a user