3

Suppose we have B.h, main.cpp and B.cpp, main.cpp -> main.obj and B.cpp -> B.obj

Because of separate compilation, I think main.obj and B.obj should both have the definition of class B. Why it doesn't have the error:multiple definition of B when linking them?

B.h

#ifndef B_H
#define B_H

class B {
    public:
        void fun();
    private:
        int x = 0;
};

#endif

B.cpp

#include "B.h"

void B::fun() {
    
}

main.cpp

#include "B.h"

int main() {
}
seineo
  • 93
  • 6

1 Answers1

3

Neither main.obj nor B.obj contains the definition of B. Object files have no need to contain type definitions, since the purpose of type definitions is to help produce the executable code and data for an object file. If two source files both operate on the same type, they both need to have that type’s definition included.

Sneftel
  • 40,271
  • 12
  • 71
  • 104