clang-format

Sijin·2025년 7월 6일

환경

  • ubuntu
  • vscode
  • c/cpp

설치

1. clang-format 설치

apt install clang-format
which clang-format // 여기서 나오는 clang-format 실행파일 경로 확인

2. vscode extension 설치

https://marketplace.visualstudio.com/items?itemName=xaver.clang-format

3. vscode 설정

// .vscode/settings.json
{
    "clang-format.executable": "/usr/bin/clang-format",
    "editor.formatOnSave": true
}

4. .clang-format 파일 생성

// .clang-format

BasedOnStyle: Google
IndentWidth: 4
UseTab: Never
ColumnLimit: 120
AllowShortFunctionsOnASingleLine: Empty
BreakBeforeBraces: Allman

동작 예시

formatting 전

void Kernel_task_init(void)
{
    sAllocated_tcb_index = 0;

    for(uint32_t i = 0; i < MAX_TASK_NUM; i++){
        
    }
}

formatting 후

void Kernel_task_init(void)
{
    sAllocated_tcb_index = 0;

    for(uint32_t i = 0; i < MAX_TASK_NUM; i++)
    {
        
    }
}

clang-format style

"C_Cpp.clang_format_fallbackStyle"

vscode settings에서 설정할 수 있는 대표 스타일은 아래와 같은 것 들이 있다

  • LLVM
  • Google
  • Chromium
  • Mozilla
  • Microsoft
  • 등등

커스텀 스타일

  • IndentWidth: 들여쓰기 칸 수
  • UseTab: 탭 사용 여부 (Always, Never, ForIndentation)
  • ColumnLimit: 한 줄 최대 길이
  • BreakBeforeBraces: 중괄호 위치 (Allman은 중괄호를 새 줄에 배치)
  • AllowShortFunctionsOnASingleLine: 짧은 함수 한 줄 허용 여부

변수명 스타일

  • 변수명 스타일은 clang-format이 아닌 clang-tidy에서 관리한다고 함

trouble-shooting

vscode - There are multiple formatters for 'C' files. One of them should be configured... 오류

  • vscode 왼쪽 하단 아이콘이 흔들리면서 format on save 동작이 안됨
  • f1 > Format Document With... 메뉴 > clang-format 선택

0개의 댓글