【问题标题】:Strange multiple definitions error with headers带有标题的奇怪的多个定义错误
【发布时间】:2026-01-14 07:25:07
【问题描述】:

我的项目中有一个奇怪的多重定义错误。 我正在使用#ifndef 预处理器命令来避免多次包含同一个文件。我清除了所有其他代码。这是我的简化文件:

1 - main.cpp

#include "IP.hpp"

int main()
{
    return 0;
}

2 - IP.cpp

#include "IP.hpp"

//some codes!

3 - IP.hpp

#ifndef IP_HPP_INCLUDED
#define IP_HPP_INCLUDED

unsigned char LUTColor[2];

#endif // IP_HPP_INCLUDED

在win7中使用代码块和gnu gcc,它说:

obj\Debug\main.o:C:\Users\aaa\Documents\prg\ct3\main.cpp|4|首先在这里定义|

||=== 构建完成:1 个错误,0 个警告 ===|

在我删除所有其他代码之前,错误是:

||=== 边缘测试,调试 ===|

obj\Debug\IP.o||在函数`Z9getHSVLUTPA256_A256_12colorSpace3b'中:|

c:\program files\codeblocks\mingw\bin..\lib\gcc\mingw32\4.4.1\include\c++\exception|62|`LUTColor'的多重定义|

obj\Debug\main.o:C:\Users\aaa\Documents\prg\edgetest\main.cpp|31|首先在这里定义|

||=== 构建完成:2 个错误,0 个警告 ===|

“LUTColor”在 IP.hpp 中!

怎么了?

【问题讨论】:

标签: c++ multiple-definition-error


【解决方案1】:

问题出在标题中 - 你需要:

#ifndef IP_HPP_INCLUDED
#define IP_HPP_INCLUDED

extern unsigned char LUTColor[2]; // Declare the variable

#endif // IP_HPP_INCLUDED
  • 不要在标题中定义变量!

您还需要指定一个源文件来定义LUTColor(IP.cpp 是显而易见的地方)。

另请参阅:What are extern variables in C,其中大部分适用于 C++ 和 C。

【讨论】:

  • 不要在标题中定义变量! 除非它们是 const! +1
  • const 的东西是否被认为是变量
  • const bool myBad_IsNotVariable = true;
  • 但是标题中允许使用常量这一点值得一提,而且我没有区分变量和常量,因此您的评论增加了一些价值。谢谢。
最近更新 更多