How to separate a few special keywords - c++

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.

Related

Why would inline functions have multiple identical definitions?

I'm working through the C++ Primer (5th Edition), and while it's been really great material so far, I find in some instances I run into head-scratching explanations that give me more questions than answers.
In the current example (emphasis mine on the bolded):
Unlike other functions, inline and constexpr functions may be defined multiple times in the program. After all, the compiler needs the definition, not just the declaration, in order to expand the code. However, all of the definitions of a given inline or constexpr must match exactly. As a result, inline and constexpr functions normally are defined in headers.
I've done a bit of research on this, and I've seen many answers that I'm able to define an inline function multiple times as long as the definition is identical. Additionally, I've seen that the standard allows for this. What I'm curious is: why?
Is there a feasible coding situation where I would have my #include for a given header file for an inline function I want, only to provide a duplicate definition in my .cpp file? I feel like I'm missing an obvious situation where this rule is applicable. Why not just make it so you could only define the inline function once in the header, period, and not worry about it afterwards?
All the best.
The answer is surprisingly straightforward: this is done to allow you define the body of inline functions inside header files.
Since header files are "pasted" verbatim inside a translation unit that references them, any function definitions inside the headers would end up inside that translation unit. If you include the same header from several files, all these files would have defined the same function, with identical definitions (because they come from the same header).
Since the preprocessing stage is done before compiling, the compiler has no idea what part of a translation unit came from a header, and which was there in your cpp file. That's why it was easier for standard writers to allow multiple identical definitions.
Why not just make it so you could only define the inline function once in the header, period, and not worry about it afterwards?
Reasons that I can think of.
The compiler won't be able to enforce it. The contents that it processes are already pre-processed.
Also, mandating that inline functions be defined only in header files is too restrictive. You will find a large number of classes defined only in source files in real world applications. It will be a shame if those classes couldn't use inline functions.

Static libraries. Importing and exporting inline functions

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.

Inline and dlimport/dllexport

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.

Are there any advantages to making a free static function?

I have a .cpp file which has some static free functions. I know how that would help in a header file, but since the cpp is not included anywhere, what's the point? Are there any advantages to it?
Declaring free functions as static gives them internal linkage, which allows the compiler more aggressive optimizations, as it is now guaranteed that nobody outside the TU can see that function. For example, the function might disappear entirely from the assembly and get inlined everywhere, as there is no need to provide a linkable version.
Note of course that this also changes the semantics slightly, since you are allowed to have different static functions of the same name in different TUs, while having multiple definitions of non-static functions is an error.
Since comment boxes are too small to explain why you have a serious error in your reasoning, I'm putting this as a community wiki answer. For header-only functions, static is pretty much useless because anyone who includes their header will get a different function. That means you will duplicate code the compiler creates for each of the functions (unless the linker can merge the code, but by all I know, that's very unlikely), and worse, if the function would have local statics, each of those locals would be different, resulting in potentially multiple initializations for each call to a definition from a different inclusion. Not good.
What you need for header-only functions is inline (non-static inline), which means each header inclusion will define the same function and modern linkers are capable of not duplicating the code of each definition like done for static (for many cases, the C++ Standard even requires them to do so), but emitting only one copy of the code out of all definitions created by all inclusions.
A bit out of order response because the first item addressed raises some huge questions in my head.
but since the cpp is not included anywhere
I strongly hope that you never #include a source file anywhere. The preprocessor doesn't care about the distinction between source versus header. This is distinction exists largely to benefit humans, not the compilers. There are many reasons you should never #include a source file anywhere.
I have a .cpp file which has some static free functions. I know how that would help in a header file ...
How would that help?
You declare non-static free functions in a header if those free functions have external linkage. Declaring (but not defining) static free functions in a header doesn't help. It is a hindrance. You want to put stuff in a header that helps you and other programmers understand the exported content of something. Those static free functions are not exported content. You can define free functions in a header and thus make them exported content, but the standard practice is to use the inline keyword rather than static.
As far as your static free functions in your source file, you might want to consider putting the declarations of those functions near the top of the source file (but not in a header). This can help improve understandability. Without those declarations, the organization of the source file will look Pascalish, with the low-level functions defined first. Most people like a top-down presentation. By declaring the functions first you can employ a top-down strategy. Or an inside out strategy, or whatever strategy makes the functionality easiest to understand.

How to define (non-method) functions in header libraries

When writing a header library (like Boost), can one define free-floating (non-method) functions without (1) bloating the generated binary and (2) incurring "unused" warnings?
When I define a function in a header that's included by multiple source files which in turn is linked into the same binary, the linker complains about redefinitions. One way around this is to make the functions static, but this reproduces the code in each translation unit (BTW, can linkers safely dereplicate these?). Furthermore, this triggers compiler warnings about the function being unused.
I was trying to look for an example of a free-floating function in Boost, but I couldn't find one. Is the trick to contain everything in a class (or template)?
If you really want to define the function (as opposed to declaring it), you'll need to use inline to prevent linker errors.
Otherwise, you can declare the function in the header file and provide its implementation separately in your source file.
You can use the inline keyword:
inline void wont_give_linker_errors(void)
{
// ...
}
Er... The answer to your question is simply don't. You just don't define functions in header files, unless they are inline.
'static' function can also be defined in headers, but it is only useful for very specific rare purposes. Using 'static' just to work around a multiple-definition problem is utter nonsense.
Again, header files are for non-defining function declarations. Why on Earth would you want to define functions there?
You said you are writing "header library". What's a "header library"? Please note, that Boost defines its "functions" in header files because their "functions" are not really functions, they are function templates. Function templates have to be defined in header files (well, almost). If that's wasn't the case, Boost wouldn't be doing something as strange as defining anything in header files.
Besides the already mentioned inline, with most compilers templates have to be defined in headers (and with all compilers it's allowed). Since boost is mostly templates, that explains why it is almost all headers.
People have suggested inline but that violates the very first part of your question i.e. it bloats the code as the full definition is inserted into the code at each call of the function. The answer to your overall question is therefore "No".
If you mark them as static then they are still defined in each source file as you rightly pointed out but only once and so that's a better option than inline if code size is the only issue. I don't know if linkers can, or are allowed to, spot the duplicates and merge them. I suspect not.
Edit:
Just to clear up any confusion as to whether I support the notion of using static and/or defining functions within headers files generally then rest assured I don't. This was simply meant as a technical response as to the differences between functions marked inline and static defined in header files. Nothing more.