GCC compiler error: “redefinition…previously defined”

前端 未结 4 1813
再見小時候
再見小時候 2021-02-02 15:39

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

相关标签:
4条回答
  • 2021-02-02 16:23

    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.

    0 讨论(0)
  • 2021-02-02 16:24

    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

    0 讨论(0)
  • 2021-02-02 16:30

    The same thing just happened to me and it was because I accidentally included the .c/.cpp file (within it) instead of the header file.

    That would definitely get you a lot of that error.

    0 讨论(0)
  • 2021-02-02 16:33

    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
    0 讨论(0)
提交回复
热议问题