在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;
}

错误

警告:内联函数add(int,int)已使用但从未定义
add(int,int)的未定义引用
ld返回1个退出状态

但是,如果我从文件删除inline代码将编译并执行良好。我在做什么错了?

注意:我已经看到了堆栈上的所有线程溢出,尽管它们与我的问题相似,但是答案无法解决我的问题

使用mingw编译器和代码

解决方法

您必须在头文件中定义内联函数,有关更多信息,请参见 https://stackoverflow.com/questions/5057021/why-are-c-inline-functions-in-the-header#:~:text=If%20you%20want%20to%20put,compiler%20cannot%20inline%20the%20function

,
pipe