Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static inline methods?

Tags:

c++

static

inline

Okay,

Here is what I'm trying to do... Right now it is compiling but failing at linking... LNK2001

I want the methods static because there are no member variables, however I also want them inline for the speedups they provide.

What is the best way to do this? Here is what I have in a nutshell:

/* foo.h */
class foo
{
    static void bar(float* in);
};

/* foo.cpp */
inline void foo::bar(float* in)
{
    // some dark magic here
}

I'm trying to do this because I want to be able to go:

foo::bar(myFloatPtr);

foo doesn't have any member variables... it doesn't make sense to.

like image 725
Polaris878 Avatar asked Oct 27 '09 00:10

Polaris878


People also ask

What is a static inline?

Static inline functions are simple. Either a function defined with the inline function specifier is inlined at a reference, or a call is made to the actual function. The compiler can choose which to do at each reference. The compiler decides if it is profitable to inline at -xO3 and above.

Can a inline function be static?

Static local variables are not allowed to be defined within the body of an inline function.

What does inline static mean C++?

Static means the function should not be visible outside of the translation unit, inline is a hint to the compiler the programmer would like to have this function inlined. Those two are not related. Using static inline makes sense when the inlined function is not used outside of the translation unit.

Why is header inline static?

A static inline function is, in practice, likely (but not certain) to be inlined by some good optimizing compiler (e.g. by GCC when it is given -O2 ) at most of its call sites. It is defined in a header file, because it then could be inlined at most call sites (perhaps all of them).


3 Answers

If you are calling bar from another cpp file, other than foo.cpp, it needs to be in a header file.

like image 61
gatorfax Avatar answered Nov 15 '22 04:11

gatorfax


First, I would put them in a namespace instead, because there is no logic at all in that "class". Second, you may define the functions body in the header file directly to allow the compiler to see them. Otherwise, you need whole program optimization to be done by the linker for inlining those functions(AFAIK).

like image 36
Khaled Alshaya Avatar answered Nov 15 '22 05:11

Khaled Alshaya


You must define your inline function in the header file, not a separate implementation file. The definitions are needed when the header file is #included, if they are hoped to be inlined, after all.

The link failure you are seeing is because the declaration (in the header file) does not inform the compiler that the method is to be inline, whereas the implementation is inline, so not available for linking.

like image 23
John Zwinck Avatar answered Nov 15 '22 05:11

John Zwinck