Roger Zhang
Roger Zhang

Reputation: 53

Get all the functions' names from c/cpp files

For example, there is a C file a.c, there are three functions in this file: funA(), funB() and funC().

I want to get all the function names from this file.

Additionally, I also want to get the start line number and end line number of each function.

Is there any solution?

Can I use clang to implement it?

Upvotes: 4

Views: 6996

Answers (3)

AmrShams07
AmrShams07

Reputation: 493

you can use ctags which is pretty simple and straight forward. you can run ctags like

ctags -x --c-kinds=f

this will output the tags(function names)

Upvotes: 5

David C. Rankin
David C. Rankin

Reputation: 84521

One solution that works well for the job is cproto. It will scan source files (in K&R or ANSI-C format) and output the function prototypes. You can process entire directories of source files with a find command similar to:

find "$dirname" -type f -name "*.c" \
-exec /path/to/cproto -s \
-I/path/to/extra/includes '{}' >> "$outputfile" \;

While the cproto project is no longer actively developed, the cproto application continues to work very, very well. It provides function output in a reasonable form that can be fairly easily parsed/formatted as you desire.

Note: this is just one option based on my use. There are many others available.

Upvotes: 3

Chris VanWyk
Chris VanWyk

Reputation: 93

You can compile the file and use nm http://en.wikipedia.org/wiki/Nm_(Unix) on the generated binary. You can then just parse the output of nm to get the function names.

If you want to get line numbers, you can use the function names to parse the source file for line numbers.

All the this can be accomplished with a short perl script that makes system calls to gcc and nm.

This is assuming you are using a *nix system of course...

Upvotes: 5

Related Questions