Now I analyse some old code, which was not written by me. In headers there are many declarations like this:
SVPDSDKDLLEXPORT inline C3vec mult(C3vec src, D3DXMATRIX &m);
SVPDSDKDLLEXPORT is defined as _declspec(dllexport), if it is used in SVPDSDK; as _declspec(dllimport), if it is used in any project, which uses SVPDSDK.dll. Inlining here seems very strange for me as there is no definition in the header, it is in .cpp file, but compilation and linkage of SVPDSDK and all projects, which use respective DLL, are executed without any problems. I assume, that it is just ignored and the function is exported as though is was not inlined.
I've found this discussion:
C++ : inline functions with dllimport/dllexport?
Looked like I should have removed "inline" from all such declarations, don't mix inlining and export/import. But then I found this topic in MSDN:
http://msdn.microsoft.com/en-us/library/xa0d9ste
I don't understand some parts of it.
You can define as inline a function with the dllexport attribute. In this case, the function is always instantiated and exported, whether or not any module in the program references the function. The function is presumed to be imported by another program.
Firstly, "the function is always instantiated", what does it mean? I've found only topics about template functions instantiation in C++, no any other instantiation. Is it connected only with templates or not?
Secondly, "the function is always exported". I don't understand it at all. Is it possible, that function with declspec(_dllexport) is not exported in some cases? In what cases?
Now about import:
You can also define as inline a function declared with the dllimport attribute. In this case, the function can be expanded (subject to /Ob specifications), but never instantiated. In particular, if the address of an inline imported function is taken, the address of the function residing in the DLL is returned. This behavior is the same as taking the address of a non-inline imported function.
Again, I don't understand, what means instantiation in this case.
While writing this question and analysing topic from MSDN, I made a conclusion, that function, which is exported/imported and inlined at the same time, is inlined only in its project itself (SVPDSDK in my case) and is non-inlined in all importing projects. It's not evidently declared in MSDN topic. If I don't import it in any project, which uses it, and I have not a definition in its header file, it will be an ordinary inlined function, so I will get a linkage error. Then it seems for me that it's agreeable to mix inlining and export/import, thought it contradicts an answer in the stackoverflow discussion, mentioned above. Am I right?
And I still don't understand all this words about inlined functions instantiation.
I'm sorry, that I combined some questions in one topic, but I don't know, how to divide it in separate ones, because they are united by the same issue and the same materials. However, I would be grateful, if anyone could clarify this questions for me.
In fact, inline is a sort of hint for the optimizer. Compiler can still generate a real function with body, pushing args on the stack, etc. This will not break any logic. It would definitely do so if your "inline" function would have more than 10000 lines of code. Microsoft even has special __forceinline keyword. Guess why it was introduced.
The function is always instantiated and exported ...
The wording might be not perfect here. Instantiation means here that a body and an entry point will be generated. This has nothing to do with template instantiation. The whole paragraph means that __declspec is more important than inline.
For dllimport they basically write that dllimport prevents generation of body of this inline function in the current binary module, while the inline expansion is still possible.
Related
usually I wrote only in header or only in cpp, however obviously that's wrong and unusual. Therefore recently I started to get used to separating things into 2 different file.
I'm usually using these keywords:
inline
__stdcall
My question is the following:
Where should I place them? Only in header? Only in source? Both?
Which is the usual convention about it?
My question is ONLY ABOUT THOSE KEYWORDS. It's now about how to generally spearate them. I know already know the basics!
Since an inline function must be inline in all translation units (as you know from the basics), it's simplest to declare it inline in the header. Otherwise you could accidentally forget to define it inline in one source file, while you have defined it inline in another.
In fact, since inline functions must be defined in every translation unit where it's used and the definition must always be the same, it's simplest to also define the inline function in the header and simply include the header in the source files, rather than define it separately in any source file.
When you define the inline function in a header, it's typically recommended to define it out-of-line (might seem paradoxical). This guideline suggested by Tadeusz Kopec is good. You should define the function inline at the definition (in the header, as I suggested), but not at the declaration so that it's easier to later change the definition non-inline if you so later wish. It's also true for non-member functions, but especially true for member functions.
Now, __stdcall is a non-standard keyword, so you'll have to take a look at the documentation of the implementation. The documentation doesn't explicitly state it, but the caller must know the calling convention, and therefore it must be in the header. The documentation explicitly states that the keyword does not need to be in a out of line definition of the function, so you may omit it.
In fact, if you only specify it in the declaration, you don't have to go looking for the definition if you later want to change the calling convention. On the other hand, if the function must be changed when the calling convention is changed, then explicitly defining the calling convention in the definition of the function can serve as a reminder. So, it's a matter of preference.
I suppose you should place full function signature in the .h file to make sure that person reading your code can understand what you untended without digging into .cpp.
Also, quick look at Google C++ style guide didn't help me to find information about placing these 2 words, so it is not a crucial problem.
I know inline fits tiny body functions called several times. If the number of calls increases it may result in an extra large code. But what about a large body function called only a few times?
I'm interested mainly in inline-ing a large body function that's only called once, in a while loop in main(). This function is in fact the core so it's 90% of the program and as stated, executes once per tick.
I figure the compiler has no problem in making it inline, as it's like I'd write it myself in the while. Instead, I define it somewhere else and call it in the while.
EDIT:
I'm well aware that inline is more of compiler decision than of user, going so far as even to inlining non-specified inline functions, so the user control is almost negligible. But it's a matter of principle plus in this particular case it could serve very well.
Reasonable idea. There are a number of compilers which do link-time code generation. Those can see that your function has only one caller, and inline it.
Then again, since that takes link-time code generation, the inline keyword is not that useful anyway.
An inline function (if it is really inlined) would be absolutely the same as if you just copied all the code to a places from where you do call the function. So you may easily imagine how large would be the code.
Also the inline statement is rather a hint to a compiler that this function would be better to inline into the code where it is called. But depending on circumstances a compiler may decide to not inline it — if it thinks that this would be better.
Also you may find useful this short faq about an inline functions
Inline functions are simple functions that you cant write in another file like example.cpp and include it with the main class files where you have like class name { atributes, methods ..}; In front of the function you cand write "inline" and the compiler will see as if it's writen inside the class. That is what i know for the oop way. And yea for functions that contains while , foor, do while loops it's recomanded to write outside of the class function not in a inline.It's a matter of coding style.
You're probably barking up the wrong tree with inline. You need to profile your code both with and without inline to know what the effect will truly be. If I were a gambling man, (and I am), I'd bet that it would not improve performance, and it might make performance worse.
inline tells the compiler that you would like the function call to be substituted inline at the point of the call, but the compiler is free to ignore your request. Back a number of years ago it was fairly common to employ inline as a performance enhancement -- sometimes it had a beneficial effect, sometimes it didn't. These days, however, compilers have gotten so good at optimizing code that attempting to outsmart the compiler in this regard is folly. The compiler is far better than you at optimizing your code.
Moreover, these days compilers will very aggressively ignore your requestion to inline the function implementation at the call-site. Most inline requests are ignored. On today's hardware, this is usually a good thing considering performance. Inlining functions can actually hinder performance in ways you might not realize.
These days, inline is not a performance tool. Instead, it's something completely different. From the standard, section 7.1.2/4:
An inline function shall be defined in every translation unit in which
it is odr-used and shall have exactly the same definition in every
case (3.2). [ Note: A call to the inline function may be encountered
before its definition appears in the translation unit. —end note ] If
the definition of a function appears in a translation unit before its
first declaration as inline, the program is ill-formed. If a function
with external linkage is declared inline in one translation unit, it
shall be declared inline in all translation units in which it appears;
no diagnostic is required. An inline function with external linkage
shall have the same address in all translation units. A static local
variable in an extern inline function always refers to the same
object. A string literal in the body of an extern inline function is
the same object in different translation units. [ Note: A string
literal appearing in a default argument is not in the body of an
inline function merely because the expression is used in a function
call from that inline function. —end note ] A type defined within the
body of an extern inline function is the same type in every
translation unit.
This question arose while I was implementing my static library.
I want to check my guess and gain information on using inline functions in static libs.
My guess is that an iplementator of a static lib can not export an inline function in his library
Due to the inline statement is
implemented by a compiler(it is up to the compiler whether to make
the function inline) by placing low level commands representing
operations in the function body to the code segment so that
operations won't be placed in the tables of export/import and
therefore can't be processed by linker and therefore can't be
included by librarian to the code of application to which static lib
is attached. Is my logic right?
I guess that importing function as inline is allowed but I wonder how it is implemented, because it is compiler`s
responsibility but on the linkage state there is only librarian, so
that means that it must undertake some actions in order to make
function inline.
Yes, inline functions are typically placed in a header, so the function body is directly visible to the compiler everywhere the function is used. This lets the compiler evaluate whether to generate inline code for the function in any particular instance.
This basically doesn't arise -- "An inline function shall be defined in every translation unit in which it is odr-used." (§3.2/3). That means if the compiler is going to generate the function inline, what goes into the library is object code that includes inline expansion of the code for that function. Since it's possible that function may not be expanded inline at every use, there will also typically be a definition of the function in the library, but that definition will be used (at least primarily) like a normal function, not expanded inline.
Linkers can also generate code though. Regardless of whether a function is or isn't an inline function by the language standard, and is defined in the same or a different translation unit from the one where it's used, the linker may be able to generate inline code for it anyway.
To make a long story short, the inline keyword has little or no effect on a typical compiler as far as whether a function's code will be generated inline or not. The main (if not sole) effect is that it changes the one-definition rule -- being inline means that multiple (identical) definitions of the same function can exist without causing a problem.
Do you understand the keyword inline - you could equally use replace.
An inline function enables the compile if so choosing to replace the function call with the actual code - nothing to export/import. It is defined in the header file. Anything that uses the object code will require that header code and thus the compiler will replace the function call with the actual code.
On Visual C++ you can use Microsoft specific behavior, and export/import inline functions with __declspec(dllexport) inline or extern inline. Note that this is Microsoft specific behavior, if you target anything but Windows and are not concerned at all with portability, you could consider it.
Edit: I've restored the original title but really what I should have asked was this: 'How do C++ linkers handle class methods which have been defined in multiple object files'
Say I have a C++ class defined in a header along these lines:
class Klass
{
int Obnoxiously_Large_Method()
{
//many thousands of lines of code here
}
}
If I compile some C++ code which uses 'Obnoxiously_Large_Method' in several locations, will the resulting object file always inline the code for 'Obnoxiously_Large_Method' or will it optimise for size (for example, when using g++ -Os) and create a single instance of 'Obnoxiously_Large_Method' and use it like a normal function?, if so, how do linkers resolve the collisions between other object files which have instantiated the same function?. Is there some arcane C++ namespace Juju which keeps the separate object instances of method from colliding with each other?
7.1.2 Function specifiers
A function declaration (8.3.5, 9.3, 11.4) with an inline specifier
declares an inline function. The inline specifier indicates to the
implementation that inline substitution of the function body at the
point of call is to be preferred to the usual function call mechanism.
An implementation is not required to perform this inline substitution
at the point of call; however, even if this inline substitution is
omitted, the other rules for inline functions defined by 7.1.2 shall
still be respected.
So, the compiler is not required to actually 'inline' any function.
However, the standard also says,
An inline function with external linkage shall have the same address in all translation units.
Member functions normally have external linkage (one exception is when the member function belongs to a 'local' class), so inline functions must have a unique address for cases where the address of the function is taken. In this case, the compiler will arrange for the linker to throw away all but one instance of a non-inlined copy of the function and fix-up all address references to the function to be to the one that's kept.
Section [9.3], Member functions, of the C++98 Standard states:
A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2).
Thus, it has always been the case that marking member functions defined in the class definition explicitly inline is unnecessary.
On the inline function specifier, the Standard states:
A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The inline specifier indicates to the [C++ compiler] that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. [However, a C++ compiler] is not required to perform this inline substitution at the point of call;
So, it is up to the compiler whether it will actually inline the definition of the function rather than call it via the usual function call mechanism.
Nothing is always inlined (unless your compiler has an attribute or private keyword to force it to do so...at which point you're writing $(COMPILER)-flavored C++ rather than standard C++). Very long functions, recursive functions, and a few other things generally aren't inlined.
The compiler can choose not to inline stuff if it determines that doing so will degrade performance, unreasonably increase the object file's size, or make things work incorrectly. Or if it's optimizing for size instead of speed. Or if you ask it not to. Or if it doesn't like your shirt. Or if it's feeling lazy today, cause it compiled too much last night. Or for any other reason. Or for no reason at all.
There is no - single answer to this question. Compilers are smart beasts. You can specifically use the inline words if you want, but this doesn't mean that the compiler will actually inline the function.
Inline is there to help the developer with optmization. It hints at the compiler that something should be inlined, but these hints are generally ignored nowadays, since compilers can do better at register assignment and deciding when to inline functions (in fact, a compiler can either inline or not inline a function at different times). Code generation on modern processors is far more complicated than on the more deterministic ones common when Ritchie was inventing C.
What the word means now, in C++, is that it can have multiple identical definitions, and needs to be defined in every translation unit that uses it. (In other words, you need to make sure it can be inlined.) You can have an inline function in a header with no problems, and member functions defined in a class definition are automatically effectively inline.
That said, I used to work with a greenhills compiler, and it actually obeyed my will more than it disobeyed it :).. It's up to the compiler, really.
The inline keyword deals with c++ definition of a function. The compiler may inline object code where ever it wants.
Functions defined inline (eg they use the inline keyword), create object code for the function in every compilation unit. Those functions are marked as special so the linker knows to only use one.
See this answer for more specifics.
It doesn't have to be inlined, no; it's just like if you specified inline explicitly.
When you write inline, you promise that this method won't be called from translation units where it isn't defined, and therefore, that it can have internal linkage (so the linker won't connect one object-file's reference to it to another object-file's definition of it). [This paragraph was wrong. I'm leaving it intact, just struck-out, so that the below comments will still make sense.]
I had a discussion with Johannes Schaub regarding the keyword inline.
The code there was this:
namespace ... {
static void someFunction() {
MYCLASS::GetInstance()->someFunction();
}
};
He stated that:
Putting this as an inline function may
save code size in the executable
But according to my findings here and here it wouldn't be needed, since:
[Inline] only occurs if the compiler's cost/benefit analysis show it to be profitable
Mainstream C++ compilers like Microsoft Visual C++ and GCC support an option that lets the compilers automatically inline any suitable function, even those not marked as inline functions.
Johannes however states that there are other benefits of explicitly specifying it. Unfortunately I do not understand them. For instance, he stated that And "inline" allows you to define the function multiple times in the program., which I am having a hard time understanding (and finding references to).
So
Is inline just a recommendation for the compiler?
Should it be explicitly stated when you have a small function (I guess 1-4 instructions?)
What other benefits are there with writing inline?
is it needed to state inline in order to reduce the executable file size, even though the compiler (according to wikipedia [I know, bad reference]) should find such functions itself?
Is there anything else I am missing?
To restate what I said in those little comment boxes. In particular, I was never talking about inlin-ing:
// foo.h:
static void f() {
// code that can't be inlined
}
// TU1 calls f
// TU2 calls f
Now, both TU1 and TU2 have their own copy of f - the code of f is in the executable two times.
// foo.h:
inline void f() {
// code that can't be inlined
}
// TU1 calls f
// TU2 calls f
Both TUs will emit specially marked versions of f that are effectively merged by the linker by discarding all but one of them. The code of f only exists one time in the executable.
Thus we have saved space in the executable.
Is inline just a recommendation for the compiler?
Yes.
7.1.2 Function specifiers
2 A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The inline
specifier indicates to the implementation that inline substitution of the function body at the point of call
is to be preferred to the usual function call mechanism. An implementation is not required to perform this
inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules
for inline functions defined by 7.1.2 shall still be respected.
For example from MSDN:
The compiler treats the inline expansion options and keywords as suggestions. There is no guarantee that functions will be inlined. You cannot force the compiler to inline a particular function, even with the __forceinline keyword. When compiling with /clr, the compiler will not inline a function if there are security attributes applied to the function.
Note though:
3.2 One definition rule
3 [...]An inline function shall be defined in every translation unit in which it is used.
4 An inline function shall be defined in every translation unit in which it is used and shall have exactly
the same definition in every case (3.2). [ Note: a call to the inline function may be encountered before its
definition appears in the translation unit. —end note ] If the definition of a function appears in a translation
unit before its first declaration as inline, the program is ill-formed. If a function with external linkage is
declared inline in one translation unit, it shall be declared inline in all translation units in which it appears;
no diagnostic is required. An inline function with external linkage shall have the same address in all
translation units. A static local variable in an extern inline function always refers to the same object.
A string literal in the body of an extern inline function is the same object in different translation units.
[ Note: A string literal appearing in a default argument expression is not in the body of an inline function
merely because the expression is used in a function call from that inline function. —end note ] A type
defined within the body of an extern inline function is the same type in every translation unit.
[Note: Emphasis mine]
A TU is basically a set of headers plus an implementation file (.cpp) which leads to an object file.
Should it be explicitly stated when you have a small function (I
guess 1-4 instructions?)
Absolutely. Why not help the compiler help you generate less code? Usually, if the prolog/epilog part incurs more cost than having it inline force the compiler to generate them? But you must, absolutely must go through this GOTW article before getting started with inlining: GotW #33: Inline
What other benefits are there with writing inline?
namespaces can be inline too. Note that member functions defined in the class body itself are inline by default. So are implicitly generated special member functions.
Function templates cannot be defined in an implementation file (see FAQ 35.12) unless of course you provide a explicit instantiations (for all types for which the template is used -- generally a PITA IMO). See the DDJ article on Moving Templates Out of Header Files (If you are feeling weird read on this other article on the export keyword which was dropped from the standard.)
Is it needed to state inline in order to reduce the executable file
size, even though the compiler
(according to wikipedia [I know, bad
reference]) should find such functions
itself?
Again, as I said, as a good programmer, you should, when you can, help the compiler. But here's what the C++ FAQ has to offer about inline. So be wary. Not all compilers do this sort of analysis so you should read the documentation on their optimization switches. E.g: GCC does something similar:
You can also direct GCC to try to integrate all “simple enough” functions into their callers with the option -finline-functions.
Most compilers allow you to override the compiler's cost/benefit ratio analysis to some extent. The MSDN and GCC documentation is worth reading.
Is inline just a recommendation for the compiler?
Yes. But the linker needs it if there are multiple definitions of the function (see below)
Should it be explicitly stated when you have a small function (I guess 1-4 instructions?)
On functions that are defined in header files it is (usually) needed. It does not hurt to add it to small functions (but I don't bother). Note class members defined within the class declaration are automatically declared inline.
What other benefits are there with writing inline?
It will stop linker errors if used correctly.
is it needed to state inline in order to reduce the executable file size, even though the compiler (according to wikipedia [I know, bad reference]) should find such functions itself?
No. The compiler makes a cost/benefit comparison of inlining each function call and makes an appropriate choice. Thus calls to a function may be inlined in curtain situations and not inlined in other (depending on how the compilers algorithm works).
Speed/Space are two competing forces and it depends what the compiler is optimizing for which will determine weather functions are inlined and weather the executable will grow or shrink.
Also note if excessively aggressive inlining is used causing the program to expand too much, then locality of reference is lost and this can actually slow the program down (as more executable pages need to be brought into memory).
Multiple definition:
File: head.h
// Without inline the linker will choke.
/*inline*/ int add(int x, int y) { return x + y; }
extern void test()
File: main.cpp
#include "head.h"
#include <iostream>
int main()
{
std::cout << add(2,3) << std::endl;
test();
}
File: test.cpp
#include "head.h"
#include <iostream>
void test()
{
std::cout << add(2,3) << std::endl;
}
Here we have two definitions of add(). One in main.o and one in test.o
Yes. It's nothing more.
No.
You hint the compiler that it's a function that gets called a lot, where the jump-to-the-function part takes a lot of the execution time.
The compiler might decide to put the function code right where it gets called instead where normal functions are. However, if a function is inlined in x places, you need x times the space of a normal function.
Always trust your compiler to be much smarter than yourself on the subject of premature micro-optimization.
Actually, inline function may increase executable size, because inline function code is duplicated in every place where this function is called. With modern C++ compilers, inline mostly allows to programmer to believe, that he writes high-performance code. Compiler decides itself whether to make function inline or not. So, writing inline just allows us to feel better...
With regards to this:
And "inline" allows you to define the function multiple times in the program.
I can think of one instance where this is useful: Making copy protection code harder to crack. If you have a program that takes user information and verifies it against a registration key, inlining the function that does the verification will make it harder for a cracker to find all duplicates of that function.
As to other points:
inline is just a recommendation to compiler, but there are #pragma directives that can force inlining of any function.
Since it's just a recommendation, it's probably safe to explicitly ask for it and let the compiler override your recommendation. But it's probably better to omit it altogether and let the compiler decide.
The obfuscation mentioned above is one possible benefit of inlining.
As others have mentioned, inline would actually increase the size of the compiled code.
Yes, it will readily ignore it when it thinks the function is too large or uses incompatible features (exception handling perhaps). Furthermore, there is usually a compiler setting to let it automatically inline functions that it deems worthy (/Ob2 in MSVC).
It should be explicitly stated if you put the definition of the function in the header file. Which is usually necessary to ensure that multiple translation units can take advantage of it. And to avoid multiple definition errors. Furthermore, inline functions are put in the COMDAT section. Which tells the linker that it can pick just one of the multiple definitions. Equivalent to __declspec(selectany) in MSVC.
Inlined functions don't usually make the executable smaller. Since the call opcode is typically smaller than the inlined machined code, except for very small property accessor style functions. It depends but bigger is not an uncommon outcome.
Another benefit of in-lining (note that actual inlining is sometimes orthogonal to use of the "inline" directive) occurs when a function uses reference parameters. Passing two variables to a non-inline function to add its first operand to the second would require pushing the value of the first operand and the address of the second and then calling a function which would have to pop the first operand and address of the second, and then add the former value indirectly to the popped address. If the function were expanded inline, the compiler could simply add one variable to the other directly.
Actually inlining leads to bigger executables, not smaller ones.
It's to reduce one level of indirection, by pasting the function code.
http://www.parashift.com/c++-faq-lite/inline-functions.html