Unresolved external symbol of constructer when using STL vectors

104 views Asked by At

So, I have a pretty simple project in VS2019 that includes three files:

a.h

#pragma once

class A {
public:
    A();
};

a.cpp

class A {
public:
    A() {}
};

main.cpp

#include <vector>
#include "a.h"

int main() {
    std::vector<A> va;
    va.emplace_back();
    return 0;
}

It works fine without vectors. But this code throws an linker error about constructor. What I really don't understand is if I change a.cpp that way:

#include "a.h"

A::A() {}

it works fine. Why doesn't the linker see the constructor in the body of the class?

1

There are 1 answers

0
Vlad from Moscow On BEST ANSWER

The compilation unit with main sees only this declaration

class A {
public:
    A();
};

and indeed the constructor is not defined.

The declaration of the class A in the module a.cpp breaks the one definition rule. That is the class declared in a.cpp is not the same as the class declared in a.h.

In the case of this definition of the module a.cpp

#include "a.h"

A::A() {}

the both compilation units have the same class declaration and for this class there is defined the constructor.