How can I define the function body in a .h file?
Sometimes I define bodies of small global functions in .h files (static inline). It works.
Now I have larger global func开发者_Python百科tion. I need to to define it in .h file. I do not want it to be static inline. I tried the following trick with "dummy template":
template <typename Tunused> int myfunction(...) {
...
}
to achieve this -- to define global function in .h file.
Compiler complains "cannot deduce template argument for 'unused'".
Do you guys understand what I an trying to do ? How can I trick the compiler ? I think I need to unsert some dummy usage of template arg into the function so that compiler can deduce it.
Can anyone help ?
Just put its prototype in the .h file, and its implementation in a single .c file:
In .h file:
int myFunc( int x );
In .c file:
int myFunc( int x )
{
return x + 4;
}
You should not use "static" on functions merely so you can define them in a header, use "inline" for that.
And once you use "inline", you don't need any template "tricks", just define the function:
inline int myfunction(...) {/*...*/}
When you want to move the definition out of the header, remove the inline and define the function in a .cpp file.
Honestly, I don't recommend putting large non-template function's definition in .h file unless there is definite reason that you can't put the definition in .cpp file. If you have to put the definition in .h, the following code might help:
// .h
template< int Unused > int myfunction_() {
// definition
}
namespace { int (&myfunction)() = myfunction_<0>; }
// .cpp
int main() { myfunction(); }
If you could show the reason that you have to put the definition in .h, better suggestions may be posted.
Edit: Rewrote the code in the light of Bo Persson's pointing out.
If you really want to do this and are paranoid about inlining. You could do the following:
#ifdef DEFINE_MY_FUNCTION
int myfunction(...) {
...
}
#else
// just declare it
int myfunction(...);
#endif
Then just #define DEFINE_MY_FUNCTION
before one of your #include "myheader.h"
lines (in a cpp file).
However, there are many reasons to go the conventional route, as others have advised, not least the fact that any implementation tweaks will require recompilation of any file that uses myfunction()
.
精彩评论