vim autowrite functions in header file. C lang - c

I tried to use vim for c program editing. Is there a way to auto write function skeleton defined in header file?
situations like
"my_code.h"
int temp(int*);
and "my_code.c"
<<< here auto write >>> like
int temp(int*) { return }
int main()
{
}
I'm using c.vim plug-in. I tried to find it, but I couldn't make it.

There are code completion scripts, yes.. However, this is not something you generally want. It works for simple things like basic C functions, and fails horribly beyond that (i.e. templates etc in c++). You don't save any time by using such plugins, and mastering vim motion/yank/paste commands provide the same result in the same amount of time, and you become more familiar with a modal editor. Is it that hard to copy-paste the function prototype and add some braces {/}?
If you want something to help as a reminder to write function definitions to go with function prototypes, consider using the taglist plugin.

snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.
There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.
Additionally, there are also template plugins that pre-initialize a new, empty file with a skeleton, often including a file header and copyright statement. Search vim.org; you'll find plenty.

I've have a :GOTOIMPL command in lh-cpp that generates an empty function definition from a function declaration.
However, you'll have to execute the command on each function declaration and go back to the header file. I've never took the time to batch the process from an header file and no implementation file -- as this is not a use case I have as there exist other solutions...
IOW... there exist projects that do the job from the command-line (and which you could call from vim then) (like for instance https://github.com/Davidbrcz/header-expander), or even other plugins (like protodef: http://www.vim.org/scripts/script.php?script_id=2624).

Related

what is the purpose of UVM automation macro?

I'm trying to understand about UVM automation macro.
among other things, i found some sentence "UVM system Verilog call library also includes macros that automatically implement the print, copy, clone, compare, pack and unpack methods and more" from text.
and I found that lots of example used with the following usage.
For example,
....
uvm_object_utils_begin(apb_transfer)
'uvm_field_int(addr, UVM_DEFAULT)
'uvm_field_int(data, UVM_DEFAULT)
...
uvm_object_utils_end
but I didn't get it. that usage of 'uvm_field_int() is just defining the variable not copy, clone, compare....
How do I understand what uvm automation macro to do?
even I also curious about why those things are named as a automation? I can't find any something auto kind of thing.
As you say, the UVM field automation macros generate a number of class utility methods such as copy, print and clone that include the registered fields. That's it. I guess the name "automation" is used, because they automatically write code so you don't have to.
My company (Doulos) recommends you don't use these macros useless you know what you're doing. This is because they can be hard to debug, can generate more code than you need and have a strange side effect (values can be read from the configuration database automatically without your knowledge). Of course, the advantage of using them is that you get a whole bunch of code for free - the copy, compare,, print methods etc.
The HTML documentation supplied with a UVM download is very good. Search for `uvm_object_utils and follow your nose.

C struct introspection at runtime

Is there a facility for the C language that allows run-time struct introspection?
The context is this:
I've got a daemon that responds to external events, and for each event we carry around an execution context struct (the "context"). The context is big and messy, and contains references to all sorts of state.
Once the event has been handled, I would like to be able to run the context through a filter, and if it matches some set of criteria, drop a log message to help with debugging. However, since I hope to use this for field debugging, I won't know what criteria will be useful to filter on until run time.
My ideal solution would allow the user to, essentially, write a C-style boolean expression and have the program use that. Something like:
activate_filter context.response_time > 4.2 && context.event.event_type == foo_event
Ideas that have been tossed around so far include:
Providing a limited set of fields that we know how to access.
Wrapping all the relevant structs in some sort of macro that generates introspection tools at run time.
Writing a python script that knows where (versioned) headers live, generates C code and compiles it to a dll, which the daemon then loads and uses as a filter. Obviously this approach has some extra security considerations.
Before I start in on some crazy design goose chase, does anyone know of examples of this sort of thing in the wild? I've dome some googling but haven't come up with much.
I would also suggest tackling this issue from another angle. The key words in your question are:
The context is big and messy
And that's where the issue is. Once you clean this up, you'll probably be able to come up with a clean logging facility.
Consider redefining all the fields in your context struct in some easy, pliable format, like XML. A simple `XML schema, that lists all the members of the struct, their types, and maybe some other metadata, even a comment that documents this field.
Then, throw together a quick and dirty stylesheet that reads the XML file and generates a compilable C struct, that your code actually uses. Then, a different stylesheet that cranks out robo-generated code that enumerates each field in the struct, and generates the code to convert each field into a string.
From that, bolting on a logging facility of some kind, with a user-provided filtering string becomes an easier task. You do have to come up with some way of parsing an arbitrary filtering string. Knowledge of lex and yacc would come in handy.
Things of this nature have been done before.
The XCB library is a C client library for the X11 protocol. The protocol defines various kinds of binary messages which are essentially simple structs that the client and the server toss to each other, over a socket. The way that libxcb is implemented, is that all X11 messages and all datatypes inside them are described in an XML definition, and a stylesheet robo-generates C struct definitions, and the code to parse them out, and provide a fairly clean C API to parse and generate X11 messages.
You are probably approaching this problem from a wrong side.
Logging is typically used to facilitate debugging. The program writes all sorts of events to a log file. To extract interesting entries filtering is applied to the log file.
Sometimes a program generates just too much events; logging libraries usually address this issues by offering verbosity control. Basically a logging function takes an additional parameter telling the verbosity level of the current message. If the value is above the globally configured threshold the message gets discarded. Some libraries even allow to control verbosity level on a per-module basis (Ex: google log).
Another possible approach is to leverage the power of a debugger since the debugger has access to all sorts of meta information. One can create a conditional breakpoint testing variables in scope for arbitrary conditions. Once the program stops any information could be extracted from the scope. This can be automated using scripting facilities provided by a debugger (gdb has great ones).
Finally there are tools generating glue code to use C libraries from scripting languages. One example is SWIG. It analyzes a header file and generates code allowing a scripting language to invoke functions, access structure fields, etc.
Your filter expression will become a program in, say, Lua (other scripting languages are supported as well). You invoke this program passing in the pointer to execution context struct (the "context"). Thanks to the accessors generated by SWIG Lua program can examine any field in the structure.
I generated introspection out of SWIG-CSV parser.
Suppose the C code contains structure like the following,
class Bike {
public:
int color; // color of the bike
int gearCount; // number of configurable gear
Bike() {
// bla bla
}
~Bike() {
// bla bla
}
void operate() {
// bla bla
}
};
Then it will generate the following CSV metadata,
Bike|color|int|variable|public|
Bike|gearCount|int|variable|public|
Bike|operate|void|function|public|f().
Now it is easy to parse the CSV file with python or C/C++ if needed.
import csv
with open('bike.csv', 'rb') as csvfile:
bike_metadata = csv.reader(csvfile, delimiter='|')
# do your thing

Why would C files end in /*[]*/

I am looking through some proprietary source code: sample programs in using a library.
The code is written in C and C++, using make for build system.
Each and every file ends in a commented out []: /*[]*/ for source files and #[]# for makefiles. What could be the reason for this?
The code is compiled for ARM with GCC, using extensions.
It is most likely a place holder for some sort of automatic expansion.
Typically something like macrodef (or one of the source code control filters) would expand such items to contain some relevant text. As typically only the comment-protected brackets would expand, the comments would remain in place, protecting the source code from actual expanded items at compilation time.
However, what you are currently looking at is probably the outer containing brackets with all of the internal expansions removed. This may have been done during a code migration from one source code control system to another. Although such an idea is highly speculative, it does not appear that they took the effort to migrate expansion items, instead of just removing them.
On one project I used to work, every C source file contained a comment at the very end:
/* End of file */
The reason for that was the gcc warning
Warning : No new line at end of file
So we had this comment (with a new line after it) to be sure people do not write after the comment :)

