如何防止.h文件中函数的多个定义
How to prevent multiple definitions of functions from .h file
我有一个基本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正确提到的,包含静态函数定义但不使用它将导致适当的编译器警告。
相关文章:
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数