I had this header file that contain a lot of inline functions,after compile it says:
multiple definition of function***,the function which looks like this:
inline int testab(int a, int b)
{
return a>b;
}
after I add static in front of inline, the error is gone. Is it the right way to do it? Or am I missing something? I thought I could set up inline functions in a header like that.
inlineor not, once the header gets copied in at least two files, you cannot link the files anymore.The only way you can safely implement a function in a header is to use
static. This way, each copy of the function would be invisible to the other ones.Note that there is no restriction to using them together, so you can safely write:
Edit: More details
inlinetells the compiler that you think the function is small enough to be inlined. That is you tell the compiler that you don’t think the extra space for inlining the function matters much as opposed to the (slight) (possible) performance gain for it. Most compilers however are intelligent enough to decide that on their own and with your keyword, they would just tend a bit more to inline, and not necessarily always listen to you. This depends on the compiler, of course. Some compilers may completely ignore the keyword.staticon the other hand, means that whatever scope a static variable is defined, it will be invisible outside it. If you have astaticvariable in a function, it would be invisible outside it. If you have astaticvariable in a file (that is, a static global variable), it will be invisible outside it, which means the symbol is not there after compiling for the linker to see and get confused. That is why, if you have written a library in which there are global variables or functions that are not supposed to be visible outside the library, you should declare them asstatic.Edit 2: Correction
Apparently, according to this answer,
inlinefunctions should not have its identifiers exported for the linker. Nonetheless, one can attachstaticto it either way just to make it more clear. Also apparently, some compilers export the identifier anyway, so in those casesstaticis indeed necessary.