C++ unresolved externals with simple class definition - c++

I keep getting an ununderstood "unresolved externals error from C++ from Visual Studio 2013. Thank you very much for your help so far. I have reduced the code even more to the following form (but the Problem persists):
main.cpp:
#include "Fibonacci.h"
using namespace std;
int main(void){
int RandInteger = 3;
Fibonacci Fib(RandInteger);
}
Fibonacci.h
class Fibonacci{
public:
Fibonacci(int n=0);
protected:
int m_n0, m_n1, m_n;
};
Fibonacci.cpp:
#include "Fibonacci.h"
Fibonacci::Fibonacci(int n){
m_n0 = 0;
m_n1 = 1;
m_n = n;
}
This code produces the following error in Visual Studio 2013:
Error 2 error LNK1120: 1 unresolved externals C:\Dropbox\todo\c++\Exam\Ex2\doesn't work\Exercise 2\fibo1\Fibo1\Debug\Fibo1.exe Fibo1
Error 1 error LNK2019: unresolved external symbol "public: __thiscall Fibonacci::Fibonacci(int)" (??0Fibonacci##QAE#H#Z) referenced in function _main C:\Dropbox\todo\c++\Exam\Ex2\doesn't work\Exercise 2\fibo1\Fibo1\main.obj Fibo1
I persists, but as soon as I replace the line in main.cpp with
Fibonacci Fib();
i.e. I do not pass the integer to the constructor, everything works (well it compiles an does nothing as expected).
Thanks for your help! I am really still stuck.

I finally found my error. Turns out that there is really nothing wrong with the code itself, but I've somehow destroyed my VisualStudio project. I am really not an expert for these things, but here is what worked for me:
create a new empty project in Visual Studio
copy your cpp files (all of them also the *.h files) into the new project folder
add them to this new project by right clicking the project and using "add New item"
I know this is the straightforward way to do it, but I cannot see how I broke the old project (it should be simple enough after all)
Thanks to all of you - thanks especially to otisonoza and Angew, for setting me on the right track that there is nothing wrong with the code (which works on their end), but with the Visual Studio project.

Your main function should return int
void main(void){
Should be
int main(){
EDIT: Thanks to otisonoza in the comments for pointing out that some compilers accept this definition of main. Other than this, I can't see any cause for compiler errors in your system. Are you sure you pasted the code exactly as you wrote it?
Also, what's up with the random tick after your definition of main?
}`
Also, you don't need to have semi-colons after each function in your .cpp file:
Fibonacci::Fibonacci(int na){
m_n0 = 0;
m_n1 = 1;
m_n = 2;
};
int Fibonacci::getNext(int FnM1, int FnM2){
return FnM1 + FnM2;
};
can be
Fibonacci::Fibonacci(int na){
m_n0 = 0;
m_n1 = 1;
m_n = 2;
}
int Fibonacci::getNext(int FnM1, int FnM2){
return FnM1 + FnM2;
}

Related

C++ Unit Test in Visual Studio 2019

I am having a problem with Visual Studio 2019 CPPUnitTestFramework. I follow the instructions, but every time I get an error. I have looked for tutorials, but anything I get is for Visual Studio 2017 and it does not solve my problem.
I am writing a program that uses OOP in C++ and I want to make unit tests, since it is going to be a considerably long project. The problem that I am having is that the program is not compiling in the test module.
Consider that I have the code such that I have the header file:
//A.h
#pragma once
class A
{
private:
// One parameter.
int a;
public:
// Add function.
int add(int, int);
// Subtract function.
int subtract(int, int);
A();
};
with the proper source file:
// A.cpp
#include "A.h"
int a;
int A::add(int alpha, int beta)
{
return alpha + beta;
}
int A::subtract(int alpha, int beta)
{
return alpha - beta;
}
A::A()
{
a = 4;
}
The structure of the program looks something like this:
To make my Unit Test, I right click on the "Solution 'TestTestUnit'" label and choose new project, look for the unit test, add the unit test and attach the reference, such that I get a file structure such as the one below:
To perform the unit test I write the code:
// TestUnitForTestTestUnit.cpp
#include "pch.h"
#include "CppUnitTest.h"
#include "../TestTestUnit/A.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace TestUnitForTestTestUnit
{
TEST_CLASS(TestUnitForTestTestUnit)
{
public:
TEST_METHOD(TestMethod1)
{
A first;
Assert::AreEqual(first.add(3, 2), 5);
}
};
}
When I try to run a test, the Test Explorer does nothing and throws the message: Aborting test run due to build failures. Please see the build for more details.
I cannot find the mistake here. The program runs perfect, but when instantiating a new "A" object the test fails. I am stuck here, are there any suggestions? What am I doing wrong (besides developing in Windows)?
UPDATE:
I have followed the suggestion to remove the namespace, as suggested by #ChrisMM, so that the test file now reads:
// TestUnitForTestTestUnit.cpp
#include "pch.h"
#include "CppUnitTest.h"
#include "../TestTestUnit/A.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
TEST_CLASS(TestUnitForTestTestUnit)
{
public:
TEST_METHOD(TestMethod1)
{
A first;
Assert::AreEqual(first.add(3, 2), 5);
}
};
such that when I run the Test Explorer gives the same message:
with error message:
1>------ Build started: Project: TestUnitForTestTestUnit, Configuration: Debug Win32 ------
1> Creating library C:\Users\<user>\Desktop\CPlusPlus\TestTestUnit\Debug\TestUnitForTestTestUnit.lib and object C:\Users\<user>\Desktop\CPlusPlus\TestTestUnit\Debug\TestUnitForTestTestUnit.exp
1>TestUnitForTestTestUnit.obj : error LNK2019: unresolved external symbol "public: int __thiscall A::add(int,int)" (?add#A##QAEHHH#Z) referenced in function "public: void __thiscall TestUnitForTestTestUnit::TestMethod1(void)" (?TestMethod1#TestUnitForTestTestUnit##QAEXXZ)
1>TestUnitForTestTestUnit.obj : error LNK2019: unresolved external symbol "public: __thiscall A::A(void)" (??0A##QAE#XZ) referenced in function "public: void __thiscall TestUnitForTestTestUnit::TestMethod1(void)" (?TestMethod1#TestUnitForTestTestUnit##QAEXXZ)
1>C:\Users\<user>\Desktop\CPlusPlus\TestTestUnit\Debug\TestUnitForTestTestUnit.dll : fatal error LNK1120: 2 unresolved externals
1>Done building project "TestUnitForTestTestUnit.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 1 up-to-date, 0 skipped ==========
Help would be appreciated.
You cannot put a test class inside a namespace. From the documentation
TEST_CLASS must be declared at namespace scope.
I suggest you to check if TestUnitForTestTestUnit has added Additional Dependencies. When I didn’t add it, the same problem as you occurred. After I added it, the program worked fine.
Right click TestUnitForTestTestUnit->Properties->C/C++->Linker->Input->Additional Dependencies-> add ..\TestTestUnit\Debug\*.obj

Creating class object defined in another project

I have a Visual C++ solution with 2 projects: rectangle and project3.
In rectangle project I have rect.cpp and rect.h.
rect.h
#ifndef rect_h
#define rect_h
class Rect
{
public:
Rect();
int m_h;
int m_w;
};
#endif //rect_h
rect.cpp
#include "rect.h"
Rect::Rect()
{
m_h = 1;
m_w = 5;
}
whenever I try to create rect object from the rectangle project it succeeds.
But when I try to do the same from the project3 it produces a linker error.
LNK2019: unresolved external symbol "public: __thiscall
Rect::Rect(void)" (??0Rect##QAE#XZ) referenced in function _main
1>C:\Users\mbaro\documents\visual studio
2017\Projects\Project2\Debug\Project3.exe : fatal error LNK1120: 1
unresolved externals
main.cpp (in project 3)
#include "rect.h"
using namespace std;
int main()
{
Rect* a = new Rect();
return 0;
}
I kind of feel that class definition is picked up successfully, but the linker can not link the constructor code from rect.cpp.
What is the problem and how to solve it?
Thanks.
The error is normal: you told the compiler where it could find the .h files, but you did not tell the linker where it could find the .obj files.
It may depend on the exact VS version, but in Project/Properties, you should find Linker/Input and there Additional dependencies. If you only need one or two object files (xxx.obj) from the other project, add them here. That way, you avoid code duplication, which will be a nightmare for future maintenance...
If you have many common files, you should considere to put them in an auxilliary project that would build a (static)library in the same solution, and then link the library in both project (and of course give access to header files of the library project for the other projects using the library).
I have already started writing a long, long answer. Then i realized, what You may be missing is that despite Your class is named "Person" the header file You should have added is named "rect.h".
Also Your constructor cannot have a declaration of values in the header file (EDIT:not true, I was mistaken). In the header file, try using:
Person(int h, int w);
You declare what will be needed, not what You already have. If You want those to be specifically what You wrote the constructor should be:
Person();
in .h
and
Person::Person()
{
m_h = 1;
m_w = 5;
}
in .cpp.
If You need more detailed description of using include, I have already written a big part of it, so don't hesitate to ask.

error LNK2019: unresolved external symbol "" referenced in function

Im currently getting the following error when I compile my code:
error LNK2019: unresolved external symbol "public: void __thiscall Agent::printSelf(void)" (?printSelf#Agent##QAEXXZ) referenced in function "public: void __thiscall World::processMouse(int,int,int,int)" (?processMouse#World##QAEXHHHH#Z) World.obj
Here is my code
Agent.h:
class Agent
{
public:
Agent();
void printSelf();
Agent.cpp:
void Agent::printSelf()
{
printf("Agent species=%i\n", species);
for (int i=0;i<mutations.size();i++) {
cout << mutations[i];
}
}
GLView.cpp:
void GLView::processMouse(int button, int state, int x, int y)
{
if(world->isDebug()) printf("MOUSE EVENT: button=%i state=%i x=%i y=%i\n", button, state, x, y);
if(button==0){
int wx= (int) ((x-conf::WWIDTH/2)/scalemult-xtranslate);
int wy= (int) ((y-conf::WHEIGHT/2)/scalemult-ytranslate);
world->processMouse(button, state, wx, wy);
}
mousex=x; mousey=y;
downb[button]=1-state;
}
void World::processMouse(int button, int state, int x, int y)
{
if (state==0) {
float mind=1e10;
float mini=-1;
float d;
for (int i=0;i<agents.size();i++) {
d= pow(x-agents[i].pos.x,2)+pow(y-agents[i].pos.y,2);
if (d<mind) {
mind=d;
mini=i;
}
}
if (mind<1000) {
//toggle selection of this agent
for (int i=0;i<agents.size();i++) {
if(i!=mini) agents[i].selectflag=false;
}
agents[mini].selectflag= !agents[mini].selectflag;
agents[mini].printSelf();
setControl(false);
}
}
}
Im pretty stumped. I haven't worked on this code in a long time, so im not sure what has changed to cause this. Anyone see anything wrong?
Most likely cause is that you're not linking in the object created from Agent.cpp.
You should check to ensure that it's part of the project and that you're using the correct version, compiled with this current compiler as well (since you state you haven't touched it in a while, it may be that the objects were built with an earlier compiler version, potentially making them incompatible - different name mangling methods, for example).
The first thing to try (once you've established all correct files are in the project) is a full clean-and-build.
On a few other points:
The error is occurring in World::processMouse meaning that the source for GLView::processMouse is probably irrelevant.
I find your mixing of printf and cout slightly ... disturbing. You should probably avoid printf for serious C++ programming. It works, but it's mostly intended for legacy C support.
Observed same issue in Visual studio 2008.
Clean, followed by Rebuild worked for me.

Compiler Error __ZTVN13..6..E

I'm currently struggeling with a compilerproblem. The problem is, that i use one of the MoSync example apps called "European Countries" (written in c++) to write my own. But when i compile the modified code, it gives me following error in response:
Controller.cpp:24: Error: Unresolved symbol '__ZTVN13Flightmanager6FlightE',
I already had a look at the example several times and i already copied the code from the example to mine, but it doesn't solve any problems.
In paticutlar i might understand what the error means (i do have c experience), but i've never seen such structured error. I also looked at namespacing conventions but there shouldn't be any problems.
//Flight.h
namespace Flightmanager
{
class Flight
{
public:
static int flightCounter;
/**
* The constructor creates the user interface.
*/
Flight(char *flightnumber, char *gate, char *departure, char *additionalinfo, char *destinationairport, char *destinationairportshort) {
this->_id = flightCounter;
flightCounter ++;
this->_flightnumber = flightnumber;
this->_gate = gate;
this->_departure = departure;
this->_additionalinfo = additionalinfo;
this->_destinationairport = destinationairport;
this->_destinationairportshort = destinationairportshort;
}
virtual ~Flight();
}
//Controller.h
#include [all other includes]
#include "../Model/Flight.h"
namespace Flightmanager
{
Controller::Controller():
mFlightArray(NULL),
mCurrentlyShownScreen(NULL)
{
initScreenSizeConstants();
initPlatformType();
//error: Unresolved symbol '__TZVN13Flightmanager6FlightE'.
initData();
//error: Unresoled symbol '__TZVN13Flightmanager6Flight13flightCounterE'.
mFlightTableView = new TableViewController(*this);//error: Unresoled symbol '__TZVN13Flightmanager6Flight13flightCounterE'.
mFlightDetailView = new DetailViewController();
}
}
I use MoSync Version 3.2
Build date: 121219-1556
Thx
You need to link in something that has definitions for:
Flight::flightCounter
Flight::~Flight()
whether that's a .o object file for Flight.cpp (or some source file) or a library depends on your project.

Unresolved External Symbol with extremely simple class (VS2010)

I am holily convinced that this is an extremely basic thing that every living human being is perfectly able to perform, yet somehow it's not working for me. The FAQ and many other threads/questions found through Google have not fixed this for me.
The situation is as follows: I have one Visual Studio 2010 project. This project is located in a Visual Studio 2010 solution. The project has the following files:
add.h:
class Adder {
public:
static int add(int i1, int i2);
};
add.cpp:
class Adder {
public:
static int add(int i1, int i2) {
return i1 + i2;
}
};
main.cpp:
#include "add.h"
int main() {
Adder::add(5, 6);
return 0;
}
When attempting to run this code, which looks fairly basic to me, I get the following linker error:
main.obj : error LNK2019: unresolved external symbol "public: static int __cdecl Adder::add(int,int)" (?add#Adder##SAHHH#Z) referenced in function _main
From what I could gather, this implies that the linker could not find the implementation for Adder::add(). However, the files are in exactly the same project, the generated .obj files are in exactly the same folder, and every single tutorial I've read on the subject of classes and header files tells me that this should work.
I've tried the following potential solutions thus far:
Add the project's own folder to additional includes/dependencies/sources/whatevers
Add extern identifiers to various things
Use a seperate namespace
Various other small adjustments in the hope they would work
So I guess my problem boils down to: How can I get the linker to notice the add.cpp file? Any help is appreciated, I've spent several hours on this now without success, while this seems like an extremely basic thing to me.
The following defines a whole new class
//add.cpp:
class Adder {
public:
static int add(int i1, int i2) {
return i1 + i2;
}
};
different from the one in the header, available only to this translation unit ("add.cpp").
What it should contain is:
//add.cpp
#include "add.h"
int Adder::add(int i1, int i2) {
return i1 + i2;
}
This implements the method defined in the class from the header add.h.