There are many ways to do this. One way involves building a search regex from a simply formatted list of functions. The list can be easily modified by hand, and the generated regex can be used to search for the specified C functions in a text file that is processed line-by-line. The following example code demonstrates this:
cfsearch.prl
#!/usr/bin/perl
# List of C functions to search for my @search_list = ( “on_foo()”, “on_bar(arg)” );
# Build a regex to search for any of the functions my $search_regex = “\^\[ \\t\]*(“; foreach my $item (@search_list) { my $item_regex = quotemeta($item); $item_regex =~ s/arg/[ \\t]*[a-zA-Z0-9_]+[ \\t]*/g; $search_regex .= “$item_regex|”; } chop($search_regex); $search_regex .= “)”;
# Parse the input file line by line searching for function calls my $line_index = 0; if (open my $file, “<$ARGV[0]”) { while (my $line = <$file>) { $line_index++; if ($line =~ /$search_regex/) { print “found ‘$1‘ on line $line_index\n”; } } } |
cfsearch_test.c
#include <stdio.h>
// Test file for cfsearch.prl // Expected Result: // > perl cfsearch.prl cfsearch_test.c // > found ‘on_foo()’ on line 22 // > found ‘on_bar(12)’ on line 23 // >
void on_foo() { printf(“Foo was here\n”); }
void on_bar(int index) { printf(“Bar #%d was here\n”, index); }
int main() { on_foo(); on_bar(12); return 0; } |
The Perl code (cfsearch.prl) first defines a list of C functions to search for. To keep the list simple, the word ‘arg’ is used in place of actual arguments. The next block iterates through the list and generates a regex that will match the function calls. The quotemeta is required to quote the parenthesis which need to be matched exactly in the regex. The replacement replaces each instance of ‘arg’ with a regex that will match a C-style function argument. The regex for each function is separated by ‘|’ so the regex will match any one of them. The last code block parses an input file line-by-line and tries to match the regex to each line. If the line matches, it prints the function and line number.