Reputation: 3316
How does compiler decide whether the function should be considered for inline or not?
Unlike linkage, there is no such thing as "inline" conflicts (declarations of same name may have inline or not).
For example, multiple declarations of functions can either have inline or not, such as:
inline static void test(); // declaration with inline
int main()
{
extern void test(); // declaration without inline.
test();
}
static void test() // definition does not have inline
{
}
or
static void test(); // declaration without inline
int main()
{
test();
}
inline static void test() // but definition has inline!
{
}
In each case, does the test() gets inlined?
My real question is, how does compiler discover that the function should be inlined? Does it look at whether the most recent declaration bear the keyword inline or does it look at whether the definition has keyword inline or not?
I tried to search it in the standard, but I could not find any rules concerning this ambiguity. It looks like inline is defined very vague in the standard.
(I initially thought that there should be a "rule" that mandates once a function is declared inline, every declaration of same name has to be inline as well.)
EDIT: I am basically asking how the compiler solves the ambiguity of multiple same-name declarations which only some of them contain inline keyword.
inline static void test() // definition with inline keyword
{
}
int main()
{
extern void test(); // declaration without inline
test(); // Does compiler consider inlining or not?
}
Upvotes: 1
Views: 212
Reputation: 20031
My real question is, how does compiler discover that the function should be inlined? Does it look at whether the most recent declaration bear the keyword inline or does it look at whether the definition has keyword inline or not?
Generally, compilers decide whether to inline a function based on (1) if the body of the function is in the header file and (2) rules of thumb specific to the compiler that determine if there's a net benefit to inline.
The inline
keyword is meant to help, but much like the register
keyword, it doesn't actually provide much when generating code. Instead, inline
simply means "don't complain if you see this definition more than once (because I'm sticking it in a header file)."
That "don't complain" thing is why your code doesn't complain even though it probably should.
If you're going to use the keyword, don't put it on the forward declaration, and do put it on the definition (and do put the definition in the header):
void test();
/* ... other declarations ... */
/* (in the same file) */
inline void test() { printf("inlined!\n"; }
There's actually a reason to do this: you may not want to clutter your declarations with the implementations.
Upvotes: 4