4

I had this header file that contain a lot of inline functions,after compile it says: multiple definition of function***,the function which looks like this:

inline int testab(int a, int b)
{
        return a>b;
}

after I add static in front of inline, the error is gone. Is it the right way to do it? Or am I missing something? I thought I could set up inline functions in a header like that.

unwind
  • 391,730
  • 64
  • 469
  • 606
user1051003
  • 1,211
  • 5
  • 16
  • 24

2 Answers2

7

inline or not, once the header gets copied in at least two files, you cannot link the files anymore.

The only way you can safely implement a function in a header is to use static. This way, each copy of the function would be invisible to the other ones.

Note that there is no restriction to using them together, so you can safely write:

static inline bool testab(int a, int b)
{
        return a>b;
}

Edit: More details

inline tells the compiler that you think the function is small enough to be inlined. That is you tell the compiler that you don't think the extra space for inlining the function matters much as opposed to the (slight) (possible) performance gain for it. Most compilers however are intelligent enough to decide that on their own and with your keyword, they would just tend a bit more to inline, and not necessarily always listen to you. This depends on the compiler, of course. Some compilers may completely ignore the keyword.

static on the other hand, means that whatever scope a static variable is defined, it will be invisible outside it. If you have a static variable in a function, it would be invisible outside it. If you have a static variable in a file (that is, a static global variable), it will be invisible outside it, which means the symbol is not there after compiling for the linker to see and get confused. That is why, if you have written a library in which there are global variables or functions that are not supposed to be visible outside the library, you should declare them as static.

Edit 2: Correction

Apparently, according to this answer, inline functions should not have its identifiers exported for the linker. Nonetheless, one can attach static to it either way just to make it more clear. Also apparently, some compilers export the identifier anyway, so in those cases static is indeed necessary.

Community
  • 1
  • 1
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
0

You need to specify static if you define a function in a header file, otherwise multiple symbol table definitions are created for the function (one in each .c file) and will collide when you try to link the respective object files. To define a inline function in a header, I belive you need:

static inline int foo(int x) __attribute__((always_inline))
    {
    return x+1;
    }

not sure if this is quite right though; see: http://gcc.gnu.org/onlinedocs/gcc-4.5.0/gcc/Inline.html#Inline.

David X
  • 3,998
  • 3
  • 29
  • 32