1

I am trying to understand how to work with header file in C++. Faced an error and I need know why and how to solve this.

I have 4 files.

main.cpp 
B.h 
A.h 
A.cpp 

Among them in some file. for ex. main.cpp or B.h if the line #include "B.h" exists, it gives me error.

Image:enter image description here

main.cpp:

#include <iostream>
#include "A.h"
#include "B.h"

int main()
{
    B obj_00;
    A obj_01(obj_00);

    return 0;
}

B.h:

#include <iostream>
#ifndef _B_H_
#define _B_H_

class B
{
private:
public:
    B();
    ~B();
};

B::B(){//some code};

B::~B(){//some code};

#endif //_B_H_

A.h:

#ifndef _A_H_
#define _A_H_

class A
{
private:
public:
    A();
    A(class B &temp);
    A(class A &temp);
    ~A();
};

#endif //_A_H_

A.cpp

#include <iostream>
#include "A.h"
#include "B.h"

A::A(A &temp){//some code};
A::A(B &temp){//some code};
A::~A(){//some code};

Error:

C:\Users\jamil\AppData\Local\Temp\ccNRBm6n.o: In function `B::B()':
E:/Personal/Programming/VSCode/test/B.h:13: multiple definition of `B::B()'
C:\Users\jamil\AppData\Local\Temp\ccsOpoic.o:E:/Personal/Programming/VSCode/test/B.h:13: first defined here
C:\Users\jamil\AppData\Local\Temp\ccNRBm6n.o: In function `B::B()':
E:/Personal/Programming/VSCode/test/B.h:13: multiple definition of `B::B()'
C:\Users\jamil\AppData\Local\Temp\ccsOpoic.o:E:/Personal/Programming/VSCode/test/B.h:13: first defined here
C:\Users\jamil\AppData\Local\Temp\ccNRBm6n.o: In function `B::~B()':
E:/Personal/Programming/VSCode/test/B.h:18: multiple definition of `B::~B()'
C:\Users\jamil\AppData\Local\Temp\ccsOpoic.o:E:/Personal/Programming/VSCode/test/B.h:18: first defined here
C:\Users\jamil\AppData\Local\Temp\ccNRBm6n.o: In function `B::~B()':
E:/Personal/Programming/VSCode/test/B.h:18: multiple definition of `B::~B()'
C:\Users\jamil\AppData\Local\Temp\ccsOpoic.o:E:/Personal/Programming/VSCode/test/B.h:18: first defined here
collect2.exe: error: ld returned 1 exit status
yo only
  • 97
  • 1
  • 2
  • 6
  • The important part of the duplicate is this: *When should I write the keyword 'inline' for a function/method in C++?* **Only when you want the function to be defined in a header.** – Fantastic Mr Fox Mar 02 '22 at 22:09

1 Answers1

1

This code:

B::B(){//some code};

B::~B(){//some code};

Will be pasted by the pre-processor into multiple translation units (A.cpp and main.cpp). It will be compiled 2 times and therefore violates the ODR (One definition rule). If you implemented it in the class:

class B
{
    B() { ... }

Then it would be automatically inlined, avoiding this issue. Since you have it out of the class you need to tell the compiler and the linker that you intended this using the inline keyword:

inline B::B(){//some code};

inline B::~B(){//some code};

Read more about the inline keyword here.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175