How to add print statements in every function in c

2019-06-17 18:33发布

I am working on embedded code and for now totally reliant on prints from within functions to figure out the flow of execution (there is no stack trace functionality available).

It often happens that I put a bunch of print statements, build my code and run it only to realize I should've put prints in a dozen other places too. And then start the hour long process again.

Is there an easy way to take my 5 or 6 c files that I want to analyze and run some tool that will go in and add a print statement in each function? (this will obviously have to be after the variable declarations as this is in C)

Even better would be to have a print each time there is an if/ else or switch/ case ..basically any conditional statements.

5条回答
迷人小祖宗
2楼-- · 2019-06-17 19:03

For only 5-6 files I would manually go in and add a PRINT("name of function") macro in each function and then define that to either output the string, or nothing

You could use ctags to analyse the files and build this automatically but unless you have 100s of files it would be quicker to just do it by hand

查看更多
放我归山
3楼-- · 2019-06-17 19:11

You don't state the compiler you are using, but gcc has a very handy switch:

-finstrument-functions

which inserts a special call at each function entry and exit. You could compile only the relevant files with this tweak, no need to modify the source code.

The calls are made to two functions you should create:

      void __cyg_profile_func_enter (void *this_fn,
                                     void *call_site);
      void __cyg_profile_func_exit  (void *this_fn,
                                     void *call_site);

Etrace is a tool designed for exploiting this to create call traces, see http://ndevilla.free.fr/etrace/

查看更多
smile是对你的礼貌
4楼-- · 2019-06-17 19:18

you can use macros like this

 #define begin {printf(__func__##" Started");
 #define end printf(__func__##" Ended");}

and then replace all your {,} with begin and end macros (__func__ is a macro which return function name and is defined in C99 there are also other equvalent macros for other compilers)

查看更多
等我变得足够好
5楼-- · 2019-06-17 19:25

I would recommend you using a debugger, like GBD. That way you can even run your program "step by step" and analyze such conditions. I don't see a reason to print something in every function.

查看更多
太酷不给撩
6楼-- · 2019-06-17 19:26

If vim is your favourite editor you can install this plugin: http://www.vim.org/scripts/script.php?script_id=213 and customize the related template. Can be useful for a lot of differents tasks. (It works for the new functions that you will define, that is not your case but might be useful for future use)

查看更多
登录 后发表回答