Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ unresolved external symbol

Tags:

c++

I have a class setup and from that class I am using inheritance.

In file a.h

class a
{
public:
    virtual void print();
};

In file b.h:

#include "a.h"
#include <iostream>
class b: public a
{
public:
    void print();
};

And in b.cpp

#include "a.h"
#include "b.h"
void b::print(){};

In the main file I am including both of these files:

#include "a.h"
#include "b.h"

Yet I get an unresolved symbol for the virtual function print. The file a.obj is listed as the file generating the error What am I doing wrong? If I move b.cpp into b.h below the class definition it works fine.

like image 808
Joshua Enfield Avatar asked Dec 06 '10 02:12

Joshua Enfield


People also ask

What is unresolved external symbol in C?

The unresolved external symbol is a linker error that indicates it cannot find the symbol or its reference during the linking process.

How do I fix lnk2001 unresolved external symbol?

To fix this issue, add the /NOENTRY option to the link command. This error can occur if you use incorrect /SUBSYSTEM or /ENTRY settings in your project. For example, if you write a console application and specify /SUBSYSTEM:WINDOWS, an unresolved external error is generated for WinMain .

What is LNK2019 unresolved external symbol?

LNK2019 can occur when a declaration exists in a header file, but no matching definition is implemented. For member functions or static data members, the implementation must include the class scope selector. For an example, see Missing Function Body or Variable.

How do you fix undefined reference error in C?

Used the GCC compiler to compile the exp. c file. The error: undefined reference to function show() has appeared on the terminal shell as predicted. To solve this error, simply open the file and make the name of a function the same in its function definition and function call.


1 Answers

You have an implementation for b::print but not for a::print. What would happen if instantiated an object of class a and called print() on it? i.e.

a o;
o.print();

b::print overrides a::print but you still need to have an implementation of a::print (unless you make it pure virtual).

to make print pure virtual in a, define it like this:

virtual void print() = 0;

When a class has pure virtual functions, you cannot instantiate objects of that class. You must derive from that class and provide an implementation of any pure virtual functions before you have a class that can actually be instantiated.

like image 141
Ferruccio Avatar answered Sep 21 '22 05:09

Ferruccio