C++ inline 함수 | "Inline Function" 가이드
이 글의 핵심
C++ inline 함수에 대한 실전 가이드입니다. 개념부터 실무 활용까지 예제와 함께 상세히 설명합니다.
inline 함수란?
함수 호출을 함수 본문으로 대체
// 일반 함수
int add(int a, int b) {
return a + b;
}
// inline 함수
inline int add(int a, int b) {
return a + b;
}
int main() {
int x = add(3, 4);
// 인라인화: int x = 3 + 4;
}
inline의 장점
// 함수 호출 오버헤드 제거
inline int square(int x) {
return x * x;
}
// 루프에서 효과적
for (int i = 0; i < 1000000; i++) {
int result = square(i); // 호출 오버헤드 없음
}
헤더 파일에서 정의
// math_utils.h
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
// inline 함수는 헤더에 정의 가능
inline int add(int a, int b) {
return a + b;
}
inline int multiply(int a, int b) {
return a * b;
}
#endif
// main.cpp
#include "math_utils.h"
int main() {
int x = add(3, 4);
int y = multiply(5, 6);
}
클래스 멤버 함수
class Point {
private:
int x, y;
public:
Point(int x, int y) : x(x), y(y) {}
// 클래스 내부 정의는 암시적 inline
int getX() const {
return x;
}
int getY() const {
return y;
}
// 명시적 inline
inline void setX(int newX) {
x = newX;
}
};
// 클래스 외부 정의는 inline 필요
inline void Point::setY(int newY) {
y = newY;
}
실전 예시
예시 1: 간단한 getter/setter
class Rectangle {
private:
int width, height;
public:
Rectangle(int w, int h) : width(w), height(h) {}
// 간단한 함수는 inline 효과적
int getWidth() const { return width; }
int getHeight() const { return height; }
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
int area() const { return width * height; }
};
예시 2: 수학 유틸리티
// math_utils.h
inline int abs(int x) {
return x < 0 ? -x : x;
}
inline int max(int a, int b) {
return a > b ? a : b;
}
inline int min(int a, int b) {
return a < b ? a : b;
}
inline int clamp(int value, int low, int high) {
return max(low, min(value, high));
}
int main() {
int x = clamp(150, 0, 100); // 100
std::cout << x << std::endl;
}
예시 3: 벡터 연산
struct Vec2 {
float x, y;
Vec2(float x = 0, float y = 0) : x(x), y(y) {}
inline Vec2 operator+(const Vec2& other) const {
return Vec2(x + other.x, y + other.y);
}
inline Vec2 operator-(const Vec2& other) const {
return Vec2(x - other.x, y - other.y);
}
inline Vec2 operator*(float scalar) const {
return Vec2(x * scalar, y * scalar);
}
inline float dot(const Vec2& other) const {
return x * other.x + y * other.y;
}
inline float length() const {
return std::sqrt(x * x + y * y);
}
};
int main() {
Vec2 v1(1, 2);
Vec2 v2(3, 4);
Vec2 v3 = v1 + v2;
float d = v1.dot(v2);
float len = v1.length();
}
예시 4: 비트 연산
// bit_utils.h
inline bool getBit(int value, int pos) {
return (value & (1 << pos)) != 0;
}
inline int setBit(int value, int pos) {
return value | (1 << pos);
}
inline int clearBit(int value, int pos) {
return value & ~(1 << pos);
}
inline int toggleBit(int value, int pos) {
return value ^ (1 << pos);
}
int main() {
int flags = 0;
flags = setBit(flags, 0); // 0001
flags = setBit(flags, 2); // 0101
flags = clearBit(flags, 0); // 0100
std::cout << getBit(flags, 2) << std::endl; // 1
}
inline 제한사항
// inline은 힌트일 뿐 (강제 아님)
inline void complexFunction() {
// 복잡한 코드
// 컴파일러가 인라인 안할 수 있음
}
// 인라인 안되는 경우:
// - 재귀 함수
// - 너무 큰 함수
// - 가상 함수 (대부분)
// - 함수 포인터로 호출
자주 발생하는 문제
문제 1: 큰 함수 인라인
// ❌ 너무 큰 함수
inline void hugeFunction() {
// 수백 줄의 코드
// 코드 크기 증가
}
// ✅ 작은 함수만 inline
inline int add(int a, int b) {
return a + b;
}
문제 2: 재귀 함수
// ❌ 재귀 함수 (인라인 안됨)
inline int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
// 컴파일러가 인라인 안함
문제 3: 헤더 중복 정의
// ❌ inline 없이 헤더에 정의
// utils.h
int add(int a, int b) { // 중복 정의 에러
return a + b;
}
// ✅ inline 추가
inline int add(int a, int b) {
return a + b;
}
문제 4: 가상 함수
class Base {
public:
// inline 가상 함수
virtual inline void func() {
// 대부분 인라인 안됨 (동적 바인딩)
}
};
// 정적 호출 시만 인라인 가능
Base obj;
obj.func(); // 인라인 가능
Base* ptr = &obj;
ptr->func(); // 인라인 안됨
모던 C++에서의 inline
// C++17: inline 변수
inline int globalCounter = 0; // 헤더에 정의 가능
// 클래스 static 멤버
class MyClass {
public:
inline static int count = 0; // C++17
};
사용 권장사항
// ✅ inline 사용 권장
// 1. 간단한 getter/setter
inline int getValue() const { return value; }
// 2. 작은 유틸리티 함수
inline int max(int a, int b) { return a > b ? a : b; }
// 3. 템플릿 함수 (헤더에 정의)
template<typename T>
inline T square(T x) { return x * x; }
// ❌ inline 불필요
// 1. 큰 함수
// 2. 재귀 함수
// 3. 컴파일러가 자동 인라인
FAQ
Q1: inline은 언제 사용?
A:
- 작고 자주 호출되는 함수
- getter/setter
- 헤더 파일 정의
Q2: 성능 향상은?
A: 함수 호출 오버헤드 제거. 작은 함수에서 효과적.
Q3: inline은 강제?
A: 아니요. 힌트일 뿐. 컴파일러가 결정.
Q4: 헤더에 정의 필요?
A: inline 함수는 헤더에 정의 가능 (권장).
Q5: 컴파일러 자동 인라인?
A: 네. 최적화 옵션으로 자동 인라인.
Q6: inline 학습 리소스는?
A:
- “Effective C++”
- cppreference.com
- “C++ Primer”
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- C++ RVO/NRVO | “Return Value Optimization” 가이드
- C++ Expression Templates | “지연 평가” 고급 기법
- C++ Profiling | “성능 프로파일링” 가이드
관련 글
- C++ RVO/NRVO |
- C++ 메모리 정렬 |
- C++ Branch Prediction |
- C++ Cache Optimization |
- C++ Copy Elision |