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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Do not define variables in headers! unless they are const! +1
Are things that are const considered to be variable?
const bool myBad_IsNotVariable = true;
But the point that constants are allowed in headers is worth making, and I didn't make any distinction between variables and constants, so your comment adds some value. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.