Wei Shi
Wei Shi

Reputation: 5055

Reorder function in c file based on c header file

Is there any tool to automatically reorder the .c file based on .h?

For example, foo.h

void function1();
void function2();
void function3();

And foo.c

void function2(){}
void function1(){}
void function3(){}

Can I reorder it as

void function1(){}
void function2(){}
void function3(){}

By the way, I'm using Vim in Ubuntu.

Upvotes: 14

Views: 606

Answers (1)

Randall Cook
Randall Cook

Reputation: 6776

I don't believe there is such a tool. In C, order of declaration and definition generally does not matter. There is of course the exception of a dependency loop (a() calls b() which calls a()), but when functions are declared in a header file, even this is not a problem, since all the declarations are effectively the "forward" declarations needed to handle dependency loops.

Thus the order of definitions in a translation unit is essentially a matter of taste and style. As such, it is not a feature that editor designers are apt to address, since the effort to create features general and powerful enough to be worthwhile to a preponderance of users may be deemed to be prohibitively large. Think how long it took for (non-programmable) editors to commonly have flexible and powerful automatic indentation and reformatting features.

There is also risk of breaking the logic, grammar, or readability of code when it is reorganized automatically. For example, if comments lie between function definitions, how will the tool know if a comment goes with a particular function, or with a group of functions, or with the function above? And as @Yuri mentions above, what about functions inside #if/#else/#endif blocks? And what about subtle cases like macros that expand to functions or #include directives sandwiched between function definitions? I suppose a reordering feature could restrict its domain to a simple case, but if the case gets too simple, its appeal is correspondingly limited, and it doesn't get released publicly or widely.

All that being said, I think with a rich toolset at your disposal, such a feature would not be too hard to implement, though if I were doing it, I expect that at the first unanticipated difficulty, I would find myself wondering if it wouldn't be easier to just edit the source files by hand. Multiline cut and paste is pretty easy, after all.

Upvotes: 2

Related Questions