2

I have a function which is very small and it is not part of any class. Can I put it in a header file to make it inline? some thing such as this:

inline int add(int a, int b)
{
      return a+b;
}

Please note that it is not a method of a class, but a c type function.

mans
  • 17,104
  • 45
  • 172
  • 321

2 Answers2

11

It is already answered in C++ FAQ

How do you tell the compiler to make a non-member function inline?

When you declare an inline function, it looks just like a normal function:

void f(int i, char c);

But when you define an inline function, you prepend the function’s definition with the keyword inline, and you put the definition into a header file:

inline
void f(int i, char c)
{
// ...
}

Note: It’s imperative that the function’s definition (the part between the {...}) be placed in a header file, unless the function is used only in a single .cpp file. In particular, if you put the inline function’s definition into a .cpp file and you call it from some other .cpp file, you’ll get an “unresolved external” error from the linker.

Alper
  • 12,860
  • 2
  • 31
  • 41
5

The answer to your question is yes.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91