1
#include <iostream>

using namespace std;

inline int square(int n)
{
    return n * n;
}

int main(void)
{
    cout << square(2) << endl;
}

By compiling the code using gcc I found out that the compiler is still treating the square function as simple function rather than as inline.

(I checked out the assembly code and there I saw call to square function. That's how I knew it's not treating it as inline.)

Why is it denying my request to make the function inline even though its a simple function? If gcc is denying such a simple function inline then what's the use of inline keyword?

I can force inline the function; that's not the problem. I just want to know why gcc is declining my request.

Lokesh
  • 2,842
  • 7
  • 32
  • 47
  • possible duplicate of [How do I force gcc to inline a function?](http://stackoverflow.com/questions/8381293/how-do-i-force-gcc-to-inline-a-function) – Jendas Aug 21 '15 at 09:16

3 Answers3

6

inline is essentially ignored on modern mainstream compilers (it just enables the usual exemption to the ODR for the function). The optimizer will do his thing anyway, and it probably knows better than you or me (although there's usually some compiler-specific flag to force the inlining of a function).

Anyway, probably you are not seeing any inlining there because you compiled with optimizations disabled - a setting used often in debugging, where inlining and other optimizations makes impossible to match source lines to compiled code (and thus stepping through in a debugger). Enabling optimizations -O3 on my machine (g++ 4.8.4) makes the function disappear completely - the result (4) is evaluated completely at compile time.


To sum it up: currently, the point of inline is to allow you to supply the function definition in multiple translation units without having linker errors for multiple definitions of a function.

This is useful because if you have a good candidate for inlining you want to put it into a header file (so that compiling each .cpp the compiler can see immediately its definition, and expand it inline right away - link time code generation is just a recent thing) but you want the linker to know that the extra non-inline copies that arise refer all to the same thing, and can be discarded safely (marking them as static would lead to unnecessary code duplication in each TU).

Community
  • 1
  • 1
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

You are not compiling with optimization enabled. Even with -O1 your code compiles to the equivalent of

int main () {
    std::cout << 4;
}

Also, don't you worry about what should be inlined and what not, let the compiler do that for you. It is way better. (As always, unless you proof by measurement that the compiler was wrong.)

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
0

Compile with optimizations, e.g. g++ -O3 ....

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271