How can I jump to function when doing C development in Emacs?

I am doing C development in Emacs. If I have a source file open with multiple functions and "the marker" is at a function call e.g. int n = get_number(arg); is there any way I can "jump to" the implementation of that function? e.g. to int get_number(int *arg) { ... }
I have done some Java development in Eclipse and is missing this functionallity, because I'm not that used to Emacs but I would like to learn.
You have to create a tag file.
Under Unix, you have the etags program that understands the syntax of C, C++, Java... and that create a tag file that can be used by Emacs.
This rather old page (2004) provides more information.
To jump to a function use M-. (that’s Meta-Period) and type the name of the function. If you
simply press enter Emacs will jump to the function declaration that matches the word under
the cursor.
There are several "tags" systems which allows that (there is one bundled with emacs, there is GNU global which isn't bundled with emacs but integrate well with it and has some advantages). Compared with Eclipse, you'll need to build the tags file.
Then there is semantic/EDE which is now bundled with emacs which should provide a solution without needing to build a database explicitly. I've not tried to use it recently. When I did, it has performance problem and I found the set up was painful. (Both possibly due to the fact that I'm working on a big -- several 10's millions lines -- and old -- some things date back to the mid 80's -- project without the possibility of reorganizing it).
I think semantic-mode should do you the same result. Although I haven't tried to jump to another file, but in one file it's very excellent. Go to a variable, issue keystroke C-c,j, it will jump to the definition of the variable. Go back to previous line using C-uC-space. To display reference to the symbol, use keystroke C-c,g
It really helps me.
I haven't tried it to jump to another file, because my current project is a modified Java program, where we are using preprocessor (a non standard java process). So I think that is where the problem lies.
Anyone success with semantic-mode???
thanks
I really like cscope for this, but etags probably works as well.

