Repeated Multiple Definition Errors from including same header in multiple cpps

后端 未结 9 1562
南方客
南方客 2020-11-27 06:12

So, no matter what I seem to do, I cannot seem to avoid having Dev C++ spew out numerous Multiple Definition errors as a result of me including the same header file in multi

相关标签:
9条回答
  • 2020-11-27 07:01

    While most of the other answers are correct as to why you are seeing multiple definitions, the terminology is imprecise. Understanding declaration vs. definition is the key to your problem.

    A declaration announces the existence of an item but does not cause instantiation. Hence the extern statements are declarations - not definitions.

    A definition creates an instance of the defined item. Hence if you have a definition in a header it is instantiated in each .cpp file, resulting in the multiple definitions. Definitions are also declarations - i.e. no separate declaration is needed if for instance the scope of the item is limited to one .cpp file.

    Note: the use of the word instantiation here really only applies to data items.

    0 讨论(0)
  • 2020-11-27 07:01

    This is what worked for me: linking the sources into separate libraries. (My problem was not with creating a program but one/many libraries.) I then linked (successfully) one program with the two libraries I created.

    I had two sets of functions (with one depending on the other) in the same source file, and declared in the same single header file. Then I tried to separate the two function sets in two header+source files.

    I tried with both #pragma once and include guards with #ifndef ... #define ... #endif. I also defined the variables and functions as extern in the header files.

    As Steve Fallows pointed out, the problem isn't with the compilation but rather with linkage. In my particular problem, I could get away with having two sets of functions, each in its own source file, compiling and then linking into two separate libraries.

    g++ -o grandfather.o -c grandfather.cpp
    g++ -o father.o -c father.cpp
    g++ -fPIC -shared -o libgf.so grandfather.o
    g++ -fPIC -shared -o libfather.so father.o
    

    This forces me to link my programs with both libgf.so and libfather.so. In my particular case it makes no difference; but otherwise I couldn't get them to work together.

    0 讨论(0)
  • 2020-11-27 07:08

    You need to define your variables as extern in the header file, and then define them in a cpp file as well. i.e.:

    extern MYSTRUCT Job_Grunt;
    

    in your header file, and then in a cpp file in your project declare them normally.

    The header file is only for definitions, when you instantiate a variable in the header file it will try to instantiate it every time the header is included in your project. Using the extern directive tells the compiler that it's just a definition and that the instantiation is done somewhere else.

    0 讨论(0)
提交回复
热议问题