views:

1868

answers:

4

I'm getting a lot of " redefinition of x....x previously defined here". Please what does this error means?

+5  A: 

You are probably including a header file twice. Make sure your header files are surrounded by #ifndef statements.

http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html

Mehrdad Afshari
+9  A: 

You need to limit each file from being included only once. You can do this in 2 ways.

1) At the top of your header files put:

#pragma once

Or 2) if your compiler doesn't support that, put at the top/end of your header files:

#ifndef _MYFILE_H_
#define _MYFILE_H_
...
#endif

Replace MYFILE with the name of your file, and replace ... with the contents of the header file.

Brian R. Bondy
I think that #pragma only works in VC++, not in gcc. The #define trick is portable.
Gorpik
supoprted by gcc and vc++
Brian R. Bondy
Wikipedia says #pragma once is supported by VC++ and gcc http://en.wikipedia.org/wiki/Pragma_once .
Max Lybbert
+5  A: 

The error means that there is a symbol that has been defined in one place and an alternate definition has been made in another place.

This can occur if in cases like:

  • if you define two functions with the same name
  • if there is a mismatch between a function and it's prototype
  • you call a non-trivial function before it has been defined, and without a prototype

In this last case there will be a mismatch between the real function and the "implicit declaration" that the compiler assumes when it doesn't have a prototype to use.

These situations can be avoided by:

  • Ensuring that function prototypes are only declared once
  • Ensuring that all functions have unique names within their scope (ie. within a file if they are static, or unique if they are used between object files)
  • Be careful if using extern statements in source files to declare prototypes. Better to use a prototype from the appropriate header file.
  • Ensure that all functions have prototypes - either within the source file in the case of static functions, or in a header file if they are to be used by other object files.
  • Ensure that all header files can only be included once for each source file, by using either of the constructs suggested by Mehrdad and Brian R. Bondy
Andrew Edgecombe
A: 

The answer to the error for me is weird. It happened ten minutes ago...

My editor (for whatever reason) generates tens of copies of the source code in the same .mm (iPhone) source file. The error went away after the duplicated codes are removed.

ohho