将头文件#ifndef添加到当前目录中的C头文件中

时间:2016-08-04 22:30:51

标签: python c shell c-preprocessor

在当前目录中,所有C头文件(* .h)不包含预处理器宏

#ifndef FILENAME_H
#define FILENAME_H
...
#endif

,手动将它们添加到每个标题中太繁琐了。如何通过python或shell自动完成?

4 个答案:

答案 0 :(得分:2)

根据Cody的回答,我实施了guardHeader.py:

  1 #!/usr/bin/python3
  2
  3 import glob,os,sys
  4
  5 global search_dir
  6
  7 def clearContent(pfile):
  8     pfile.seek(0)
  9     pfile.truncate()
 10
 11 def guard(fileName):
 12     file = open(fileName, 'r+')
 13     content = file.read()
 14
 15     fileNameUp = fileName.split(".")[0].upper() + '_H'
 16     guardBegin = '#ifndef ' + fileNameUp + '\n'    \
 17             '#define ' + fileNameUp + '\n\n'
 18     guardEnd = '\n#endif'
 19     newContent = guardBegin + content + guardEnd
 20
 21     clearContent(file)
 22     file.write(newContent)
 23
 24 if __name__ == '__main__':
 25     if len(sys.argv) == 1:
 26         print('Please provide a directory')
 27     else:
 28         search_dir = sys.argv[1]
 29
 30     # enter search directory
 31     os.chdir(search_dir)
 32
 33     for file in glob.glob("*.h"):
 34         guard(file)

答案 1 :(得分:1)

假设您在unix个shell中,findcutsed可用。您可以使用find获取每个文件名,然后使用sed更改这些文件。

您可以将以下脚本保存在名为addifndef.sh的文件中。

  for fn in $(find . -maxdepth 1 -type f -regex '.*\.h$' | cut -f 2 -d '/'); 
  do 
     dn=$(echo $fn | cut -f 1 -d '.');
     sed -i  -e "1 i#ifndef ${dn}_H\n#define ${dn}_H" -e "$ a#endif" "$fn";  
  done

然后,在shell提示符下将该脚本作为[prompt $] sh addifndef.sh运行。

或者,您可以在命令行中直接使用此命令。

有关详细信息,您必须查看man pages findcutsed的{​​{1}}。

答案 2 :(得分:1)

我要去看第二张@ kaylum的建议而且也没有给你全部的东西,但这里有一些伪代码可能会让你走上正确的道路

for each file in the directory
   if filename doesn't end with .h
      continue
   open the file
   store its contents in a variable
   create the header guard by taking the filename, removing the '.', and replacing it with a '_'
   create new contents = headerGuard + contents + "\n#endif"
   write file back out to the same name

这些内容中的每一项都应该通过快速谷歌/堆栈溢出搜索来回答,如果你无法找出任何这些部分,那么关于该位的特定堆栈溢出问题将更适合这个站点。 And here is one link to a relevant question to get you started.

答案 3 :(得分:0)

这是一个完成任务的小脚本:https://gist.github.com/rumpeltux/9e4a3e6e8ccd4c0c86770ca4f2afc1d0

wget https://gist.github.com/rumpeltux/9e4a3e6e8ccd4c0c86770ca4f2afc1d0/raw/auto_add_headers.sh

find -name \*.h | xargs sh auto_add_headers.sh
相关问题