views:

453

answers:

3

I am looking for an easy way to print out a specific function from within some C/C++ source code. For example, assume that test.c has several functions defined within it. I want to be able to print out the source code associated with only one of those functions.

Edit: Sorry, I should be a bit more clear about my end goal. I want the function printed to the screen so I can use wc to grab the word count of this specific function. Also, I want this be part of a command line tool-chain so it isn't an option to manually enter files and select the text.

A: 

I generally use the print-region (or preferably print-region-with-faces) from within emacs. However, it is not automated, I have to select the region by hand.

Works in other languages as well.


The following due to Tom Smith in the comments:

(defun print-fn (interactive) 
   (save-excursion (mark-defun) 
   (print-region)))

If you liked this, follow the link to Tom's user-page and see if he deserves your vote...


Making this CW, so I won't benefit from people voting up Tom's good thinking. Cheers.


Edit after clarification: This doesn't seem to be pointed at the OP's actual question. Alas.

dmckee
I am sure (without looking it up) that emacs c++ mode will include a mark-function command. Combining the two would easily yield a print-function command - untested emacs-lisp:(defun print-fn (interactive) (save-excursion (mark-function) (print-region)))
Tom Smith
Looks like they used the existing "mark-defun".
dmckee
A: 

What is your end goal with printing out a function?

Do you want to use this as such:

if (error == Foo())
{
    PrintFunction(foo);
    exit(1);
}

There are easier ways to output where errors are. I could maybe help more if I had a better idea of the problem you are trying to solve with this.

For a idea of how to implement such a PrintFunction():

  1. Have a data struct that wraps around a function and contains: function line start, function line end, and maybe a pointer to the function.
  2. Write a function that prints out a line base on number of the source file. __FILE__ gives you the source file name.
  3. With knowing the start and end of where the function lies in the code, printing the function would be trivial.

This has an annoying pitfall of needing to update the line numbers of where your function lies in the file. But this could maybe be solved with a macro.

lillq
+1  A: 

You can run your project through Doxygen. It will index all your functions (and classes, structs etc) and can make them available in multiple formats (including PDF and HTML, both easily printable).

codelogic