如何在源代码中的特定行检查 GCC 预处理器定义

hyd*_*yde 5 macros gcc c-preprocessor

有没有办法在源文件中的某个点转储所有当前的预处理器定义?或者另一种检查源文件中两点之间预处理器指令更改的方法?

我在这里没有找到任何东西。这是一个给出这个想法的例子:

#define FOO

#pragma message "defines before whatever.h"
#pragma please_dump_all_defines
#include <whatever.h>
#pragma message "defines after whatever.h"
#pragma please_dump_all_defines

// rest of the file
Run Code Online (Sandbox Code Playgroud)

获取信息的另一种方式也可以使用,例如以gcc -E某种方式,只要考虑到FOO上述内容可能会影响包含文件的确切定义,并且可以跟踪多个#define/#undef等。

Mik*_*han 4

当然,GCC 预处理器不能完全满足您的要求,但它确实有一个-dCHARS选项,用于标志组合CHARS,您可以通过一些脚本来利用它来提取翻译单元中两点之间预处理器定义的更改。

我将用包含这两个文件的翻译单元进行说明:

foo.c

#define B 1
#define C 2
#pragma message Begin
#include "bar.h"
#pragma message End
#undef B
#undef C
#define B 4
#define C 5 
Run Code Online (Sandbox Code Playgroud)

酒吧.h

#ifndef BAR_H
#define BAR_H

#undef B
#undef C
#ifdef A
#define B 2
#define C 3
#endif

#endif
Run Code Online (Sandbox Code Playgroud)

调用:

cpp -dD foo.c
Run Code Online (Sandbox Code Playgroud)

-dD选项将#define|#undef指令保留在经过预处理的输出中。该输出有超过 500 行,所以我只引用有趣的尾部:

# 1 "<command-line>" 2
# 1 "foo.c"
#define B 1
#define C 2

# 3 "foo.c"
#pragma message Begin
# 3 "foo.c"

# 1 "bar.h" 1

#define BAR_H 

#undef B
#undef C
# 5 "foo.c" 2

# 5 "foo.c"
#pragma message End
# 5 "foo.c"

#undef B
#undef C
#define B 4
#define C 5
Run Code Online (Sandbox Code Playgroud)

或者,调用:

cpp -dD -DA foo.c
Run Code Online (Sandbox Code Playgroud)

相应的尾部(带有我的评论)是:

# 1 "<command-line>" 2
# 1 "foo.c"
#define B 1
#define C 2

# 3 "foo.c"
#pragma message Begin
# 3 "foo.c"

# 1 "bar.h" 1

#define BAR_H 

#undef B
#undef C

#define B 2     //<- New with -DA
#define C 3     //<- New with -DA
# 5 "foo.c" 2

# 5 "foo.c"
#pragma message End
# 5 "foo.c"

#undef B
#undef C
#define B 4
#define C 5
Run Code Online (Sandbox Code Playgroud)

脚本与此相关的是:

  • 1) 提取#define|#undef起始点标记 之前的指令,#pragma message Begin仅保留每个宏名称的滚动最新指令。
  • 2) 从起点到终点标记重复1) #pragma message End
  • 3) 按宏名称匹配两组并报告前后差异。

运气好的话,碰巧我需要把我的(从来都不是很光彩的)Python 上的蜘蛛网吹掉去面试,所以这里有一个脚本(只是粗略地调试过):

宏差异.py

#!/usr/bin/python

import sys, argparse, os, string, re, subprocess, shlex
from subprocess import call, CalledProcessError

class macro_directive:
    def __init__(self,directive = None,name = None,definition = None):
        self.__directive = directive
        self.__name = name
        self.__definition = definition
    def __eq__(self,other):
        return  self.__name == other.__name and \
                self.__directive == other.__directive and \
                self.__definition == other.__definition
    def __neq__(self,other):
        return not __eq__(self,other)
    @property
    def empty(self):
        return not self.__directive
    @property
    def directive(self):
        return self.__directive
    @property
    def name(self):
        return self.__name
    @property
    def definition(self):
        return self.__definition

    @property
    def desc(self):
        desc = self.__directive + ' ' + self.__name
        if self.__definition:
            desc += ' '
            desc += self.__definition
        return desc

    @staticmethod
    def read(line):
        match = re.match('^\s*#\s*(define|undef)\s+(\w+) \s*(.*)$',line)
        if match:
            directive = match.group(1)
            name = match.group(2)
            if directive == 'define':
                return macro_directive(directive,name,match.group(3))
            else:
                return macro_directive(directive,name)
        else:
            return macro_directive()
    @staticmethod
    def make_dict(lines):
        d = {}
        for line in lines:
            md = macro_directive.read(line);
            if not md.empty:
                d[md.name] = md
        return d


def find_marker(lines,marker):
    for i, line in enumerate(lines):
        if line.find(marker) == 0:
            return i;
    return -1

def split_by_marker(lines,marker):
    mark_i = find_marker(lines,marker)
    if mark_i != -1:
        return [lines[:mark_i],lines[mark_i:]]
    return [[],lines]

parser = argparse.ArgumentParser(
    prog="macrodiff",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description='Extract changes in simple preprocessor macro values between' +
        ' two marked points in a C/C++ translation unit. ' +
        'Function-like macros are not supported')
parser.add_argument('-s', '--start', metavar='STARTSTR',required=True,
    help='The initial macro values will be those in effect when the' +
        ' first line commencing with STARTSTR is read')
parser.add_argument('-e', '--end', metavar='ENDSTR',
    help='The final macro values will be those in effect when the first line' +
    ' commencing with ENDSTR is read, or if --end is not given then those' +
    ' in effect at end-of-file ')
parser.add_argument('--pp', default='cpp -dD',metavar='PP',
    help='PP is the preprocessor command to invoke. Default \'cpp -dD\'')
parser.add_argument('--ppflags',default='',metavar='PPFLAGS',
    help='PPFLAGS are additional options to be passed to PP')
parser.add_argument('infile',metavar='FILE',nargs=1,
    help='FILE is a C/C++ source file to be processed')

args = vars(parser.parse_args())
startstr = args['start'];
endstr = args['end'];
stdout = ''
command = args['pp'] + ' ' + args['ppflags'] + ' ' + args['infile'][0]

try:
    stdout = subprocess.check_output(shlex.split(command))
except CalledProcessError, e:
    sys.stderr.write( '***Error: Command \"' + command + '\" failed: \"' + \
        e.output + '\": ' + 'syscode = ' + str(e.returncode) + '\n')
    sys.exit(e.returncode)
lines = stdout.splitlines();
lines_before,lines_after = split_by_marker(lines,startstr);
if not lines_before:
    sys.stderr.write( '***Error: STARTSTR \"' + startstr + '\" not found\n')
    sys.exit(1)
if endstr:
    lines_after, ignore = split_by_marker(lines_after,endstr);
    if not lines_after:
        sys.stderr.write( '***Error: ENDSTR \"' + endstr + '\" not found\n')
        sys.exit(1)

directives_dict_before = macro_directive.make_dict(lines_before)
directives_dict_after = macro_directive.make_dict(lines_after)
intersection = \
    directives_dict_before.viewkeys() & directives_dict_after.viewkeys()

for key in intersection:
    before = directives_dict_before[key]
    after = directives_dict_after[key]
    if before != after:
        print 'BEFORE[' + before.desc + '] AFTER[' + after.desc +']'  

sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

用法

$ ./macrodiff.py -h
usage: macrodiff [-h] -s STARTSTR [-e ENDSTR] [--pp PP] [--ppflags PPFLAGS]
                    FILE

Extract changes in simple preprocessor macro values between two marked points in a C/C++ translation unit. Function-like macros are not supported

positional arguments:
  FILE                  FILE is a C/C++ source file to be processed

optional arguments:
  -h, --help            show this help message and exit
  -s STARTSTR, --start STARTSTR
                        The initial macro values will be those in effect when
                        the first line commencing with STARTSTR is read
  -e ENDSTR, --end ENDSTR
                        The final macro values will be those in effect when
                        the first line commencing with ENDSTR is read, or if
                        --end is not given then those in effect at end-of-file
  --pp PP               PP is the preprocessor command to invoke. Default 'cpp
                        -dD'
  --ppflags PPFLAGS     PPFLAGS are additional options to be passed to PP
Run Code Online (Sandbox Code Playgroud)

尝试使用以下方法:

$ ./macrodiff.py -s='#pragma message Begin' -e='#pragma message End' foo.c
Run Code Online (Sandbox Code Playgroud)

输出:

BEFORE[define C 2] AFTER[undef C]
BEFORE[define B 1] AFTER[undef B]
Run Code Online (Sandbox Code Playgroud)

或者:

$ ./macrodiff.py -s='#pragma message Begin' -e='#pragma message End' --ppflags='-DA' foo.c
Run Code Online (Sandbox Code Playgroud)

输出:

BEFORE[define C 2] AFTER[define C 3]
BEFORE[define B 1] AFTER[define B 2]
Run Code Online (Sandbox Code Playgroud)

或者:

$ ./macrodiff.py -s='#pragma message Begin' --ppflags='-DA' foo.c
Run Code Online (Sandbox Code Playgroud)

这次是在#pragma message Begin文件末尾和文件结尾之间进行差异。输出:

BEFORE[define C 2] AFTER[define C 5]
BEFORE[define B 1] AFTER[define B 4]
Run Code Online (Sandbox Code Playgroud)

如果您更愿意使用独特的注释而不是编译指示作为开始和结束标记,请添加-CPPFLAGS. 这将保留预处理输出中的注释,指令中的注释除外。

对类函数宏的支持留作练习。