Question

in C++, a function can be defined to be inline using inline key word. It is like the programmer has requested from the compiler to insert the complete body of the function in every place that the function is called.

But as I know compilers are not obligated to respect this request. So is there any way to guarantee that a function is inlined?

Was it helpful?

Solution

Use __forceinline in VC++ and __attribute__((always_inline)) in g++

OTHER TIPS

Nope. Actually inlining a function is a complete implementation detail, and many functions cannot be inlined. This makes the existence of an inline forcing mechanism impossible. Even compilers that offer keywords like __forceinline (VC++) won't inline functions with that qualifier under some circumstances. And the page carries a very apt warning about misusing this qualifier.

As this isn't covered by the standard, it depends on the compiler you're using. The compiler's documentation will tell you if there is a feature for forcing a function to be inlined, and how to use it. The documentation should also tell you the limits of that feature, such as for recursive calls in a non-tail position.

If you are using a Microsoft compiler, you may use __forceinline, as explained here: http://msdn.microsoft.com/en-us/library/z8y1yy88%28v=vs.71%29.aspx

I do not know of a way to force inlining in g++ or other compilers.

I cannot imagine that there´s a way to do that. It is mainly dependant on the compiler. Another solution would be to use #define macro to define your function

By putting the definition of a function right into its declaration in the header, the function gets the highest chances to be inlined.

class TheClass
{
public:
    static void DoSomething () // declaration
    {
        // the function's code (definition) goes here
    };
};

// in the same header..

void DoOtherThings () // declaration
{
    // the function's code (definition) goes here
}

In any case, there is no strong guarantee, perhaps even if you use the compiler-specific keyword for inline forcing.

A 100% percent guarantee would be transforming your function into a C++ macro and using the macro instead of referring to the function. If you function has multiple lines, place a \ (a space followed by a backslash) where you want to have a line break in your "macro-function".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top