I have observed that inline functions can not be prototyped. example:
.cpp file:
1 2 3 4
inlinevoid whatever()
{
cout<< "this is inline"<< endl;
}
.h file, prototype inlinevoid whatever(); //would ask for a definition
Because of this, I have have just made functions that are used in only 1 .cpp file (ever) inlined, to make it more efficient (and it has demonstrated that it is more efficient).
It's worked out fine so far, but what about the scope of the definition??
Since an inline function is like a templated function, in that it can't be prototyped, how are name conflicts resolved, and what is the best practice for writing inline functions??
example of a conflict:
1 2
//in some arbitrary header...
void do_somthing();
1 2 3 4 5 6 7 8 9 10 11
//in .cpp file that inlcudes the header...
inlinevoid do_somthing()
{
cout<< "I'm doing somthing!!"<< endl;
}
int main()
{
do_somthing(); //which one?? it compiles fine though!!
return 0;
}
I have observed that inline functions can not be prototyped.
This is not true.
Inline functions have internal linkage, so their bodies are only visible in whatever source file they're in.
1 2
// foo.h
void func();
1 2 3 4 5 6 7 8 9 10 11
// foo.cpp
#include "foo.h"
inlinevoid func()
{
//...
}
void anotherfunc()
{
func(); // Not a problem. Compiles and links OK
}
1 2 3 4 5 6 7 8
// main.cpp
#include "foo.h"
int main()
{
func(); // LINKER ERROR
// no body for 'func' found
}
Because of this, if an inline function needs to be available in multiple source files, it is usually defined in the header. This way, all the source files that include it have its body:
1 2 3 4 5
// foo.h
inlinevoid func()
{
//...
}
1 2 3 4 5 6 7
// foo.cpp
#include "foo.h"
void anotherfunc()
{
func(); // Not a problem. Compiles and links OK
}
1 2 3 4 5 6 7
// main.cpp
#include "foo.h"
int main()
{
func(); // Not a problem. Compiles and links OK.
}