gedamial
gedamial

Reputation: 1498

"Unresolved external symbol public _thiscall" linker error calling constructor and destructor

This may seem a duplicate. Instead, I've tried to find a similar post of my issue on StackOverflow but I can't resolve the linker error.

These are the linker errors:

1.

LNK2001 unresolved external symbol "public: __thiscall ged::Mathematichs::GFraction::~GFraction(void)" (??1GFraction@Mathematichs@ged@@QAE@XZ)

and 2.

LNK2001 unresolved external symbol "public: __thiscall ged::Mathematichs::GFraction::GFraction(int,int)" (??0GFraction@Mathematichs@ged@@QAE@HH@Z)

I've linked this project to my static library (where GFraction is defined). The problem isn't the linking to the library, because I've other classes in that lib that actually work.

This is the definition of the constructor and destructor

#ifndef GFraction_H
#define GFraction_H
#include <string>

namespace ged
{
   namespace Mathematichs
   {
      class GFraction
      {
      public:
          GFraction();
          GFraction(int num, int den);
      };
    }
  }
  #endif

In the .cpp file I have this:

#include "GFraction.h"

using namespace ged::Mathematichs;

GFraction::GFraction() {}
GFraction::~GFraction() {}

But, if I try to implement the body of the costructors and of the destructor direcly in the .h files, the linker errors goes away.

Why? I want those to be in the .cpp file!

Upvotes: 0

Views: 1365

Answers (1)

Mike Kinghan
Mike Kinghan

Reputation: 61337

In your .cpp file the using-directive:

using namespace ged::Mathematichs;

imports into the global namespace any definitions that already exist in namespace ged::Mathematichs. It does not add any new definitions to that namespace. In particular it does not add the definitions:

GFraction::GFraction() {}
GFraction::~GFraction() {}

to that namespace, where as the linker tells you, they need to be. They remain in the global namespace. Write your header file like this:

#ifndef GFraction_H
#define GFraction_H
#include <string>

namespace ged
{
    namespace Mathematichs
    {
        class GFraction
        {
        public:
            GFraction();
            ~GFraction(); // <- You need to declare the destructor
            GFraction(int num, int den);
        };
    }
}

And your .cpp file like this:

#include "GFraction.h"

namespace ged {
namespace Mathematichs {

GFraction::GFraction() {}
GFraction::~GFraction() {}
GFraction(int num, int den) { ... }

} // namespace Mathematichs
} // namespace ged

to put the definitions in the same namespaces as the declarations.

Upvotes: 1

Related Questions