Using gcc v4.8.1
If I do:
//func.hpp
#ifndef FUNC_HPP
#define FUNC_HPP
int func(int);
#endif
//func.cpp
#include "func.hpp"
int func(int x){
return 5*x+7;
}
//main.cpp
#include <iostream>
#include "func.hpp"
using std::cout;
using std::endl;
int main(){
cout<<func(5)<<endl;
return 0;
}
Even the simple function func
will not get inlined. No combination of inline
, extern
, static
, and __attribute__((always_inline))
on the prototype and/or the definition changes this (obviously some combinations of these specifiers cause it to not even compile and/or produce warnings, not talking about those). I'm using g++ *.cpp -O3 -o run
and g++ *.cpp -O3 -S
for assembly output. When I look at the assembly output, I still see call func
. It appears only way I can get the function to be properly inlined is to have the prototype (probably not necessary) and the definition of the function in the header file. If the header is only included by one file in the whole program (included by only main.cpp
for example) it will compile and the function will be properly inlined without even needing the inline
specifier. If the header is to be included by multiple files, the inline
specifier appears to be needed to resolve multiple definition errors, and that appears to be its only purpose. The function is of course inlined properly.
So my question is: am I doing something wrong? Am I missing something? Whatever happened to:
"The compiler is smarter than you. It knows when a function should be inlined better than you do. And never ever use C arrays. Always use std::vector!"
-Every other StackOverflow user
Really? So calling func(5) and printing the result is faster than just printing 32? I will blindly follow you off the edge of a cliff all mighty all knowing and all wise gcc.
For the record, the above code is just an example. I am writing a ray tracer and when I moved all of the code of my math and other utility classes to their header files and used the inline
specifier, I saw massive performance gains. Literally like 10 times faster for some scenes.