【问题标题】:Problems with linking inline functions in C++在 C++ 中链接内联函数的问题
【发布时间】:2020-09-25 10:09:43
【问题描述】:

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 编译器

【问题讨论】:

  • 您可能需要阅读 inline 在 C++ 中的确切含义(例如:en.cppreference.com/w/cpp/language/inline)。您似乎试图让编译器在函数使用时内联函数,这不是关键字的用途
  • @UnholySheep 我只是在学习内联函数并关注this 页面,到目前为止我还没有做任何不同的事情
  • 您链接到的页面将函数声明和定义合并为一个。你把它分开了,你不能按照你想要的方式做
  • @KamilCuk 我把定义放在头文件from here

标签: c++ function inline


【解决方案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

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2012-10-02
    • 2020-07-23
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多