-1

In this question, the answer states that to inline a function for a static library, the function is declared inline in the header file and extern in the source file. However in C++, if this is done, a compiler error (Redeclaration of member is not allowed) is generated. What is the correct way to write a function in so it works the same way as in the C post?

Header:

class Int64
{
    uint64_t a;
public:
    inline void flip() { a = ~a; }

};

Source:

extern void Int64::flip(); // redeclaration of member is not allowed
me'
  • 494
  • 3
  • 14

1 Answers1

0

In C++, you can declare a function as inline only if function code is available in compile time (if you really want to inline that function code). So you cannot implement function body inside compiled static library which will not be available when you use this static library. If you do so, this function call will be similar to a normal function call.

From cppreference:

2) The definition of an inline function must be present in the translation unit where it is accessed (not necessarily before the point of access).

Although, you can define your inline function in your static library header(like header only function).

By the way, remember that inline is just a suggestion. compiler will decide to inline or not. This normally happens when you compile code with optimizations enabled, but especially when you don't optimize your code, you normally see that functions are not inlined.

As an example, check this small static library with containing 2 files:

test.h:

#pragma once

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

int sub(int a, int b);

test.cpp:

int sub(int a, int b)
{
    return a - b;
}

When you use this library, sum will be inlined and sub will be a normal normal call. Remember, you can even define sub as inline in library header too (without its body) and it will still be like a normal function call.

Afshin
  • 8,839
  • 1
  • 18
  • 53