博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
inline函数必须在头文件中定义吗?
阅读量:2392 次
发布时间:2019-05-10

本文共 974 字,大约阅读时间需要 3 分钟。

前不久在写代码的时候遇到一个link错误,代码的原型如下所示,基本就是定义了一个基类和派生类,在派生类的一个成员函数中用到了基类定义的一个内联函数。

[cpp]
  1. // base.h  
  2. class Base  
  3. {  
  4. protected:  
  5.    void fun();  
  6. };  
  7.   
  8. // base.cpp  
  9. #include "base.h"  
  10. inline void Base::fun()  
  11. {}  
  12.   
  13. // derived.h  
  14. #include "base.h"  
  15. class Derived: public Base  
  16. {  
  17. public:  
  18.    void g();  
  19. };  
  20.   
  21. // derived.cpp  
  22. void Derived::g()  
  23. {  
  24.    fun(); //VC2008: error LNK2019: unresolved external symbol  
  25. }  
// base.hclass Base{protected:   void fun();};// base.cpp#include "base.h"inline void Base::fun(){}// derived.h#include "base.h"class Derived: public Base{public:   void g();};// derived.cppvoid Derived::g(){   fun(); //VC2008: error LNK2019: unresolved external symbol}

写这个内联函数的时候也没细想,结果违反了inline函数的要求。所谓内联函数,就是编译器将函数定义({...}之间的内容)在函数调用处展开,藉此来免去函数调用的开销。如果这个函数定义在头文件中,所有include该头文件的编译单元都可以正确找到函数定义。然而,如果内联函数fun()定义在某个编译单元A中,那么其他编译单元中调用fun()的地方将无法解析该符号,因为在编译单元A生成目标文件A.obj后,内联函数fun()已经被替换掉,A.obj中不再有fun这个符号,链接器自然无法解析。

所以,如果一个inline函数会在多个源文件中被用到,那么必须把它定义在头文件中。在C++中,这意味着如果inline函数具有public或者protected访问属性,你就应该这么做。

转载地址:http://somab.baihongyu.com/

你可能感兴趣的文章
java.rmi.ConnectException: Connection refused to host: 127.0.0.1
查看>>
数据库服务器 Cloudscape
查看>>
JAVA中使用Schema校验XML
查看>>
使用Jakarta-ORO库的几个例子
查看>>
使用BlazeDS实现Java和Flex通信
查看>>
使用 Apache MINA 开发高性能网络应用程序
查看>>
五分钟学会使用spring-data-cassandra快速实现数据的访问
查看>>
Build self-healing distributed systems with Spring Cloud
查看>>
如何利用Spring Cloud构建起自我修复型分布式系统
查看>>
Java代码实现设置系统时间
查看>>
java -D参数简化加入多个jar
查看>>
用Erlang开发的文档数据库系统CouchDB
查看>>
Apache Commons工具集简介
查看>>
Apache Cayenne—辣椒你吃了吗?
查看>>
云应用开发工具:Spring Cloud 1.0 正式发布
查看>>
[转]在VC中使用智能指针操作Excel
查看>>
关于Linux命令行环境下无线网卡的配置
查看>>
C++的朋友,你都在用什么连数据库啊
查看>>
Setup Kubernetes on a Raspberry Pi Cluster easily the official way!
查看>>
Installing Kubernetes on Linux with kubeadm
查看>>