如何防止.h文件中函数的多个定义

How to prevent multiple definitions of functions from .h file

本文关键字:定义 函数 何防止 文件      更新时间:2023-10-16

我有一个基本Core.h文件和许多其他。cpp和。h文件,比如- (a.p p, a.h, b.p p, b.h, c.p p, c.h)

现在,我已经将Core.h文件包含在所有.h文件中(即a.h, b.h和c.h)。在c.p中,我包含了a.h和b.h文件。结果Core.h文件被包含了两次,我得到的错误类型是

/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

问题不在于包含警卫:它们在不同的翻译单元之间没有帮助。

你需要:

  • 在.cpp文件中定义函数一次,只在.h文件中声明
  • 在标题
  • 中定义它们为inline
  • 在标题
  • 中定义它们为static

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