How do I run a function from a class file in C++? - 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"){}

Related

LNK2005 class X already defined in Y.obj

I have a starter project and I need to write a custom allocator and diagnostic tools for it. I made a class Class in which I have 2 methods for the custom allocator void alloc() void dealloc() and for the diagnostic tools void evaluate().Now, I declared an object test of type Class in CustomAllocator.h and use the 2 methods to allocate and deallocate memory with no problems. But when I try to call the evaluate() method in CustomAllocatorTest.cpp I got the linker error class Class test(?test##3VClass##A) already defined in CustomAllocatorTest.obj and LNK1169 one or more multiply defined symbols found.
Class.h
#pragma once
class Class
{
public:
void alloc() { std::cout << "alloc"; }
void dealloc() { std::cout << "dealloc"; }
void evaluate() { std::cout << "evaluate"; }
};
CustomAllocator.h
#ifndef _CUSTOM_ALLOCATOR_H_
#define _CUSTOM_ALLOCATOR_H_
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <stdlib.h>
#include "Class.h"
Class test;
#endif // _CUSTOM_ALLOCATOR_H_
CustomAllocator.cpp (#include "stdafx.h" includes "CustomAllocator.h")
#include "stdafx.h"
using namespace std;
int main()
{
test.evaluate();
return 0;
}
in your file CustomAllocator.h you declare test in global scope :
#ifndef _CUSTOM_ALLOCATOR_H_
#define _CUSTOM_ALLOCATOR_H_
#include "Class.h"
Class test; // <-- Declaration of test
#endif
But your CustomAllocator.h is included many times, in many places (in UseCustomAllocator.h and CustomAllocator.cpp) which will generate an already defined error for test variable.
Please see how to declare externe globale variable here #pragma once doesn't prevent multiple variable definitions

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(){}

Simple code - Unresolved external symbol - 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;
}

Compiling Error with C++ and namespace

Here's the whole code getting the errors:
Engine.h
#ifndef ENGINE_H
#define ENGINE_H
#include "DXManager.h"
namespace XEngine
{
class Engine
{
};
}
#endif
DXManager.h
#ifndef DX_MANAGER_H
#define DX_MANAGER_H
namespace XEngine
{
class Engine; // forward declaration
class DXManager
{
public:
void run(Engine *engine);
};
}
#endif
DXManager.cpp
#include <iostream>
#include "Engine.h"
#include "DXManager.h"
using namespace XEngine;
void DXManager::run(Engine *engine)
{
std::cout<<"DXManager::run"<<std::endl;
}
With these 30 lines of code, I'm getting 20 errors like:
'XEngine' : a namespace with this name does not exist
'XEngine' : a symbol with this name already exists and therefore this name cannot be used as a namespace name
syntax error : identifier 'Engine'
Clearly, I'm missing something important here. What am I doing wrong?
note: I am aware that circular dependency is a bad thing, but in my particular case I believe that it is relevant.
In DXManager.cpp you are not just using some names from namespace XEngine. You define the function in that namespace.
So must be:
DXManager.cpp
#include <iostream>
#include "Engine.h"
#include "DXManager.h"
namespace XEngine {
void DXManager::run(Engine *engine)
{
std::cout<<"DXManager::run"<<std::endl;
}
}
AFAIK some of the compilers (like MSVC) process using variant too.
But it is not correct because your syntax tries to define function ::DXManager::run - not ::XEngine::DXManager::run you intend to define.
In the forward-declaration of class Engine the namespace XEngine doesn't exist at this point.
A workaround would be moving the declaration inside the namespace block.
When Engine.h includes DXManager.h, the latter defines a class XEngine::Engine without declaring the namespace first.

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