简体   繁体   中英

How to define an inline free function (non member function) in C++?

In C++, I need to define some inline general functions. However, when I write the prototype in a header file and the implementation in a.cpp file, I encounter with "LNK2001 unresolved external symbol" error.

Shall I remove the .cpp file and implement the function in the header file?

I am trying to define some shared non-member math functions that can be used by other classes.

Header file:

inline void foo()
{
    //some code
}

.cpp file

//nothing

The name of the inline specifier is somewhat misleading, as it suggests that the function be inlined. However, inline foremost specifies the linkage of the function (it's also a hint to the compiler to consider inlining). For a function declared inline no linkable symbol is generated in the compiled object.

Therefore, inline functions only make sense when defined (not merely declared) in a header file, which is included by, possibly, many compilation units. The inline specifier than prevents multiple (in fact any ) symbols for this function to be emitted by the compiler in the respective object files.

If you need a small function only once for one compilation unit, you don't need to declare it anywhere else. Moreover, you don't need to declare it inline, but place it in the anonymous namespace to prevent it from being visible (in the object file generated).

So, either (that's most likely your use case)

// foo.hpp:
inline void foo(bar x) { /* ... */ }  // full definition

// application.cpp:
#include "header.hpp"

/* ... */ foo();

or

// application.cpp:
namespace {
    inline void foo(bar x)   // inline specifier redundant
    { /* ... */ }
}

/* ... */ foo();

If you want your function to be in-line, you have to provide the definition in the header. If you have it in a separate cpp file it wont be in-lined. The link error is usually due to not including the cpp file during linking stage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM