CMake Quick Guide (with docker compose)

1. 개요

CMake는 C/C++ 등 여러 프로그래밍 언어로 작성된 프로젝트의 빌드 자동화 도구입니다. GNU Make나 Ninja 같은 하위 빌드 시스템의 설정 파일을 생성하는 메타 빌드 시스템(Meta Build System) 이라고 할 수 있습니다.

2. CMake의 핵심 개념

2.1. CMakeLists.txt

  • CMake 프로젝트는 이 파일을 중심으로 구성됩니다.
  • 빌드 설정, 소스 코드 목록, 컴파일 옵션 등을 명시합니다.

2.2. 빌드 디렉토리 분리 (Out-of-source build)

  • 소스 코드와 빌드 결과물을 분리하여 관리 가능
  • 예:
Bash
mkdir build
cd build
cmake ..
make
Bash

2.3. 다양한 플랫폼 지원

  • Windows, macOS, Linux 등에서 동일한 CMakeLists.txt로 빌드 구성 가능
  • Visual Studio, Makefile, Ninja 등 다양한 빌드 시스템을 지원

3. 주요 명령어

명령어설명
cmake .현재 디렉토리의 CMakeLists.txt를 바탕으로 빌드 설정 생성
cmake ..상위 디렉토리의 CMakeLists.txt를 사용해 빌드 설정 생성
make생성된 Makefile로 실제 빌드 수행
cmake --build .플랫폼 독립적 빌드 명령

4. 주요 기능

  • install, test, configure_file 등 다양한 프로젝트 관리 기능 내장
  • find_package로 외부 라이브러리 탐색
  • target_link_libraries로 라이브러리 연결
  • option, if 등을 활용한 조건부 설정

5. 예시 프로젝트 구조

Bash
MyCMakeWithDockerCompose/
├── app/
   ├── CMakeLists.txt
   └── hello-world.cpp
└── docker-compose.yml
Bash

app/CMakeLists.txt:

CMake
cmake_minimum_required(VERSION 3.10)

set(CMAKE_C_COMPILER "/usr/bin/gcc")
set(CMAKE_CXX_COMPILER "/usr/bin/g++")

project(HelloWorld)

add_executable(HelloWorld hello-world.cpp)
CMake

app/hello-world.cpp:

C++
#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
C++

docker-compose.yml:

YAML
services:
  hello-cmake:
    image: ubuntu:18.04
    container_name: hello-cmake
    volumes:
      - type: bind
        source: ./app
        target: /app
    working_dir: /app
    command: >
      bash -c "
        apt update &&
        apt install -y cmake build-essential &&
        mkdir -p build &&
        cd build &&
        cmake .. &&
        make
      "
YAML

6. 예시 프로젝트 빌드

Bash
root@centricone:~/MyCMakeWithDockerCompose# docker compose up
[+] Running 1/1
  Container hello-cmake  Created
Attaching to hello-cmake
hello-cmake  | 

...... 생략 ......

hello-cmake  | [100%] Linking CXX executable HelloWorld
hello-cmake  | [100%] Built target HelloWorld
hello-cmake exited with code 0
root@centricone:~/MyCMakeWithDockerCompose# ls -l app/build/
total 40
-rw-r--r-- 1 root root 12200 May 19 02:14 CMakeCache.txt     
drwxr-xr-x 5 root root  4096 May 19 02:15 CMakeFiles
-rw-r--r-- 1 root root  1460 May 19 02:14 cmake_install.cmake
-rwxr-xr-x 1 root root  8928 May 19 02:14 HelloWorld
-rw-r--r-- 1 root root  4839 May 19 02:15 Makefile
root@centricone:~/MyCMakeWithDockerCompose/app# ./build/HelloWorld 
Hello, World!
root@centricone:~/MyCMakeWithDockerCompose#
Bash

1: 도커 컨테이너 실행

12: 빌드내용 확인을 위해 디렉터리 조회

17: 빌드된 HelloWorld 바이너리

7. CMake의 장점

  • 다양한 옵션 제공: 테스트, 설치, 패키징 등 통합 관리
  • 유지보수 용이: 큰 프로젝트에서도 구성 관리가 쉬움
  • 크로스 플랫폼: 다양한 OS 및 빌드 도구에 대응
  • 모듈화: 서브 디렉토리 단위 구성 가능

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다