Reputation: 2515
I have the following piece of code.
#include <iostream>
using namespace std;
inline void inlinefunc() { cout << "hello" << endl; }
void func() { cout << "hello" << endl; }
bool isInlineFunc(void (*f)()) { return (f == inlinefunc); }
void print(void (*f)()) {
cout << (isInlineFunc(f)?"inline - ":"normal -");
f();
}
int main() {
void (*f)();
f = inlinefunc;
print(f);
f = func;
print(f);
}
How do I generically write isInlineFunc
?
Upvotes: 3
Views: 225
Reputation: 2762
You really can't - even with GCC, function's declared with __attribute__((always_inline))
won't be inlined if they don't meet the compiler's criteria for things that would increase the speed of the program.
Inlining functions can have serious negative effects on performance, and the compiler is almost always the only thing in the right position to know if that's the case. Inlining functions thwarts CPU architectural features like code cache and branch predictors, and even lower-level features like instruction decode cache (and bandwidth).
In short, there are some things that any modern CPU will do at tremendous speed, and C/C++ function calls are right up there. Profiling function call overhead is almost certainly going to give within-error measurements of your profiling overhead.
Upvotes: 0
Reputation: 52107
In general, compiler can apply any optimization it chooses, as long as it doesn't change the semantics of your code.
Inlining is just an optimization strategy. "Detecting" whether the function was inlined or not would mean that the semantics depends on the optimization, in direct violation of the above.
Upvotes: 0
Reputation: 54584
You can't. According to the C++ standard [basic.def.odr] (D refers to the definition in question):
... If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.
Taking the address of a function, inline or otherwise, must result in the same behavior as if there were a single definition of that function. For inline functions, it means the address is the same.
Upvotes: 0
Reputation: 78914
You don't.
The compiler is basically allowed to do whatever it wants with regards to inlining functions. A function can be inlined in one place and not inlined in another place.
If you're thinking about this, you're probably prematurely optimizing something.
Upvotes: 2
Reputation: 81349
What do you mean generically? Do you want to have a function that tells you if another function is declared inline
? That can't be done.
Also note that by taking the address of an inline function, the implementation is forced to actually have an out of line implementation of the function.
Upvotes: 4