티스토리 뷰

개발/그 외 개발관련

CMake 가이드

부캐: 개발하는 조대리 2025. 1. 3. 02:43
반응형

CMake 가이드

 

CMake 가이드

1. CMake란 무엇인가?

CMake는 빌드 과정을 자동화하기 위한 크로스 플랫폼 도구입니다. CMakeLists.txt라는 설정 파일을 기반으로 플랫폼에 맞는 빌드 파일(예: Makefile 또는 Visual Studio 프로젝트 파일)을 생성합니다.

 

2. 프로젝트 구조

CMake를 사용할 때의 일반적인 프로젝트 구조:

project/
├── src/
│   ├── main.cpp
│   └── hello.cpp
├── include/
│   └── hello.h
└── CMakeLists.txt
    

 

3. CMakeLists.txt 작성

# 최소 CMake 버전
cmake_minimum_required(VERSION 3.10)

# 프로젝트 이름
project(HelloApp)

# 헤더 파일 경로 설정
include_directories(include)

# 소스 파일 목록
set(SOURCES
    src/main.cpp
    src/hello.cpp
)

# 실행 파일 생성
add_executable(app ${SOURCES})
    

 

4. 빌드 과정

  1. 빌드 디렉토리 생성: mkdir build && cd build
  2. CMake 실행: cmake ..
  3. 프로젝트 빌드: make
  4. 프로그램 실행: ./app

 

5. 고급 기능

5.1 라이브러리 추가

# 정적 라이브러리 추가
add_library(hello STATIC src/hello.cpp)

# 실행 파일에 라이브러리 연결
target_link_libraries(app hello)
    

5.2 빌드 옵션 설정

# 컴파일러 옵션 추가
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -O2")
    

5.3 설치 설정

# 설치 경로 정의
install(TARGETS app DESTINATION bin)
install(FILES include/hello.h DESTINATION include)
    

 

6. 일반적인 오류와 해결 방법

오류 메시지 원인 해결 방법
Could not find CMakeLists.txt CMakeLists.txt 파일 없음 CMakeLists.txt 파일 생성 및 프로젝트 설정 추가
No rule to make target Makefile 생성 실패 cmake .. 명령어로 Makefile 재생성
undefined reference 라이브러리 링크 누락 target_link_libraries로 필요한 라이브러리 연결

 

7. 학습 자료