How to implement standard C function extraction?

I have a "a pain in the a$$" task to extract/parse all standard C functions that were called in the main() function. Ex: printf, fseek, etc...
Currently, my only plan is to read each line inside the main() and search if a standard C functions exists by checking the list of standard C functions that I will also be defining (#define CFUNCTIONS "printf...")
As you know there are so many standard C functions, so defining all of them will be so annoying.
Any idea on how can I check if a string is a standard C functions?
If you have heard of cscope, try looking into the database it generates. There are instructions available at the cscope front end to list out all the functions that a given function has called.
If you look at the list of the calls from main(), you should be able to narrow down your work considerably.
If you have to parse by hand, I suggest starting with the included standard headers. They should give you a decent idea about which functions could you expect to see in main().
Either way, the work sounds non-trivial and interesting.
Parsing C source code seems simple at first blush, but as others have pointed out, the possibility of a programmer getting far off the leash by using #defines and #includes is rather common. Unless it is known that the specific program to be parsed is mild-mannered with respect to text substitution, the complexity of parsing arbitrary C source code is considerable.
Consider the less used, but far more effective tactic of parsing the object module. Compile the source module, but do not link it. To further simplify, reprocess the file containing main to remove all other functions, but leave declarations in their places.
Depending on the requirements, there are two ways to complete the task:
Write a program which opens the object module and iterates through the external reference symbol table. If the symbol matches one of the interesting function names, list it. Many platforms have library functions for parsing an object module.
Write a command file or script which uses the developer tools to examine object modules. For example, on Linux, the command nm lists external references with a U.
The task may look simple at first but in order to be really 100% sure you would need to parse the C-file. It is not sufficient to just look for the name, you need to know the context as well i.e. when to check the id, first when you have determined that the id is a function you can check if it is a standard c-runtime function.
(plus I guess it makes the task more interesting :-)
I don't think there's any way around having to define a list of standard C functions to accomplish your task. But it's even more annoying than that -- consider macros,
for example:
#define OUTPUT(foo) printf("%s\n",foo)
main()
{
OUTPUT("Ha ha!\n");
}
So you'll probably want to run your code through the preprocessor before checking
which functions are called from main(). Then you might have cases like this:
some_func("This might look like a call to fclose(fp), but surprise!\n");
So you'll probably need a full-blown parser to do this rigorously, since string literals
may span multiple lines.
I won't bring up trigraphs...that would just be pointless sadism. :-) Anyway, good luck, and happy coding!

Resources