0

プリプロセッサを次のようにインデントしたい:

int foo_func()
{
    normal_code();
    normal_code();
#ifdef FOO
#  define aaa
#  define bbb
    code_that_only_foo();
    code_that_only_foo();
#endif
    normal_code_again();
    normal_code_again();
}

clang-formatを試しましたが、ディレクティブの後にすべてのスペースが削除#され、その動作を制御するオプションが見つかりませんでした。では、clang-format はそのようにプリプロセッサのインデントを実行できますか?

4

1 に答える 1

0

その仕事をするツールが見つからない場合は、次のようなツールを作成してください。

#!/usr/bin/env python3

from sys import stdin
from string import whitespace


def main():
    not_directive = whitespace + '#'
    indentation = 0
    for line in stdin:
        stripped = line.lstrip()
        if stripped.startswith('#'):
            directive = stripped.lstrip(not_directive)
            if directive.startswith('endif'):
                indentation -= 1
            print('#{}{}'.format('  ' * indentation, directive), end='')
            if directive.startswith('if'):
                indentation += 1
        else:
            print(line, end='')


if __name__ == '__main__':
    main()

オンラインでの動作を確認する

stdin からソースを読み取り、変更されたソースを stdout に書き込みます。
シェルで入出力を簡単にリダイレクトできます。

Python3 を知らず、理解したい場合:

  • string.lstrip(chars)最初から削除されてstring戻ります。デフォルトはです。chars
    charswhitespace
  • 'test' * 0=> '''test' * 1=> 'test''test' * 3=>'testtesttest'
  • '#{}{}'.format('textA', 'textB')=>'#textAtextB'
于 2015-12-30T16:02:28.870 に答える