如何防止.h文件中的函数的多个定义 [英] How to prevent multiple definitions of functions from .h file

查看:167
本文介绍了如何防止.h文件中的函数的多个定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的Core.h文件和许多其他的.cpp和.h文件,让我们说 - (a.cpp,ah,b.cpp,bh,c.cpp,ch)

I have a base Core.h file and many other .cpp and .h files, lets say - (a.cpp, a.h, b.cpp, b.h, c.cpp, c.h)

现在,我将Core.h文件包含在所有.h文件(ieah,bh和ch)中。在c.cpp中,我包括a.h和b.h文件。结果Core.h文件被包含两次,我得到的错误

Now, I have included Core.h file in all .h files (i.e. a.h, b.h and c.h) . And in c.cpp, I am including a.h and b.h file. As a result Core.h file is getting included two times and I am getting error of kind

/tmp/ccq7z6jY.o: In function `fileID2fileName(int)':
/home/Core.h:20: multiple definition of `fileID2fileName(int)'
/tmp/cciNkoqe.o:/home/Core.h:20: first defined here
/tmp/ccravW4I.o: In function `fileID2fileName(int)':
/home/Core.h:20: multiple definition of `fileID2fileName(int)'
/tmp/cciNkoqe.o:/home/Core.h:20: first defined here
/tmp/ccdUjOEu.o: In function `fileID2fileName(int)':
/home/Core.h:20: multiple definition of `fileID2fileName(int)'
/tmp/cciNkoqe.o:/home/Core.h:20: first defined here
collect2: ld returned 1 exit status


推荐答案

问题不是包括警卫:他们不会帮助跨越不同的翻译单位

The problem is not include guards : they won't help across different translation units.

您需要:


  • a .cpp文件并只在您的.h文件中声明

  • 在标题中定义 inline b
  • 在标头中定义 static

  • define your functions one time each in a .cpp file and only declare them in your .h file
  • define them inline in your headers
  • define them static in your headers

正如StackedCrooked ,包括静态函数定义但不使用它将导致适当的编译器警告。

As StackedCrooked rightly mentions, including the static function definition but not using it will result in an appropriate compiler warning.

这篇关于如何防止.h文件中的函数的多个定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