0

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

  • 2
    You probably need to read up on what `inline` means exactly in C++ (e.g.: https://en.cppreference.com/w/cpp/language/inline). You seem to be trying to get the compiler to inline the function at its usage, which is not what the keyword is for – UnholySheep Sep 25 '20 at 10:12
  • @UnholySheep I am just learning about inline functions and following [this](https://www.tutorialspoint.com/cplusplus/cpp_inline_functions.htm#:~:text=To%20inline%20a%20function%2C%20place,is%20more%20than%20a%20line.) page, so far I haven't done anything different –  Sep 25 '20 at 10:15
  • The page you linked to has the function declaration and definition merged into one. You have it separated, which you cannot do the way you are trying to – UnholySheep Sep 25 '20 at 10:16
  • @KamilCuk I put the definition in a header file [from here](https://stackoverflow.com/questions/22249510/do-c-inline-functions-have-to-be-declared-in-same-file) –  Sep 25 '20 at 10:21

2 Answers2

1

You have to define the inline function inside the header file, more info under https://stackoverflow.com/questions/5057021/why-are-c-inline-functions-in-the-header#:~:text=If%20you%20want%20to%20put,compiler%20cannot%20inline%20the%20function.

SushiWaUmai
  • 348
  • 6
  • 20
1
//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
Allen ZHU
  • 690
  • 5
  • 14