7
I usually divide the program into small modules, each with its own header and implementation. In general, the abstraction level used allows the implementation to be completely changed without breaking the rest of the code that depends on the module.
In some benchmarks I ran using Callgrind, implementing the functions of a module widely used also in the header produced considerable gains in performance. In these cases I did the following:
module. h
#include <stdlib.h> //cabecalhos necessários
#ifndef MODULO_IMPLEMENTACAO
inline int funcao1(int x, int y)
{
//código
}
inline int funcao2(int x, int y, double z)
{
//código
}
#endif
module. c
#define MODULO_IMPLEMENTACAO
#include "modulo.h"
extern inline int funcao1(int x, int y)
{
//código
}
extern inline int funcao2(int x, int y, double z)
{
//código
}
If I understand correctly, the problems of this approach are the fact that I have to recompile all the files that depend on the module in question if the implementation changes, the fact that it takes longer to compile, and the creation of functions that before would not exist - the ones that were declared static
and inline implementads by compiler.
Is there any other disadvantage in this practice? When implementing the functions in the header?
I would include just the header in
main.c
.modulo.c
is a file containing functions in case the compiler decides not to implement inline, http://stackoverflow.com/a/216546/2264920 (C99)– 2013Asker
@Douglas, it’s not necessary. The compiler will always include header definitions in all files that include it (duplicates and unused ones are removed by Linker later). In your case you don’t even need to have the
modulo.c
.– Guilherme Bernal
but what about the definition provided on that link, is it incorrect or not understood correctly? What if the compiler decides to call an external function instead of implementing inline? " inline": no externally Visible Function is Emitted, but one Might be called and so must exist.
– 2013Asker
Another point that can be raised is that they only need to be declared in files . h functions that you want to reuse in other modules. If the function is "private" from that module it can stay only in the file . c/. cpp and be declared as
inline
if appropriate.– C. E. Gesser
The true function of
inline
is to suppress duplicate function definition errors in Linker step and thus allow writing it in headers. The compiler is completely free to decide whether or not to apply optimization to any function you find.– Guilherme Bernal