← Documents Documentation/dev-tools/clang-format.rst GitHub 원문 ↗

Linux 6.18.37 · Dev Tools

clang-format

clang-format으로 커널 코드를 검토하고 선택 영역을 다시 서식화하는 방법, 커널 스타일 구성과 도구가 보존하지 못하는 정렬 패턴 및 선택적 스타일 옵션을 설명합니다.

Source pathDocumentation/dev-tools/clang-format.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

clang-format.rst:1-184

`clang-format`은 커널의 `.clang-format` 규칙을 이용해 C 계열 코드를 빠르게 정돈하고 스타일 문제를 찾는 보조 도구입니다. 파일 전체에 일괄 적용하기보다는 깨끗한 작업 트리에서 diff를 검토하거나 편집기의 선택 영역을 다듬는 방식이 실용적입니다.

도구와 버전에 따라 출력이 달라질 수 있고, 커널에서 관례적으로 사용하는 매크로 및 지정 초기화자 열 정렬을 보존하지 못할 수 있습니다. 생성 결과는 반드시 사람이 검토하고, 서브시스템별 필요가 있다면 보조 `.clang-format`과 선택적 정렬 옵션을 제한적으로 사용해야 합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. _clangformat:
2
3 clang-format
4 ============
5
6 ``clang-format`` is a tool to format C/C++/... code according to
7 a set of rules and heuristics. Like most tools, it is not perfect
8 nor covers every single case, but it is good enough to be helpful.
9
10 ``clang-format`` can be used for several purposes:
11
12 - Quickly reformat a block of code to the kernel style. Specially useful
13 when moving code around and aligning/sorting. See clangformatreformat_.
14
15 - Spot style mistakes, typos and possible improvements in files
16 you maintain, patches you review, diffs, etc. See clangformatreview_.
17
18 - Help you follow the coding style rules, specially useful for those
19 new to kernel development or working at the same time in several
20 projects with different coding styles.
21
22 Its configuration file is ``.clang-format`` in the root of the kernel tree.
23 The rules contained there try to approximate the most common kernel
24 coding style. They also try to follow :ref:`Documentation/process/coding-style.rst <codingstyle>`
25 as much as possible. Since not all the kernel follows the same style,
26 it is possible that you may want to tweak the defaults for a particular
27 subsystem or folder. To do so, you can override the defaults by writing
28 another ``.clang-format`` file in a subfolder.
29
30 The tool itself has already been included in the repositories of popular
31 Linux distributions for a long time. Search for ``clang-format`` in
32 your repositories. Otherwise, you can either download pre-built
33 LLVM/clang binaries or build the source code from:
34
35 https://releases.llvm.org/download.html
36
37 See more information about the tool at:
38
39 https://clang.llvm.org/docs/ClangFormat.html
40
41 https://clang.llvm.org/docs/ClangFormatStyleOptions.html
42
43
44 .. _clangformatreview:
45
46 Review files and patches for coding style
47 -----------------------------------------
48
49 By running the tool in its inline mode, you can review full subsystems,
50 folders or individual files for code style mistakes, typos or improvements.
51
52 To do so, you can run something like::
53
54 # Make sure your working directory is clean!
55 clang-format -i kernel/*.[ch]
56
57 And then take a look at the git diff.
58
59 Counting the lines of such a diff is also useful for improving/tweaking
60 the style options in the configuration file; as well as testing new
61 ``clang-format`` features/versions.
62
63 ``clang-format`` also supports reading unified diffs, so you can review
64 patches and git diffs easily. See the documentation at:
65
66 https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting
67
68 To avoid ``clang-format`` formatting some portion of a file, you can do::
69
70 int formatted_code;
71 // clang-format off
72 void unformatted_code ;
73 // clang-format on
74 void formatted_code_again;
75
76 While it might be tempting to use this to keep a file always in sync with
77 ``clang-format``, specially if you are writing new files or if you are
78 a maintainer, please note that people might be running different
79 ``clang-format`` versions or not have it available at all. Therefore,
80 you should probably refrain yourself from using this in kernel sources;
81 at least until we see if ``clang-format`` becomes commonplace.
82
83
84 .. _clangformatreformat:
85
86 Reformatting blocks of code
87 ---------------------------
88
89 By using an integration with your text editor, you can reformat arbitrary
90 blocks (selections) of code with a single keystroke. This is specially
91 useful when moving code around, for complex code that is deeply intended,
92 for multi-line macros (and aligning their backslashes), etc.
93
94 Remember that you can always tweak the changes afterwards in those cases
95 where the tool did not do an optimal job. But as a first approximation,
96 it can be very useful.
97
98 There are integrations for many popular text editors. For some of them,
99 like vim, emacs, BBEdit and Visual Studio you can find support built-in.
100 For instructions, read the appropriate section at:
101
102 https://clang.llvm.org/docs/ClangFormat.html
103
104 For Atom, Eclipse, Sublime Text, Visual Studio Code, XCode and other
105 editors and IDEs you should be able to find ready-to-use plugins.
106
107 For this use case, consider using a secondary ``.clang-format``
108 so that you can tweak a few options. See clangformatextra_.
109
110
111 .. _clangformatmissing:
112
113 Missing support
114 ---------------
115
116 ``clang-format`` is missing support for some things that are common
117 in kernel code. They are easy to remember, so if you use the tool
118 regularly, you will quickly learn to avoid/ignore those.
119
120 In particular, some very common ones you will notice are:
121
122 - Aligned blocks of one-line ``#defines``, e.g.::
123
124 #define TRACING_MAP_BITS_DEFAULT 11
125 #define TRACING_MAP_BITS_MAX 17
126 #define TRACING_MAP_BITS_MIN 7
127
128 vs.::
129
130 #define TRACING_MAP_BITS_DEFAULT 11
131 #define TRACING_MAP_BITS_MAX 17
132 #define TRACING_MAP_BITS_MIN 7
133
134 - Aligned designated initializers, e.g.::
135
136 static const struct file_operations uprobe_events_ops = {
137 .owner = THIS_MODULE,
138 .open = probes_open,
139 .read = seq_read,
140 .llseek = seq_lseek,
141 .release = seq_release,
142 .write = probes_write,
143 };
144
145 vs.::
146
147 static const struct file_operations uprobe_events_ops = {
148 .owner = THIS_MODULE,
149 .open = probes_open,
150 .read = seq_read,
151 .llseek = seq_lseek,
152 .release = seq_release,
153 .write = probes_write,
154 };
155
156
157 .. _clangformatextra:
158
159 Extra features/options
160 ----------------------
161
162 Some features/style options are not enabled by default in the configuration
163 file in order to minimize the differences between the output and the current
164 code. In other words, to make the difference as small as possible,
165 which makes reviewing full-file style, as well diffs and patches as easy
166 as possible.
167
168 In other cases (e.g. particular subsystems/folders/files), the kernel style
169 might be different and enabling some of these options may approximate
170 better the style there.
171
172 For instance:
173
174 - Aligning assignments (``AlignConsecutiveAssignments``).
175
176 - Aligning declarations (``AlignConsecutiveDeclarations``).
177
178 - Reflowing text in comments (``ReflowComments``).
179
180 - Sorting ``#includes`` (``SortIncludes``).
181
182 They are typically useful for block re-formatting, rather than full-file.
183 You might want to create another ``.clang-format`` file and use that one
184 from your editor/IDE instead.
185

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

clang-format 개요와 구성

1-43

clang-format

`clang-format`은 일련의 규칙과 휴리스틱에 따라 C/C++ 등의 코드를 서식화하는 도구입니다. 대부분의 도구와 마찬가지로 완벽하지 않고 모든 단일 사례를 다루지는 못하지만, 도움을 주기에는 충분합니다.

`clang-format`은 다음과 같은 여러 목적으로 사용할 수 있습니다.

코드 블록을 커널 스타일로 빠르게 다시 서식화할 수 있습니다. 코드를 옮기거나 정렬하고 순서를 맞출 때 특히 유용합니다. clangformatreformat_을 참조하십시오.

유지 관리하는 파일, 검토하는 패치, diff 등에서 스타일 실수, 오타, 개선 가능성을 찾을 수 있습니다. clangformatreview_를 참조하십시오.

코딩 스타일 규칙을 따르도록 도와줍니다. 커널 개발을 처음 시작했거나 서로 다른 코딩 스타일을 사용하는 여러 프로젝트를 동시에 작업할 때 특히 유용합니다.

구성 파일은 커널 트리 루트의 `.clang-format`입니다. 이 파일의 규칙은 가장 일반적인 커널 코딩 스타일을 근사하려고 하며, 가능한 한 `Documentation/process/coding-style.rst <codingstyle>`도 따르려고 합니다. 커널 전체가 같은 스타일을 따르지는 않으므로 특정 서브시스템이나 폴더에서는 기본값을 조정하고 싶을 수 있습니다. 하위 폴더에 다른 `.clang-format` 파일을 작성하면 기본값을 재정의할 수 있습니다.

도구 자체는 오래전부터 널리 쓰이는 Linux 배포판 저장소에 포함되어 있습니다. 사용하는 저장소에서 `clang-format`을 검색하십시오. 또는 다음 위치에서 미리 빌드된 LLVM/clang 바이너리를 내려받거나 소스 코드를 빌드할 수 있습니다.

https://releases.llvm.org/download.html

도구에 관한 자세한 정보는 다음 문서를 참조하십시오.

https://clang.llvm.org/docs/ClangFormat.html

https://clang.llvm.org/docs/ClangFormatStyleOptions.html

코딩 스타일 관점에서 파일과 패치 검토

44-83

코딩 스타일 관점에서 파일과 패치 검토

도구를 인라인 모드로 실행하면 전체 서브시스템, 폴더 또는 개별 파일에서 코드 스타일 실수, 오타, 개선점을 검토할 수 있습니다.

다음과 같이 실행할 수 있습니다.

# Make sure your working directory is clean!
clang-format -i kernel/*.[ch]

그런 다음 git diff를 살펴보십시오.

이 diff의 줄 수를 세는 것도 구성 파일의 스타일 옵션을 개선하거나 조정하는 데 유용하며, 새로운 `clang-format` 기능이나 버전을 시험하는 데에도 유용합니다.

`clang-format`은 unified diff 읽기도 지원하므로 패치와 git diff를 쉽게 검토할 수 있습니다. 다음 문서를 참조하십시오.

https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting

`clang-format`이 파일의 일부 구간을 서식화하지 않게 하려면 다음과 같이 할 수 있습니다.

int formatted_code;
// clang-format off
    void    unformatted_code  ;
// clang-format on
void formatted_code_again;

특히 새 파일을 작성하거나 maintainer인 경우, 파일을 항상 `clang-format`과 동기화하려고 이 기능을 쓰고 싶을 수 있습니다. 그러나 사람마다 서로 다른 `clang-format` 버전을 실행하거나 도구를 전혀 사용할 수 없을 수 있다는 점에 유의하십시오. 따라서 커널 소스에서는 이 기능 사용을 자제하는 편이 좋습니다. 적어도 `clang-format`이 보편화되는지는 지켜봐야 합니다.

코드 블록 다시 서식화

84-110

코드 블록 다시 서식화

텍스트 편집기와의 통합을 사용하면 한 번의 키 입력으로 임의의 코드 블록, 즉 선택 영역을 다시 서식화할 수 있습니다. 코드를 옮길 때, 들여쓰기가 깊은 복잡한 코드, 여러 줄 매크로와 그 백슬래시 정렬 등에 특히 유용합니다.

도구가 최적의 결과를 만들지 못한 경우에는 언제든 변경 내용을 나중에 직접 조정할 수 있습니다. 하지만 첫 번째 근사 결과로는 매우 유용할 수 있습니다.

널리 쓰이는 여러 텍스트 편집기용 통합이 있습니다. vim, emacs, BBEdit, Visual Studio 같은 일부 편집기는 지원 기능이 내장되어 있습니다. 사용 방법은 다음 문서의 해당 절을 읽으십시오.

https://clang.llvm.org/docs/ClangFormat.html

Atom, Eclipse, Sublime Text, Visual Studio Code, XCode 및 기타 편집기와 IDE에서는 바로 사용할 수 있는 플러그인을 찾을 수 있을 것입니다.

이 용도에는 몇 가지 옵션을 조정할 수 있도록 보조 `.clang-format` 파일 사용을 고려하십시오. clangformatextra_를 참조하십시오.

지원하지 않는 커널 코드 패턴

111-156

지원하지 않는 기능

`clang-format`은 커널 코드에서 흔히 쓰이는 몇 가지 형식을 지원하지 않습니다. 기억하기 쉬운 사례들이므로 도구를 정기적으로 사용하면 곧 이런 형식을 피하거나 결과를 무시하는 방법을 익히게 됩니다.

특히 자주 보게 되는 사례는 다음과 같습니다.

한 줄짜리 `#define` 블록의 정렬. 예를 들면 다음과 같습니다.

#define TRACING_MAP_BITS_DEFAULT       11
#define TRACING_MAP_BITS_MAX           17
#define TRACING_MAP_BITS_MIN           7

위 형식과 다음 형식을 비교하십시오.

#define TRACING_MAP_BITS_DEFAULT 11
#define TRACING_MAP_BITS_MAX 17
#define TRACING_MAP_BITS_MIN 7

지정 초기화자의 정렬. 예를 들면 다음과 같습니다.

static const struct file_operations uprobe_events_ops = {
        .owner          = THIS_MODULE,
        .open           = probes_open,
        .read           = seq_read,
        .llseek         = seq_lseek,
        .release        = seq_release,
        .write          = probes_write,
};

위 형식과 다음 형식을 비교하십시오.

static const struct file_operations uprobe_events_ops = {
        .owner = THIS_MODULE,
        .open = probes_open,
        .read = seq_read,
        .llseek = seq_lseek,
        .release = seq_release,
        .write = probes_write,
};

추가 기능과 옵션

157-184

추가 기능/옵션

출력과 현재 코드 사이의 차이를 최소화하기 위해 일부 기능과 스타일 옵션은 구성 파일에서 기본적으로 활성화하지 않습니다. 다시 말해 차이를 가능한 한 작게 만들어 전체 파일의 스타일뿐 아니라 diff와 패치도 가능한 한 쉽게 검토할 수 있게 합니다.

특정 서브시스템, 폴더 또는 파일 같은 다른 경우에는 커널 스타일이 다를 수 있으며, 이런 옵션 가운데 일부를 활성화하면 해당 위치의 스타일을 더 잘 근사할 수 있습니다.

예를 들면 다음과 같습니다.

대입문 정렬(`AlignConsecutiveAssignments`).

선언 정렬(`AlignConsecutiveDeclarations`).

주석의 텍스트 재배치(`ReflowComments`).

`#include` 정렬(`SortIncludes`).

이 옵션들은 일반적으로 전체 파일보다 코드 블록을 다시 서식화할 때 유용합니다. 다른 `.clang-format` 파일을 만들어 편집기나 IDE에서 그 파일을 사용할 수 있습니다.