Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code Ordering in Source Files - Forward Declarations vs "Don't Repeat Yourself"? [closed]

Tags:

c

coding-style

If you code in C and configure your compiler to insist that all functions are declared before they are used (or if you code in C++), then you can end up with one of (at least) two organizations for your source files.

Either:

  • Headers
  • Forward declarations of (static) functions in this file
  • External functions (primary entry points)
  • Static - non-public - functions

Or:

  • Headers
  • Static - non-public - functions
  • External functions (primary entry points)

I recognize that in C++, the term 'static' is not preferred, but I'm primarily a C programmer and the equivalent concept exists in C++, namely functions in an anonymous namespace within the file.

Question:

  • Which organization do you use, and why do you prefer it?

For reference, my own code uses the second format so that the static functions are defined before they are used, so that there is no need to both declare them and define them, which saves on having the information about the function interfaces written out twice - which, in turn, reduces (marginally) the overhead when an internal interface needs to change. The downside to that is that the first functions defined in the file are the lowest-level routines - the ones that are called by functions defined later in the file - so rather than having the most important code at the top, it is nearer the bottom of the file. How much does it matter to you?

I assume that all externally accessible functions are declared in headers, and that this form of repetition is necessary - I don't think that should be controversial.

like image 616
Jonathan Leffler Avatar asked Dec 09 '22 22:12

Jonathan Leffler


1 Answers

I've always used method #1, the reason being that I like to be able to quickly tell which functions are defined in a particular file and see their signatures all in one place. I don't find the argument of having to change the prototypes along with the function definition particularly convincing since you usually wind up changing all the code that calls the changed functions anyway, changing the function prototypes while you are at it seems relatively trivial.

like image 148
Robert Gamble Avatar answered Jan 18 '23 23:01

Robert Gamble