본문으로 건너뛰기
Previous
Next
C++ Linking Explained: Static vs Dynamic Libraries, Symbols,

C++ Linking Explained: Static vs Dynamic Libraries, Symbols,

C++ Linking Explained: Static vs Dynamic Libraries, Symbols,

이 글의 핵심

How the linker combines object files into executables and libraries. Static vs dynamic linking, undefined reference fixes, -L/-l order, rpath, nm, ldd, and LTO basics.

Introduction

Linking combines object files (.o) into an executable or library—the last stage of the build. The compiler turns each .cpp into machine code independently; the linker connects them into the final image.

1. Linking basics

# 1) Compile only (no link)
g++ -c main.cpp -o main.o
g++ -c util.cpp -o util.o
# 2) Link objects into executable
g++ main.o util.o -o myapp
# Or one step (compile + link)
g++ main.cpp util.cpp -o myapp

Layout:

// util.h
#pragma once
int add(int a, int b);
// util.cpp
#include "util.h"
int add(int a, int b) {
    return a + b;
}
// main.cpp
#include <iostream>
#include "util.h"
int main() {
    std::cout << add(10, 20) << std::endl;
    return 0;
}

What the linker does

1. Symbol resolution — connect call sites to definitions
2. Relocation — fix addresses/offsets for the final layout
3. Final image — produce executable or .so/.dll

2. Static linking

Building a static library

g++ -c lib.cpp -o lib.o
ar rcs libmylib.a lib.o
g++ main.cpp -L. -lmylib -o myapp

Traits:

  • Simple deployment (single binary option)
  • No runtime library load
  • Larger binary
  • Library updates require relink

3. Dynamic linking

Linux/macOS shared libraries

g++ -fPIC -c lib.cpp -o lib.o
g++ -shared lib.o -o libmylib.so
g++ main.cpp -L. -lmylib -Wl,-rpath,. -o myapp
./myapp
# Or use LD_LIBRARY_PATH
LD_LIBRARY_PATH=. ./myapp

Windows DLL (conceptual)

g++ -shared lib.cpp -o mylib.dll
g++ main.cpp -L. -lmylib -o myapp.exe

Traits:

  • Smaller binaries; shared memory across processes
  • Runtime loader must find the library
  • Versioning and deployment are trickier

4. Common problems

Problem 1: undefined reference

undefined reference to `add(int, int)'

Fix: add the .o/.cpp or -l library that defines the symbol.

Problem 2: Library order

Dependencies go after dependents on many Unix linkers:

g++ main.o -lA -lB   # if main needs A and A needs B, order may matter

Problem 3: Library search path

g++ main.o -L./lib -lmylib -o myapp

Problem 4: Shared library not found at run time

g++ main.o -L./lib -lmylib -Wl,-rpath,./lib -o myapp
# or LD_LIBRARY_PATH, or install to system lib path + ldconfig

5. Inspecting symbols

nm

Lists symbols in objects or executables. T = defined in text, U = undefined.

ldd (Linux)

Lists shared library dependencies of an executable.

objdump

Disassembly (-d), symbol tables (-t), dynamic symbols (-T).

g++ -flto main.cpp util.cpp -o myapp
g++ -flto -O3 main.cpp util.cpp -o myapp

Effects: whole-program optimization across TUs; longer builds; harder debugging.

7. Build examples

Makefile (sketch)

CXX = g++
CXXFLAGS = -std=c++17 -Wall -g
OBJS = main.o util.o
myapp: $(OBJS)
	$(CXX) $(OBJS) -o myapp

CMake (sketch)

add_library(mylib STATIC lib.cpp)
add_executable(myapp main.cpp util.cpp)
target_link_libraries(myapp mylib)

Summary

  1. Linking joins object files.
  2. Static bundles code; dynamic references shared libs.
  3. Symbol resolution matches calls to definitions.
  4. LTO can improve performance at build cost.

Static vs dynamic

StaticDynamic
Files.a / .lib.so / .dll
SizeLarger exeSmaller exe
SpeedNo load stepLoad at startup
UpdatesRelinkOften replace .so only
Next: Name mangling, Compilation process, Makefile.


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. How the linker combines object files into executables and libraries. Static vs dynamic linking, undefined reference fixe… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, linking, static, dynamic, symbols 등으로 검색하시면 이 글이 도움이 됩니다.