inline static class methods?

I'm wondering if it's possible to have static class methods that are inline. I read this:

http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.9

Now I'm trying out an inline class method, but I get an error such as this one while compiling:

/var/tmp//cc9kETd5.o(.text+0x12): In function `main':
: undefined reference to `IOSers::foo()'
*** Error code 1


My complete code for this small example is divided into 4 files (being in same directory):

Makefile:
1
2
3
4
5
6
7
8
CC = g++
CCFLAGS = -Wall -O2 -fno-strict-aliasing -pipe

parser: IOSers.h IOSers.cc Parser.cc
        ${CC} ${CCFLAGS} IOSers.cc Parser.cc -o iosers-parser

clean:
        rm -f iosers-parser


IOSers.h:
1
2
3
4
5
6
7
8
9
10
#ifndef IOSERS_H
#define IOSERS_H

class IOSers
{
 public:
  static bool foo();
};

#endif 


IOSers.cc:
1
2
3
4
5
6
#include "IOSers.h"

inline bool IOSers::foo()
{
  return false;
}


Parser.cc:
1
2
3
4
5
6
7
#include "IOSers.h"

int main(int argc, char *argv[])
{
  bool rtn = IOSers::foo();
  return rtn;
}


If I remove the inline keyword in IOSers.cc, it compiles fine.

I'm pretty new to C++. What am I doing wrong? In practice, the functions that I'm inlining would be about 4 lines of code.
IIRC - the definition of an inline function has tp be available to the compiler at the time you attempt to reference/call the function.
This means that when compiling Parser.cc it need to be available - so it's no good putting it in IOSERs.cpp file because that file is not available at that time .

Put the function in IOSERs.h because you #include that file in Parser.cc
+1 to what guestgulkan said.

You have two options:

1) put the function body in the class itself
2) put the function body in the header below the class

1
2
3
4
5
6
7
8
9
10
class MyClass
{
  static bool Option1() { return true; }  // implicitly inlined
  static bool Option2();
};

inline bool MyClassOption2()  // inlined (note it must be in the header)
{
  return true;
}


A 3rd approach, if you plan on having many inline functions and don't want them in the class body, is to make another header and include that from your class header:

1
2
3
4
5
6
7
8
9
10
11
12
// in myclass.h
#ifndef __MYCLASS_H_INCLUDED__
#define __MYCLASS_H_INCLUDED__

class MyClass
{
  static bool Option3();
};

#include "myclass.hpp"  // or "myclass_inline.h", or whatever

#endif 

1
2
3
4
5
6
// in myclass .hpp

inline bool MyClass::Option3()
{
  return true;
}


Options 2 and 3 are benefitial because they allow you to avoid circular dependency issues if these functions use other classes.

Additional reading / Obligatory link: http://cplusplus.com/forum/articles/10627/ (specifically section 7)
Thanks guys, your replies make a lot of sense.
Topic archived. No new replies allowed.