clang-format配置与使用

2023-05-16

clang-format配置与使用

参考教程.

1. 安装

下载clang-format,设置环境变量。我使用的是vscode扩展中的clang-format

位于: extensions/ms-vscode.cpptools-1.7.0-insiders/bin/

将程序放置到系统边境变量的路径中,或者将软件路径添加到系统环境变量。

2. 配置

--style=指定配置文件。不指定将使用默认配置。默认情况下会先从当前目录寻找 .clang-format配置文件。这个配置有点弱智,难道就不能指定路径吗?

因此,自己定义的配置只能通过将.clang-format放置到需要格式化文件的路径下。因此,通过脚本或者程序的方式来复制配置文件到工作目录中。并在格式化完成后将其移除,这样可以不在工作目录下引入新的文件。

使用 Go来完成这个任务。(成功掌握可变参数和信道的使用-.-)

package main

import (
	"fmt"
	log "fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
)

func main() {

	clang_format_process(os.Args...)
}

func clang_format_process(args ...string) {
	conf_dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	work_dir, _ := os.Getwd()

	if conf_dir == work_dir {
		if os := runtime.GOOS; os == "linux" {
			conf_dir = filepath.Clean("/usr/local/sbin/clang_format_config.d")
		} else if os == "windows" {
			conf_dir = filepath.Clean("D:\\Program Files\\app")
		}
	}

	work_dir_config := filepath.Join(work_dir, ".clang-format")
	var config string = "config/.clang-format"
	conf_dir_config := filepath.Join(conf_dir, filepath.Clean(config)) /* 使用clean生成与平台无关的路径 */

	/* 根据不同的平台选择不同的格式化工具 */
	var tool_dir string
	switch os := runtime.GOOS; os {
	case "windows":
		tool_dir = filepath.Join(conf_dir, "bin/clang-format.exe")
	case "linux":
		tool_dir = filepath.Join(conf_dir, "bin/clang-format")
	}

	if _, err := os.Stat(tool_dir); err != nil {
		log.Println("Error: no such file: ", tool_dir)
		return
	}

	// is_custom := flag.Bool("nc", false, "custom argurement lists")
	// flag.Parse()
	if len(os.Args) <= 1 {
		log.Println("Usage: \nclang_format_custom file.c file1.c\nor clang_format_custom -nc (= clang-format[.exe] )")
		return
	}

	// 使用-cu参数,请删除true和修改os.Args[2:]
	if os.Args[1] != "-nc" {
		arg_pos := 1
		print_args(os.Args[1:]...)

		if _, err := os.Stat(work_dir_config); err == nil {
			log.Println(work_dir_config)
			log.Println(".clang-format has existed.")
			return
		}

		/* 复制配置文件当工作目录中 */
		if _, err := copy(conf_dir_config, work_dir_config); err != nil {
			log.Println(err)
		}

		ch := make(chan int)
		for _, arg := range os.Args[arg_pos:] {
			go clang_format_exec(ch, tool_dir, work_dir, arg)
		}

		// 阻塞在此,等待所有goroutine完成
		for i := arg_pos; i < len(os.Args); i++ {
			<-ch
		}
		os.Remove(work_dir_config)
		return
	} else {
		cmd := exec.Command(tool_dir, os.Args[2:]...) /* 不使用自定义参数时,直接调用clang-format */
		output, err := cmd.CombinedOutput()
		if err != nil {
			log.Println(err)
		}
		fmt.Print(string(output))
		return
	}
}

func print_args(args ...string) {
	log.Println("----------args list--------------")
	for _, arg := range args {
		log.Println(arg)
	}
	log.Println("-------------end-----------------")
}

func clang_format_exec(ch chan int, tool_dir, work_dir, file string) {
	log.Println("format ", file)
	cmd := exec.Command(tool_dir, "-i", file)
	err := cmd.Run()
	if err != nil {
		log.Println(err)
	}
	ch <- 1
}

func copy(src, dst string) (int64, error) {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return 0, err
	}
	if !sourceFileStat.Mode().IsRegular() {
		return 0, fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()

	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}

程序目录结构:

