0
votes
//class1.cpp
#include <iostream>
#include <stdlib.h>

using namespace std;

class class1
{
public:
    int var;
    class1(int i)
    {
        var = i;
    }
};

//class1.h:
#include <iostream>
#include <stdlib.h>

using namespace std;

class class1
{
public:
    int var;
    class1(int i = 0);
};

//main.cpp
#include <iostream>
#include <stdlib.h>
#include "class1.h"
using namespace std;

int main()
{
    class1 a(5);

    return 0;
}

error: 1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall class1::class1(int)" (??0class1@@QAE@H@Z) referenced in function _main

what the heck is going on? I swear I've made almost the exact same program before and It's worked.

2
So you're defining class1 both in the header and in the cpp?Andy Prowl
well, is there a makefile? And as Andy said, it is not clever to define the same class twice. And furthermore: What do you mean with "almost the exact same..."?Christian Graf
As Andy mentioned, it looks like you have the same method declared in both your header and source file. Try putting class1::class1(int i) : var(i) {} in your source file.Paul Dardeau
thanks everyone for helping me out. you guys rock!Nick Jarvis

2 Answers

2
votes

Change class1.cpp to something like:

//class1.cpp
#include "class1.h"

class1::class1(int i) : var(i) {}

You don't want to define the class itself again -- just define the member functions in the implementation file.

Then you'll build it something like:

g++ main.cpp class1.cpp

[of course, substituting the correct compiler name for the compiler you're using]

0
votes

Most likely you are not compiling both cpp files. Check your build settings and make sure that both main.cpp and class1.cpp are being compiled.

However you also have a serious problem. You are declaring class1 twice. Once in the header:

class class1
{
public:
    int var;
    class1(int i = 0);
};

... and again in the cpp:

class class1
{
public:
    int var;
    class1(int i)
    {
        var = i;
    }
};

In C++ there should be exactly one declaration for a class (and exactly one definition).

The way it works is you declare the class in your header, as you have already done, and then you define the members in the cpp, like this:

class1.cpp

#include "class1.h"

class1::class1(int i)
{
    var = i;
}