在Clang工具的帮助下创建C/C++代码格式化工具

2021年5月13日16:37:05 发表评论 868 次浏览

今天, 我们将讨论按用户扩展名格式化用户工作区中的文件的方式。为此, 我们将使用Clang的格式工具。

先决条件:

  • Linux机器
  • python
  • lang工具

设定:

  • 使用以下命令安装Python:
    sudo apt-get install python
  • 安装Clang格式工具
    sudo apt-get install clang-format-3.5
  • 在你具有读写权限的任何位置创建一个名为format-code.py的python文件。在此示例中, 我们将在/ home / user /中创建它。它应包含以下代码: # Python program to format C/C++ files using clang-format import os # File Extension filter. You can add new extension cpp_extensions = ( ".cxx" , ".cpp" , ".c" , ".hxx" , ".hh" , ".cc" , ".hpp" ) # Set the current working directory for scanning c/c++ sources (including # header files) and apply the clang formatting # Please note "-style" is for standard style options # and "-i" is in-place editing for root, dirs, files in os.walk(os.getcwd()): for file in files: if file .endswith(cpp_extensions): os.system( "clang-format-3.5 -i -style=file " + root + "/" + file )
  • 创建格式规范文件并将其复制到项目的顶级目录, 例如/ home / user / myproject /
    1. 创建格式文件(例如, 我们正在创建Google编码样式工具)
      clang-format-3.5 -style=google -dump-config > .clang-format 
    2. 将其复制到项目的目录, 即其位置变为:/home/user/myproject/.clang-format

如何使用它?

导航到要格式化其文件的目录, 例如cd/home/user/myproject/c-source /

运行你先前创建的格式代码文件python /home/user/format-code.py

这将格式化我们源代码目录中的所有文件, 其扩展名与代码中提到的扩展名相同。

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: