how to find a search term in source code

前端 未结 3 1674
北荒
北荒 2020-11-30 14:54

I\'m looking for a way to search for a given term in a project\'s C/C++ code, while ignoring any occurrences in comments and strings.

As the code base is rather larg

3条回答
  •  情深已故
    2020-11-30 15:07

    IMHO there is a good answers on a similar question at "Unix & Linux":

    grep works on pure text and does not know anything about the underlying syntax of your C program. Therefore, in order not search inside comments you have several options:

    1. Strip C-comments before the search, you can do this using gcc -fpreprocessed -dD -E yourfile.c For details, please see Remove comments from C/C++ code

    2. Write/use some hacky half-working scripts like you have already found (e.g. they work by skipping lines starting with // or /*) in order to handle the details of all possible C/C++ comments (again, see the previous link for some scary testcases). Then you still may have false positives, but you do not have to preprocess anything.

    3. Use more advanced tools for doing "semantic search" in the code. I have found "coccigrep": http://home.regit.org/software/coccigrep/ This kind of tools allows search for some specific language statements (i.e. an update of a structure with given name) and certainly they drop the comments.

    https://unix.stackexchange.com/a/33136/158220

    Although it doesn't completely cover your "not in strings" requirement.

提交回复
热议问题