multiple definitions error in c++ and solution to solve this issue

starkk92 picture starkk92 · Sep 20, 2013 · Viewed 48.6k times · Source

I am new to C++. I have some doubts regarding multiple definitions error in C++.

Let's say I have 3 files in a program. One header file and 2 .cpp files. I have included the header file in both the .cpp files.

  1. I have declared a class in the header file and I have defined the class in each of the .cpp files in exactly the same way. So will this type of implementation cause multiple definitions error? If so, is it because it has two copies of class definitions and the compiler doesn't know which one to take during linkage of two .o files?

Can we solve this problem by using extern in header file and defining the class in only one of the files?If we can solve the issue by using this method,do we have to include the .cpp(with class definition) into other .cpp file(with no class definition)?

  1. I have declared and defined a class in header file. Is this case the same as above (mentioned in 1)?

  2. I have declared a class in the header file and I have defined the class in each of the .cpp files but the definitions (function bodies)differs. So will this type of implementation causes multiple definitions error? If so, how can we solve this problem where the functions bodies differs in the .cpp files?

Answer

john picture john · Sep 20, 2013

1) You solve this by 'defining the class' in only one cpp file. Why would you want to define it in two files?

2) Don't define things in header files, only declare them. There are exceptions to this rule, for instance inline functions. Also classes themselves can defined more than once (by this I mean declaring the methods and data members of the class, (i.e. writing class XYZ { ... };) but each definition must be identical. The simplest way to achieve this is to define a class once in a header file. Then each definition resulting from including that header file in multiple places will necessarily be identical.

3) This one is even sillier, it's one thing to define somethiing twice, but define it twice and differently each time makes even less sense.

I guess the issue is why you think it might sometimes be necessary to define things more than once. Don't do that.

You should also make it clear what you mean by 'define the class'. I've taken that to mean define the methods and static members of the class. But if you have something else in mind that might be a source of confusion. As usual the best way to avoid this kind of terminology confusion is to post some code.