Simple code - Unresolved external symbol - c++ - c++

//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.

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]

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;
}

Related

g++ links fine with old object files with old code

base1.h
void base2::base22fun()
{
cout<<"inside base2::base22fun()"<<endl;
}
base1.cpp
#include "base1.h"
#include "iostream"
using namespace std;
void base1::base1fun()
{
cout<<"inside base1::base1fun()"<<endl;
}
base2.h
class base2
{
public:
virtual void base2fun();
};
base2.cpp
#include "base2.h"
#include "iostream"
using namespace std;
void base2::base2fun()
{
cout<<"inside base2::base2fun()"<<endl;
}
derived.h
#include "base1.h"
#include "base2.h"
class derived : public base1, public base2
{
public:
virtual void base1fun();
virtual void base2fun();
};
derived.cpp
#include "derived.h"
#include "iostream"
using namespace std;
void derived::base1fun()
{
cout<<"inside derived::base1fun"<<endl;
}
void derived::base2fun()
{
cout<<"inside derived::base2fun"<<endl;
}
global.cpp
#include "derived.h"
static derived d;
base1& b1=d;
base2& b2=d;
main.cpp
#include "base2.h"
#include "iostream"
using namespace std;
int main()
{
extern base2& b2;
cout<<b2.base2fun();
return 0;
}
I generated object file of all .cpp files using g++ base1.cpp base2.cpp derived.cpp global.cpp main.cpp -c
Then I linked them all, it worked fine.
Now I modified base2.h base2.cpp and main.cpp as follows
base2.h
class base2
{
public:
int padding;
virtual void base22fun();
virtual void base2fun();
};
base2.cpp
#include "base2.h"
#include "iostream"
using namespace std;
void base2::base22fun()
{
cout<<"inside base2::base22fun()"<<endl;
}
void base2::base2fun()
{
cout<<"inside base2::base2fun()"<<endl;
}
main.cpp
#include "base2.h"
#include "iostream"
using namespace std;
int main()
{
extern base2& b2;
cout<<b2.padding;
return 0;
}
I then recompiled base2.cpp, derived.cpp and main.cpp
I didn't recompile global.cpp, and used the old object file[global.o], and g++ linked them and the executable executed. How is this possible?
Thanks.
First of all, learn to use a makefile. That way, you don't have to type so much...
The linker will succeed as long as the required global symbols are present - in this case, the constructor of the class and probably the vtable of the class. Your object takes up extra space after the recompile, so it will overwrite another variable. If you were to add:
static int x = 42;
after static derived d; - and not initialize padding in the constructor, you'd see padding printed as 42.
And all of this is "undefined behaviour". It is allowed to fail in any plausible way - format your hard-disk, start world war III, or "kind of work with subtle side-effects". Using a makefile with the relevant dependencies set so that you automatically recompile objects.cpp whenever base2.h changes would be the right thing to do.
the object "static derived d;" is created when you run your exe. it has nothing to do with complie and link. so it worked.

Using interface to export class from dll

