当前位置: 首页 > article >正文

C++ 隐式内联函数

在阐述隐式内联函数之前,可以先看下下列代码:

/* C */
#include <stdint.h>

namespace rest_api {
    class api_entry {
        public:
            api_entry()     = default;
            ~api_entry()    = default;
           static api_entry& get_instance()
            {
                static api_entry instance;
                return  instance;
            }

            /*  Start monitoring events transmitted by the server   */
            int32_t run();
    };

};  /* namespace rest_api */

这是我在开发Fast-cgi的程序时,写一个实现rest_api标准的组件,当我直接声明它来使用时出现了问题,下列是main里的用法:

#include "http/rest_api/rest_api.h"

int main()
{
    /* event loop */
    return rest_api::api_entry::get_instance().run();
}

虽然有声明,但是在构建时报错:

/usr/bin/ld: CMakeFiles/main.dir/src/main.cpp.o: in function `main':
main.cpp:(.text+0x9): undefined reference to `rest_api::api_entry::get_instance()'
collect2: error: ld returned 1 exit status

提示没有找到该函数的定义,原因是这样的,当你在类内部声明一个函数时除了构造函数、析构函数、模板函数、操作符重载函数以外的普通成员函数都会被隐式转换为内联函数,内联函数一般是不会分配内存空间的,不会产生符号定义,所以即便你声明了也会提示你找不到这个函数。
解决方案是把它作为lib或者使用编译器属性强制C++不要让其隐式转换为内联函数,下列是采用GNU G++属性的方式解决这个问题:

/*  Get a unique instance   */
/*  TODO: Writing implementations within a class
/*        except for constructor and destructor or operator
/*        overloading functions, will be considered as implicit
/*        inline functions 
*/
[[gnu::noinline]] static api_entry& get_instance()
{
  static api_entry instance;
  return  instance;
}

http://www.kler.cn/news/329898.html

相关文章:

  • VSCODE驯服日记(四):配置SFML图形环境
  • 波阻抗,是电场矢量的模值/磁场矢量的模值
  • SQL常用语法
  • DpCas 镜头场景分割 Scene Segmentation
  • 基于微信小程序爱心领养小程序设计与实现(源码+定制+开发)
  • MySQL存储和处理XML数据
  • 数据分析-28-交互式数据分析EDA工具和低代码数据科学工具
  • 【rCore OS 开源操作系统】Rust 练习题题解: Structs
  • 探索未来:掌握python-can库,开启AI通信新纪元
  • linux dbus介绍,彻底懂linux bluez dbus
  • JS进阶 2——构造函数、数据常用函数
  • 【Java】—— 集合框架:Collection接口中的方法与迭代器(Iterator)
  • 基于Springboot的在线订餐系统设计与实现(论文+源码)_kaic
  • STM32使用Keil5 在运行过程中不复位进入调试模式
  • Html5知识点介绍
  • SpringCloud-基于Docker和Docker-Compose的项目部署
  • python UNIT3 选择与循环(1)
  • 使用微服务Spring Cloud集成Kafka实现异步通信
  • 【Java基础】Java面试基础知识QA(上)
  • 关于主流电商API接口的测试及返回【douyin电商SKU接口】
  • 螺狮壳里做道场:老破机搭建的私人数据中心---Centos下Docker学习01(环境准备)
  • 基于深度学习的图像去噪与去模糊
  • ACL(Access Control List)访问控制列表
  • 彩虹易支付最新版源码及安装教程(修复BUG+新增加订单投诉功能)
  • 推送k8s镜像到阿里云服务器
  • 滚雪球学Oracle[2.5讲]:数据库初始化配置
  • 开发指南063-上传文件到百度网盘
  • MindSearch 部署到Github Codespace 和 Hugging Face Space
  • VUE3.5版本解读
  • 5G NR 协议规范表(对应3GPP 协议编号)