요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. _clangformat:
clang-format
============
``clang-format`` is a tool to format C/C++/... code according to
a set of rules and heuristics. Like most tools, it is not perfect
nor covers every single case, but it is good enough to be helpful.
``clang-format`` can be used for several purposes:
- Quickly reformat a block of code to the kernel style. Specially useful
when moving code around and aligning/sorting. See clangformatreformat_.
- Spot style mistakes, typos and possible improvements in files
you maintain, patches you review, diffs, etc. See clangformatreview_.
- Help you follow the coding style rules, specially useful for those
new to kernel development or working at the same time in several
projects with different coding styles.
Its configuration file is ``.clang-format`` in the root of the kernel tree.
The rules contained there try to approximate the most common kernel
coding style. They also try to follow :ref:`Documentation/process/coding-style.rst <codingstyle>`
as much as possible. Since not all the kernel follows the same style,
it is possible that you may want to tweak the defaults for a particular
subsystem or folder. To do so, you can override the defaults by writing
another ``.clang-format`` file in a subfolder.
The tool itself has already been included in the repositories of popular
Linux distributions for a long time. Search for ``clang-format`` in
your repositories. Otherwise, you can either download pre-built
LLVM/clang binaries or build the source code from:
https://releases.llvm.org/download.html
See more information about the tool at:
https://clang.llvm.org/docs/ClangFormat.html
https://clang.llvm.org/docs/ClangFormatStyleOptions.html
.. _clangformatreview:
Review files and patches for coding style
-----------------------------------------
By running the tool in its inline mode, you can review full subsystems,
folders or individual files for code style mistakes, typos or improvements.
To do so, you can run something like::
# Make sure your working directory is clean!
clang-format -i kernel/*.[ch]
And then take a look at the git diff.
Counting the lines of such a diff is also useful for improving/tweaking
the style options in the configuration file; as well as testing new
``clang-format`` features/versions.
``clang-format`` also supports reading unified diffs, so you can review
patches and git diffs easily. See the documentation at:
https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting
To avoid ``clang-format`` formatting some portion of a file, you can do::
int formatted_code;
// clang-format off
void unformatted_code ;
// clang-format on
void formatted_code_again;
While it might be tempting to use this to keep a file always in sync with
``clang-format``, specially if you are writing new files or if you are
a maintainer, please note that people might be running different
``clang-format`` versions or not have it available at all. Therefore,
you should probably refrain yourself from using this in kernel sources;
at least until we see if ``clang-format`` becomes commonplace.
.. _clangformatreformat:
Reformatting blocks of code
---------------------------
By using an integration with your text editor, you can reformat arbitrary
blocks (selections) of code with a single keystroke. This is specially
useful when moving code around, for complex code that is deeply intended,
for multi-line macros (and aligning their backslashes), etc.
Remember that you can always tweak the changes afterwards in those cases
where the tool did not do an optimal job. But as a first approximation,
it can be very useful.
There are integrations for many popular text editors. For some of them,
like vim, emacs, BBEdit and Visual Studio you can find support built-in.
For instructions, read the appropriate section at:
https://clang.llvm.org/docs/ClangFormat.html
For Atom, Eclipse, Sublime Text, Visual Studio Code, XCode and other
editors and IDEs you should be able to find ready-to-use plugins.
For this use case, consider using a secondary ``.clang-format``
so that you can tweak a few options. See clangformatextra_.
.. _clangformatmissing:
Missing support
---------------
``clang-format`` is missing support for some things that are common
in kernel code. They are easy to remember, so if you use the tool
regularly, you will quickly learn to avoid/ignore those.
In particular, some very common ones you will notice are:
- Aligned blocks of one-line ``#defines``, e.g.::
#define TRACING_MAP_BITS_DEFAULT 11
#define TRACING_MAP_BITS_MAX 17
#define TRACING_MAP_BITS_MIN 7
vs.::
#define TRACING_MAP_BITS_DEFAULT 11
#define TRACING_MAP_BITS_MAX 17
#define TRACING_MAP_BITS_MIN 7
- Aligned designated initializers, e.g.::
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,
};
vs.::
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,
};
.. _clangformatextra:
Extra features/options
----------------------
Some features/style options are not enabled by default in the configuration
file in order to minimize the differences between the output and the current
code. In other words, to make the difference as small as possible,
which makes reviewing full-file style, as well diffs and patches as easy
as possible.
In other cases (e.g. particular subsystems/folders/files), the kernel style
might be different and enabling some of these options may approximate
better the style there.
For instance:
- Aligning assignments (``AlignConsecutiveAssignments``).
- Aligning declarations (``AlignConsecutiveDeclarations``).
- Reflowing text in comments (``ReflowComments``).
- Sorting ``#includes`` (``SortIncludes``).
They are typically useful for block re-formatting, rather than full-file.
You might want to create another ``.clang-format`` file and use that one
from your editor/IDE instead.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
clang-format 개요와 구성
1-43clang-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에서 그 파일을 사용할 수 있습니다.
요약과 해설
clang-format.rst:1-184`clang-format`은 커널의 `.clang-format` 규칙을 이용해 C 계열 코드를 빠르게 정돈하고 스타일 문제를 찾는 보조 도구입니다. 파일 전체에 일괄 적용하기보다는 깨끗한 작업 트리에서 diff를 검토하거나 편집기의 선택 영역을 다듬는 방식이 실용적입니다.
도구와 버전에 따라 출력이 달라질 수 있고, 커널에서 관례적으로 사용하는 매크로 및 지정 초기화자 열 정렬을 보존하지 못할 수 있습니다. 생성 결과는 반드시 사람이 검토하고, 서브시스템별 필요가 있다면 보조 `.clang-format`과 선택적 정렬 옵션을 제한적으로 사용해야 합니다.