0

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?

Community
  • 1
  • 1
ajlajlajl
  • 177
  • 1
  • 14
  • possible duplicate of [Repeated Multiple Definition Errors from including same header in multiple cpps](http://stackoverflow.com/questions/223771/repeated-multiple-definition-errors-from-including-same-header-in-multiple-cpps) – Michael Burr Dec 26 '11 at 08:33

1 Answers1

3

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.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278