Historically, the inline keyword is used to create inline functions and variables that can be expanded by the compiler. However, the compiler can automatically expand functions in optimizations. So, we are not required to use this keyword.

In modern times, inline keyword is used to define same name functions in multiple translation units without violating ODR.

Following program shows this,

lib.cpp

inline int add(int a)
{
    return a + 1;
}

main.cpp

#include "../helpers/stdout.h"
 
inline int add(int a, int b)
{
    return a + b;
}
 
int main(int argc, char const *argv[])
{
 
    print(add(2, 3));
    return 0;
}

Compiling this should not give any error and it should work as expected.

g++-15 -ggdb -std=c++20 main.cpp lib.cpp ../helpers/stdout.cpp  -o ma
in.out

For an inline function to work, the translation unit should have the definition of it. Inline function can be defined after the point of usage given the forward declaration but the compiler might not expand it.

Note

Inline variables has external linkage by default so that they become visible to linker and linker can de-duplicate the definitions.

Inline functions in header files

Inline functions are good candidates to define in header files as we just need to include header file in source code.

lib.h

#ifndef LIB_H
#define LIB_H
int add(int a, int b)
{
    return a + 1;
}
#endif

main.cpp

#include "../helpers/stdout.h"
#include "lib.h"
 
int main(int argc, char const *argv[])
{
 
    print(add(2, 3));
    return 0;
}

References

  1. https://www.learncpp.com/cpp-tutorial/inline-functions-and-variables/
  2. https://en.cppreference.com/w/cpp/language/inline.html