.
├── bin
│   ├── clang-format
│   └── clang-format.exe
├── clang_format_custom
├── clang_format_custom.exe
├── config
    ├── .clang-format
    └── .clang-format_backup

执行结果:

好了,宏定义对齐终于酸爽了。根据自己的喜好配置.clang-format配置文件。我的配置如下:

---
Language:        Cpp
# BasedOnStyle:  LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveMacros: true
AlignConsecutiveAssignments: true
AlignConsecutiveBitFields: true
AlignConsecutiveDeclarations: true
AlignEscapedNewlines: Right
AlignOperands:   Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: false
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
  AfterCaseLabel:  false
  AfterClass:      false
  AfterControlStatement: Never
  AfterEnum:       false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     false
  AfterUnion:      false
  AfterExternBlock: false
  BeforeCatch:     false
  BeforeElse:      false
  BeforeLambdaBody: false
  BeforeWhile:     false
  IndentBraces:    false
  SplitEmptyFunction: true
  SplitEmptyRecord: true
  SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit:     120
CommentPragmas:  '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat:   false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
  - foreach
  - Q_FOREACH
  - BOOST_FOREACH
IncludeBlocks:   Preserve
IncludeCategories:
  - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
    Priority:        2
    SortPriority:    0
  - Regex:           '^(<|"(gtest|gmock|isl|json)/)'
    Priority:        3
    SortPriority:    0
  - Regex:           '.*'
    Priority:        1
    SortPriority:    0
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentCaseLabels: false
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentExternBlock: AfterExternBlock
IndentWidth:     4
IndentWrappedFunctionNames: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd:   ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments:  true
SortIncludes:    true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles:  false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
Standard:        Latest
StatementMacros:
  - Q_UNUSED
  - QT_REQUIRE_VERSION
TabWidth:        4
UseCRLF:         false
UseTab:          Never
WhitespaceSensitiveMacros:
  - STRINGIZE
  - PP_STRINGIZE
  - BOOST_PP_STRINGIZE
...


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

clang-format配置与使用 的相关文章

