Search code examples
c++functionclassinline-functions

Why my inline functions have linking error?


I am learning C++ and currently testing inline functions. If I run my code now I will have linking error, but if I change
inline void Test::print40() to void Test::print40() everything would be fine. Could you explain to me why I have an error and how to use inline function in this case.

// main.cpp file
#include "Test.h"
using namespace std;

int main()
{
    Test obj1;
    obj1.print40();
}
// Test.cpp file
#include <iostream>
#include "Test.h"

inline void Test::print40()
{
    std::cout << "40";
}
// Test.h file
#pragma once

class Test
{
public:
    void print40();
};

Solution

  • Inline function definition shall be in each compilation unit where it is ODR used.

    On the other hand in your project the compilation unit main does not know that the function is an inline function. So it can not find its definition.

    Move this definition from Test.cpp

    #pragma once
    
    class Test
    {
    public:
        void print40();
    };
    
    inline void Test::print40()
    {
        std::cout << "40";
    }
    

    to the header Test.h.

    The module Test.cpp is redundant.

    As the function is very simple and short then it could be defined in the class definition as for example

    class Test
    {
    public:
        void print40()
        {
            std::cout << "40";
        }
    };
    

    In this case it will be an inline function by default.