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

4
  • 2
    You probably need to read up on what inline means exactly in C++ (e.g.: 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 Commented Sep 25, 2020 at 10:12
  • @UnholySheep I am just learning about inline functions and following this page, so far I haven't done anything different Commented Sep 25, 2020 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 Commented Sep 25, 2020 at 10:16
  • @KamilCuk I put the definition in a header file from here Commented Sep 25, 2020 at 10:21

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.