As I was busy inlining some of my functions, I was wondering if it is really necessary to inline anything. Doesn't the compiler automatically inline stuff, or do I have false memories? And if the compiler does inline stuff for me, would it be best to let it do its job or should I mess up something by doing it myself?

The reason I thought of the first question is because I can't get my now-inlined functions to work. A quick example:

test.cpp

#include <iostream>
#include <string>
#include "test.h"

void main()
{
	std::cout << getString();
	std::cin.get();
}

test2.cpp

#include "test.h"

inline
std::string getString()
{
	return "Beam me up, Scotty!";
}

test.h

#ifndef TEST_H
#define TEST_H

#include <string>

std::string getString();

#endif

This generates the error:

test.obj : error LNK2019: unresolved external symbol "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl getString(void)" (?getString@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) referenced in function _main
C:\w\e\Projects\test\Debug\test.exe : fatal error LNK1120: 1 unresolved externals

Removing the inline will make the program work.

Compilers are free to choose to ignore the inline keyword or not.

Move the code in test2.cpp to test2.h since you use the linline keyword, then delete test2.cpp from the project.

The function definition is not being included in your test.cpp module, so the linker can't find it. Often inline function definitions are saved as a different type of file (like test.inl) which is itself #include -ed.

if you really need to inline something and aren't sure whether the compiler will or not, standard practice is to write the function definition in the function declaration. In other words move the code into test.h as follows:

#ifndef TEST_H
#define TEST_H 
#include <string> 

std::string getString(){ return "Beam me up, Scotty!"; };

#endif

or include the code module as well...usually instead of being saved as a .cpp the file is saved as another type (often .inl) which you will also have to #include.

As to whether it's worth doing, that depends. If it is absolutely time-critical code and you are unsure as to whether the compiler will or will not inline functions, and it is worth the code bloat, sure. Otherwise, letting the compiler decide when to inline code...and with compilers you can change how aggressive they are about inlining code, also. I can't really see the need for it in a function like the one you mentioned...it's more often seen when writing very time critical math functions and such.

This question has already been answered. Start a new discussion instead.