Search code examples
c++functioninline

Problems with linking inline functions in C++


test2.h

#ifndef TEST2_H_INCLUDED
#define TEST2_H_INCLUDED
#include "test1.h"

inline int add(int,int);

#endif // TEST2_H_INCLUDED

test2.cpp

#include "test2.h"

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

main.cpp

#include <iostream>
#include "test2.h"

int main()
{
    std::cout << add(1,2);
    return 0;
}

Eror:

warning: inline function add(int,int) used but never defined
undefined reference to add(int,int)
ld returned 1 exit status

But if I remove inline from the files, the code compiles and executes fine. What am I doing wrong?

Note: I have seen all the threads on stack overflow,although they were similar to my question, the answers could not solve my issue

Using the mingw compiler with Code Blocks


Solution

  • //test2.h
    #ifndef TEST2_H_INCLUDED
    #define TEST2_H_INCLUDED
    #include "test1.h"
    
    inline int add(int a,int b) {
        return a+b;
    }
    
    #endif // TEST2_H_INCLUDED