I have a function f
which is:
void f(int x, int y, int z){
//bla bla bla
}
and some other functions which use f
:
void g(int x, int y, int z){
f(x, 10, 10); //10, 10 are hard coded
}
void h(int x, int y){
f(x, y, 20); //20 is hard coded
}
IMPORTANT: f
is must stay private and hidden to other files.
Now, in the header file, I JUST write the prototypes of h
and g
. Everything is OK.
I decided to use #define
for h
& g
, cause it's much easier and more standard. So I removed the functions and wrote this on the header:
#define h(x) f(x, 10, 10)
#define g(x, y) f(x, y, 10)
The problem is, as you know, I have to write the prototype of f
in the header. f
must be private. Is there any way that I can use #define in this scenario at all? Like using #def
, #undef
, ...
I decided to use #define for h & g, cause it's much easier and more standard.
#define might be easier but it's not really more standard. As a matter of fact, it's error-prone and hard to debug. #define is usually used for faster processing as in contrary to function calls, it doesn't use RAM(stack) or processing time because it's simply replaced the compiler preprocessor.
With that established, it's fair to say #define is used when we want things to work faster.
For your purpose and because you want f() to stay private, there is another way by which you can accomplish that besides keeping things faster also, by using the inline
keyword.
static inline void f(int x, int y, int z){
//bla bla bla
}
the inline keyword instructs the compiler to optimize any call to f() usually by a code replacement as in #define. Note that inline functions are not necessarily inlined by the compiler. For more about that see http://www.greenend.org.uk/rjk/tech/inline.html
Although you don't have to create h & g as functions. You can do something like that:
static inline void f(int x, int y, int z){
//bla bla bla
}
void fInterface(int x, int y, int z){
f(x, y, z);
}
then in the header file:
void fInterface(int x, int y, int z); // Prototype
#define h(x) fInterface(x, 10, 10)
#define g(x, y) fInterface(x, y, 10)
This code will have almost the same performance as exporting f() itself.
Hope you find that helpful!