奇怪的标头多重定义错误

Strange multiple definitions error with headers

本文关键字:定义 错误      更新时间:2023-10-16

我在我的项目中有一个奇怪的多个定义错误。我使用#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

使用代码块&Gnu GCC在win7中,它说:

objDebugmain.o:C:UsersaaaDocumentsprgct3main.cpp|4|这里首次定义|

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

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

||=== edgetest, Debug ===|

obj 调试 IP。0 ||In function ' Z9getHSVLUTPA256_A256_12colorSpace3b':|

c:program filescodeblocksmingwbin..libgccmingw324.4.1includec++exception|62|多重定义' LUTColor'|

objDebugmain.o:C:UsersaaaDocumentsprgedgetestmain.cpp|31|这里首次定义|

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

和'LUTColor'在IP.hpp !

怎么了?

问题在标题-你需要:

#ifndef IP_HPP_INCLUDED
#define IP_HPP_INCLUDED
extern unsigned char LUTColor[2]; // Declare the variable
#endif // IP_HPP_INCLUDED
  • 不要在头文件中定义变量!

您还需要指定一个源文件来定义LUTColor (IP.cpp是明显的位置)。

参见:什么是C中的外部变量,其中大部分适用于c++和C。