For code modularity I like to subdivide long functions into a few smaller ones like so
void main_function() {
step_1();
step_2();
}
static inline void step_1() {
// code
}
static inline void step_2() {
// code
}
For readability reasons I like those smaller sub-functions to follow the main one from which they are called. But C++ compiler will not allow that and I have to precede this code with declarations
static inline void step_1();
static inline void step_2();
which seems wasteful in this case since those sub-functions are file-private (even main_function
-private I would say, but C++ compiler doesn’t allow to declare static
functions inside functions for some reason).
Basically I hope if maybe there are some compiler flag which allows to call any function from any other function as long as they both defined in the same file? This issue always seemed to me as such an ugly meaningless inconvenience of the language. I don’t understand why they keep it this way?
3
C++ simply does not allow a function to be called before it is declared. Unlike C, which does allow it.
So, if you want your function definitions to appear after the main function, then you must forward-declare them.
1
I would advise you just to accept that C++ wants them in the order C++ wants them in. You might slightly prefer the aesthetics of the functions being in the other order, but since the compiler cares about the order it’s easier to just do what the compiler wants and move on with your life. Either put the inner functions earlier in the file or forward-declare them.
Even if you find a workaround, that workaround is likely to be unexpected by other people who read your code: doing unexpected things is way worse for readability than having functions appear in an order you don’t think is ideal.
As a side note, your “file-private” functions should probably be in an anonymous namespace these days rather than declared as static
.
1