我有一个基础 Core.h 文件和许多其他 .cpp 和 .h 文件,比方说 - (a.cpp, a.h, b.cpp, b.h, c.cpp, c.h)
现在,我已将 Core.h 文件包含在所有 .h 文件(即 a.h、b.h 和 c.h)中。在 c.cpp 中,我包含了 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 文件中声明它们
- 在标题中
内联
定义它们 - 在标题中定义它们
static
正如 StackedCrooked 正确提到的那样,包括静态函数定义但不使用它会导致相应的编译器警告。
关于c++ - 如何防止 .h 文件中的多个函数定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25407905/