作为clang-format仅重新格式化代码的工具,这种格式化是否有可能破坏工作代码或至少改变它的工作方式?是否存在某种合同,它将/不能改变代码的工作方式?
我们有很多代码需要格式化clang-format.这意味着,许多代码行都会改变.不必审查由于a而仅更改的每一行代码clang-format都将是此过程的一个大的简化.
我会说这clang-format不会改变代码的工作方式.另一方面,如果可以保证,我不是百分百肯定.
Dao*_*Wen 56
该clang-format工具有一个-sort-includes选项.更改#include指令的顺序肯定会改变现有代码的行为,并可能破坏现有代码.
由于相应的SortIncludes选项true由多个内置样式设置,因此clang-format重新排序包含可能并不明显.
MyStruct.h:
struct MyStruct {
uint8_t value;
};
Run Code Online (Sandbox Code Playgroud)
original.c:
#include <stdint.h>
#include <stddef.h>
#include "MyStruct.h"
int main (int argc, char **argv) {
struct MyStruct s = { 0 };
return s.value;
}
Run Code Online (Sandbox Code Playgroud)
现在让我们说我们跑了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;
}
Run Code Online (Sandbox Code Playgroud)
由于头文件的重新排序,我在编译时遇到以下错误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.
Run Code Online (Sandbox Code Playgroud)
但是,这个问题应该很容易解决.您不太可能拥有这样的依赖于订单的包含,但如果您这样做,您可以通过在需要特定订单的标头组之间放置一个空行来解决问题,因为显然clang-format只对#include非指令组的指令组进行排序#include.之间.
固定original.c:
#include <stdint.h>
#include <stddef.h>
#include "MyStruct.h"
int main (int argc, char **argv) {
struct MyStruct s = { 0 };
return s.value;
}
Run Code Online (Sandbox Code Playgroud)
固定restyled.c:
#include <stddef.h>
#include <stdint.h>
#include "MyStruct.h"
int main(int argc, char **argv) {
struct MyStruct s = {0};
return s.value;
}
Run Code Online (Sandbox Code Playgroud)
请注意,stdint.h并stddef.h仍在重新排序因为它们包含仍然"分组",但防止新的空行MyStruct.h移动标准库中包括前.
如果重新排序您的#include指令会破坏您的代码,您可能应该执行以下操作之一:
明确包含头文件中每个头的依赖项.在我的例子,我需要包括stdint.h在MyStruct.h.
在显式声明排序依赖关系的包含组之间添加注释行.请记住,任何非#include线都应该分组,因此注释行也可以.以下代码中的注释行也阻止在标准库头之前clang-format包含MyStruct.h.
交替original.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;
}
Run Code Online (Sandbox Code Playgroud)
小智 9
当然,它可以改变代码的工作方式.原因是C程序可以查看其源代码的一些属性.我正在考虑的是__LINE__宏观,但我不确定没有其他方法.
考虑1.c:
#include <stdio.h>
int main(){printf("%d\n", __LINE__);}
Run Code Online (Sandbox Code Playgroud)
然后:
> clang 1.c -o 1.exe & 1.exe
2
Run Code Online (Sandbox Code Playgroud)
现在做一些clang-format:
> clang-format -style=Chromium 1.c >2.c
Run Code Online (Sandbox Code Playgroud)
并且2.c是:
#include <stdio.h>
int main() {
printf("%d\n", __LINE__);
}
Run Code Online (Sandbox Code Playgroud)
当然,输出已经改变:
> clang 2.c -o 2.exe & 2.exe
3
Run Code Online (Sandbox Code Playgroud)