IClass (My interface):
#ifndef _ICLASS_H
#define _ICLASS_H
#include <sstream>
namespace Test
{
class __declspec(dllexport) IClass
{
public:
virtual ~IClass() {}
virtual bool Init(const std::string &path) = 0;
};
}
#endif
Class.h
#ifndef _CLASS_H
#define _CLASS_H
#include "IClass.h"
#include <memory>
#include <sstream>
#include <stdio.h>
namespace Test
{
class Class: public IClass
{
public:
Class();
~Class();
bool Init(const std::string &path);
};
}
#endif
Class.cpp
#include "Class.h"
namespace Test
{
Class::Class()
{
}
bool Class::Init(const std::string &path)
{
try
{
// do stuff
return true;
}
catch(std::exception &exp)
{
return false;
}
}
}
main (in exe, dll linked implicitly)
#include "IClass.h"
using namespace Test;
int main(int argc, char* argv[])
{
std::shared_ptr<IClass> test = std::make_shared<Class>(); // error: unreferenced Class
test->Init(std::string("C:\\Temp"));
}
At the moment Class is not declared
-> if I include Class.h to main following error occurs: LNK2019: unresolved external symbol: add class __declspec(dllexport) Class : public IClass resolve this linker issue, but is it ok to do it this way?
-> I also can't do this: std::shared_ptr<IClass> test = std::make_shared<IClass>();
(because it's not allowed to create an object of abstract class)
How can I solve this issue and is this best practise?
If you want your EXE to allocate a new "Class" object, the EXE code has to know the Class type. If you want to keep the Class type unknown from the EXE, one solution may be to export from your DLL a factory function, which will construct a Class object and return it as an IClass pointer.
See How to implement the factory pattern in C++ correctly

How do I run a function from a class file in C++?

I am trying to run a function from a class file, but it is not working and I get the the following error messages:
error LNK1120: 1 unresolved externals
error LNK2019: unresolved external symbol "public: void __thiscall NS::Class1::test(void)" (?test#Class1#NS##QAEXXZ) referenced in function _main
//Main.cpp
#include<iostream>
#include<string>
#include<Windows.h>
#include "Class1.h"
int main(){
NS::Class1 E;
E.test();
return 0;
};
//Class1.cpp
#include <Windows.h>
#include <string>
namespace NS{
class Class1{
Class1(){
OutputDebugString(L"Created.");
}
void test(){
OutputDebugString(L"Hello World");
}
};
}
//Class1.h
#ifndef _Class1_H_
#define _Class1_H_
namespace NS{
class Class1{
public:
void test();
};
}
#endif
In your source file, you're redefining the class, rather than defining its member functions. That will give undefined behaviour, since you're only allowed to define the class once. The source file should look more like:
#include "Class1.h"
#include <Windows.h>
NS::Class1::Class1(){
OutputDebugString(L"Created.");
}
void NS::Class1::test(){
OutputDebugString(L"Hello World");
}
You'll also need to modify the class definition in the header, since it doesn't declare a constructor.
Also, make sure that your project is compiling and linking both source files.
Your header file contains reserved IDs for the include guard and misses the declaration of the constructor. It should look like this:
#ifndef CLASS1_H
#define CLASS1_H
namespace NS {
class Class1
{
public:
Class1();
void test();
};
}
#endif
The definition of the class should not include the class declaration, it should include it, and should look more like this:
#include <Windows.h>
#include "Class1.h"
namespace NS {
Class1::Class1()
{
OutputDebugString(L"Created.");
}
void Class1::test()
{
OutputDebugString(L"Hello World");
}
}
I think your .cpp file might be causing the issue. Since you already created the class definition in your header with class member declarations, just import the Class1.h header in the Class1.cpp file and scope the member functions then defining their behavior.
so maybe try:
#include <Class1.h>
NS::Class1::Class1(){}//constructor
void NS::Class1::test(std::cout << "hi"){}

A LNK 2019 Error with my class I created

I have beeen using this template to make my classes to store data for various parts of my program.
//Classs that DOES NOT work
//"MiningPars.h"
#pragma once
#ifndef MININGPAR_H
#define MININGPAR_H
#include <iostream>
#include <fstream>
using namespace std;
class MiningPars
{
public:
int NumYears;
double iRate;
int MaxMineCap;
int MaxMillCap;
int SinkRate;
double ReclaimCost;
double PitSlope;
public:
MiningPars();
MiningPars(int numYears,double irate,int maxMineCap,int maxMillCap,
int sinkRate, double reclaimCost, double pitSlope): NumYears(numYears),
iRate(irate),MaxMineCap(maxMineCap),MaxMillCap(maxMillCap),SinkRate(sinkRate),
ReclaimCost(reclaimCost),PitSlope(pitSlope) {}
};
#endif
when I just declare a new mining par, it gives me the error
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall MiningPars::MiningPars(void)" (??0MiningPars##QAE#XZ) referenced in function "void __cdecl `dynamic initializer for 'par''(void)" (??__Epar##YAXXZ)
i.e. my code looks like this:
#include "MiningPars.h"
MiningPars par;//Error
vector <PredecessorBlock> PREDS;//is okay
void main()
{
par.iRate = .015;
//... etc.
}
most MSDN and other google searches say that i am not declaring things correctly or i haven't added appropriate dependanies, but it is the same format that I created another class. an example of my other work can be seen here:
//Classs that works
#pragma once
#ifndef PREDECESSOR_H
#define PREDECESSOR_H
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class PredecessorBlock
{
public:
int BLOCKID;
vector <int> PREDS_IDS;
int PredCount;
public:
PredecessorBlock();
PredecessorBlock(int blockID,vector<int>predsids,
int predcount) : BLOCKID(blockID),
PREDS_IDS(predsids), PredCount(predcount)
{}
};
#endif
so this has been confusing for me. I appreciate any advice you may give
main.obj : error LNK2019: unresolved external symbol "public: __thiscall MiningPars::MiningPars(void)"
Linker is complaining about not providing default constructor definition for MiningPars.
class MiningPars
{
...
MiningPars(); // This is declaration.
// Have you forgotten to provide the definition of it
// in the source file ?
And
MiningPars par;
the above statement invokes default constructor. If the definition is empty then do -
MiningPars() {}
in the class definition like you did for the parameterized constructor.
When you write
MiningPars par;
a par object of type MiningPars is created on the stack. To create an object, the constructor (in this case the default one, that is the one with no arguments) is called, but you don't define the constructor in your MiningParsclass.
To solve this, either define the constructor in your class cpp file, or if the constructor doesn't need to do anything, you can write the empty inline definition in the header file:
class MiningPars
{
public:
MiningPars() {}
...
};
or just don't declare the default constructor, the compiler will generate a empty one for you.
I agree with Mahesh
inside your class
MiningPars(){}

LNK2019 && LNK1120 errors when splitting my code in multiple files

My code is stored in a main.cpp file which contains the void main() function, and a class MyClass which I now want to split to another file. IDE is Microsoft Visual Studio 2008 Professional.
myclass.h
#include <tchar.h>
class MyClass {
public:
static bool MyFunction (TCHAR* someStringArgument);
};
myclass.cpp
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode () {
if (!someProperty) {
/* do something */
someProperty = true;
}
}
public:
static bool MyFunction (TCHAR* someStringArgument) {
doSomeOneTimeCode();
/* do something */
return true;
}
};
bool MyClass::someProperty = false;
main.cpp
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "myclass.h"
void main () {
if (MyClass::MyFunction(TEXT("myString"))) {
_tprintf(TEXT("Yay\n"));
}
}
However, when I try to run it, I get two linker errors.
LNK2019: unresolved external symbol ... (mentions MyClass::MyFunction)
LNK1120: 1 unresolved externals
What can I do to prevent these linker errors?
You declared two classes here. One of them is in myclass.h and the other is in myclass.cpp. Try the following instead:
myclass.h
#ifndef myclass_h_included
#define myclass_h_included
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode ();
public:
static bool MyFunction (TCHAR* someStringArgument);
};
#endif //!myclass_h_included
myclass.cpp
#include "myclass.h"
/*static*/ bool MyClass::someProperty = false;
void
MyClass::doSomeOneTimeCode() {
//...
}
bool
MyClass::MyFunction(TCHAR* someStringArgument) {
//...
}
Your main.cpp can stay the same. I would pay attention to UncleBens reply as well. One time initialization code should be hidden if at all possible.
Yo can't split a class definition in parts. It must be defined as a whole in one place. If you want to just have some methods of the class defined create a interface class that the MyClass class will later inherit. You should put the class' definition in a header file (myclass.h) and it's implementation in a cpp file (myclass.cpp). That way you can include the "myclass.h" in your main cpp file and use the class in your main function (which should be int main() or int main( int argc, char *argv[] )).
Strange that you didn't get a compiler error, as you are redefining MyClass.
Definitions (implementations) go into the cpp, and they are defined like this:
#include "myclass.h"
//helper functions, particularly if static, don't need to be in the class
//unnamed namespace means this stuff is available only for this source file
namespace
{
bool someProperty;
void doSomeOneTimeCode () {
if (!someProperty) {
/* do something */
someProperty = true;
}
}
}
bool MyClass::MyFunction (TCHAR* someStringArgument) {
doSomeOneTimeCode();
/* do something */
return true;
}