簡単な答え: はい。
clang-format
ツールにはオプションがあり-sort-includes
ます。ディレクティブの順序を変更する#include
と、既存のコードの動作が確実に変更され、既存のコードが壊れる可能性があります。
対応するSortIncludes
オプションがいくつかの組み込みスタイルによって設定されているため、インクルードの順序が変更さtrue
れるかどうかは明らかではありません。clang-format
MyStruct.h:
struct MyStruct {
uint8_t value;
};
オリジナル.c:
#include <stdint.h>
#include <stddef.h>
#include "MyStruct.h"
int main (int argc, char **argv) {
struct MyStruct s = { 0 };
return s.value;
}
では、 を実行するとしましょうclang-format -style=llvm original.c > restyled.c
。
restyled.c:
#include "MyStruct.h"
#include <stddef.h>
#include <stdint.h>
int main(int argc, char **argv) {
struct MyStruct s = {0};
return s.value;
}
ヘッダー ファイルの並べ替えが原因で、コンパイル時に次のエラーが発生しますrestyled.c
。
In file included from restyled.c:1:
./MyStruct.h:2:5: error: unknown type name 'uint8_t'
uint8_t value;
^
1 error generated.
ただし、この問題は簡単に回避できます。このような順序依存のインクルードがある可能性は低いですが、そうする場合は、特定の順序を必要とするヘッダーのclang-format
グループの間に空白行を入れることで問題を解決できます。の間に。#include
#include
固定オリジナル.c:
#include <stdint.h>
#include <stddef.h>
#include "MyStruct.h"
int main (int argc, char **argv) {
struct MyStruct s = { 0 };
return s.value;
}
fixed-restyled.c:
#include <stddef.h>
#include <stdint.h>
#include "MyStruct.h"
int main(int argc, char **argv) {
struct MyStruct s = {0};
return s.value;
}
stdint.h
と のインクルードはまだ「グループ化」されているため、とstddef.h
はまだ並べ替えられていることに注意してください。ただし、新しい空白行MyStruct.h
は標準ライブラリのインクルードの前に移動できませんでした。
でも...
ディレクティブの順序を変更する#include
とコードが壊れる場合は、とにかく次のいずれかを実行する必要があります。
各ヘッダーの依存関係をヘッダー ファイルに明示的に含めます。私の例では、に含める必要がありstdint.h
ますMyStruct.h
。
インクルード グループの間に、順序の依存関係を明示的に示すコメント行を追加します。非行#include
はグループを分割する必要があるため、コメント行も同様に機能することに注意してください。次のコードのコメント行も、標準ライブラリ ヘッダーの前にインクルードできないようにclang-format
します。MyStruct.h
代替オリジナル.c:
#include <stdint.h>
#include <stddef.h>
// must come after stdint.h
#include "MyStruct.h"
int main (int argc, char **argv) {
struct MyStruct s = { 0 };
return s.value;
}