随机推荐

  • 嵌入式 Rust 之书---第一章 引言

    目录 谁适合使用嵌入式Rust 范围 本书适用于谁 如何使用本书 为本书作贡献 1 1 了解你的硬件 1 2 一个no std的Rust环境 1 3 工具 1 4 安装工具 1 4 1 Linux 1 4 2 macOS 1 4 3 Win
  • 质心跟踪算法

    质心跟踪算法依赖于 xff08 1 xff09 现有对象质心 xff08 即 xff0c 质心跟踪器之前已经看到的对象 xff09 与 xff08 2 xff09 视频中后续帧之间的新对象质心之间的欧几里得距离 质心跟踪算法的主要假设是一个
  • 为什么我要刷leetcode!

    从今天开始我会每天坚持刷leetcode 为什么要这么做呢 xff1f 其实也是闲的哈哈哈哈 xff0c 被病毒困在家里那里也去不了 xff0c 那就不如来刷代码吧 xff01 其实不管是C 43 43 还是C还是java等各种各样的计算机
  • 标准模板库学习(5)----算法之非修正序列算法

    算法是STL的中枢 xff0c STL提供了算法库 xff0c 算法库都是模板函数 xff0c 主要分为四类 xff0c 非修正序列算法 修正序列算法 排序算法和数值算法 本文介绍非修正序列算法 adjacent find start en
  • Ubuntu中apt update和upgrade的区别

    原文链接 xff1a https blog csdn net CSDN duomaomao article details 77802673 简要说明 xff1a apt update xff1a 只检查 xff0c 不更新 xff08 已
  • Java中的信号量(Semaphore)

    初识Semaphore 信号量 xff0c 也可以称其为 信号灯 xff0c 它的存在就如同生活中的红绿灯一般 xff0c 用来控制车辆的通行 在程序员眼中 xff0c 线程就好比行驶的车辆 xff0c 程序员就可以通过信号量去指定线程是否
  • USB 2.0_ser!或者U232-P9 型USB转串Win7 32位或64位驱动 以及 USB转串串口序号查看和设置

    前几天叫同事在电脑城买了个USB转串数据线 xff0c 但是回来后在网上找了很多驱动都不行 觉得这个问题花了不少时间的 xff0c 我也拆开了 xff0c 打算按照芯片型号找驱动 xff0c 但是看不到芯片型号 现在终于找到合适的了 把这个
  • 《Java核心技术卷1》

    第3章 Java的基础程序设计结构 整型 用int类型表示一百万可以这么写 xff08 since 1 7 xff09 span class token keyword int span a span class token operato
  • voxl-flight quick start

    voxl flight 官方地址 xff1a https www modalai com 硬件及接口 两个版本 Snapdragon 821 xff1a 四核最高2 15GH xff0c GPU xff0c 2xDSP 视频支持 xff1a
  • 零基础如何学习优达学城的《无人驾驶入门》?

    因为感兴趣 xff0c 而且看好无人驾驶行业 xff0c 我学习了优达学城的 无人驾驶入门 课程 最近整理了无人驾驶领域的资料 xff0c 写成文章分享给大家 作为系列文章的第一篇 xff0c 我想介绍一下 无人驾驶入门 这门课 xff0c
  • realsense D435 标定(calibration)

    realsense D435 标定 文章目录 realsense D435 标定1 确定是否需要标定设备信息步骤操作打印标定目标开启标定程序 校正结果展示比较 文档 1 确定是否需要标定 工具 Depth Quality Tool 要求 将
  • 如何在linux执行PHP文件

    1 刚导入到linux系统中文件是没有可执行权 2 首先赋予文件可执行权限 chmod 43 x 文件名 例如 xff1a chomd 43 x czrkdjb php 如果要用 czrkdjb php执行 xff0c 需要在czrkdjb
  • 阿里P8大佬亲自讲解!写给程序员的Flutter详细教程,灵魂拷问

    我们程序员经常迷茫于有太多东西要学 xff0c 有些找不到方向 不知所措 很多程序员都愿意说 xff0c 我想变得更好 xff0c 但是更好是什么却很模糊 xff0c 同时我们又不知道该怎么样去做 我们的生命如此短暂 xff0c 作为程序员
  • VSCode 连接远程服务器使用图形化界面(GUI)

    1 基本环境 本地电脑系统 xff1a window10 远程服务器系统 xff1a Ubuntu18 04 2 VSCode版本 xff1a 1 51 1 2 问题描述 vscod提供了优秀的远程连接插件 xff08 Remote SSH
  • curl 命令大全及常用实例

    一 xff0c curl命令参数 a append 上传文件时 xff0c 附加到目标文件 A user agent lt string gt 设置用户代理发送给服务器 anyauth 可以使用 任何 身份验证方法 b cookie lt
  • 关于putty不能连接虚拟机的问题解决

    一 首先需要ping 一下 xff0c 看是否能ping通 xff0c 如果正常进入下一步 二 进入虚拟机终端输入 ssh localhost 如果提示 ssh connect to host localhost port 22 Conne
  • postman进行http接口测试

    HTTP的接口测试工具有很多 xff0c 可以进行http请求的方式也有很多 xff0c 但是可以直接拿来就用 xff0c 而且功能还支持的不错的 xff0c 我使用过的来讲 xff0c 还是postman比较上手 优点 xff1a 1 支
  • Linux系统迁移(将配置好的系统安装到其它电脑上)

    Linux系统迁移 说在前面 xff1a 下面有几个教程链接 xff0c 我都是通过这几个链接来完成的系统备份与系统恢复 并且遇到过一些问题 xff0c 踩过一些坑 建议先看完我的说明再进行操作 xff0c 少走弯路 没有图是因为下面分享的
  • 搭建 公网FTP服务器 外网访问

    我是在ubuntu 20 04 上配置的 xff0c 需要用到公网IP 没有公网IP的 xff0c 可以考虑花生壳这类应用来做内网穿透 1 配置FTP服务器 安装vsftpd sudo apt install vsftpd sudo vim
  • clang-format配置与使用

    clang format配置与使用 参考教程 1 安装 下载clang format xff0c 设置环境变量 我使用的是vscode扩展中的clang format 位于 xff1a extensions ms vscode cpptoo