문제

I have a strange multiple definitions error in my project. I'm using the #ifndef preprocessor command to avoid including the same file multiple times. I cleared all other code. Here are my simplified files:

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

Using codeblocks & gnu gcc in win7, it says:

obj\Debug\main.o:C:\Users\aaa\Documents\prg\ct3\main.cpp|4|first defined here|

||=== Build finished: 1 errors, 0 warnings ===|

Before I deleted all of the other code, the error was:

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

obj\Debug\IP.o||In function `Z9getHSVLUTPA256_A256_12colorSpace3b':|

c:\program files\codeblocks\mingw\bin..\lib\gcc\mingw32\4.4.1\include\c++\exception|62|multiple definition of `LUTColor'|

obj\Debug\main.o:C:\Users\aaa\Documents\prg\edgetest\main.cpp|31|first defined here|

||=== Build finished: 2 errors, 0 warnings ===|

And 'LUTColor' is in IP.hpp !

What's wrong?

도움이 되었습니까?

해결책

The problem is in the header - you need:

#ifndef IP_HPP_INCLUDED
#define IP_HPP_INCLUDED

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

#endif // IP_HPP_INCLUDED
  • Do not define variables in headers!

You also need to nominate a source file to define LUTColor (IP.cpp is the obvious place).

See also: What are extern variables in C, most of which applies to C++ as well as C.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top