C++ function failing - c++

My c++ program fails with below reasons:
Error 1 error LNK2005: "public: void __thiscall dataHolder::addData(int)" (?addData#dataHolder##QAEXH#Z) already defined in Source.obj
Error 2 error LNK2005: "public: void __thiscall dataHolder::findUnique(void)" (?findUnique#dataHolder##QAEXXZ) already defined in Source.obj
Error 3 error LNK2005: "public: void __thiscall dataHolder::printData(void)" (?printData#dataHolder##QAEXXZ) already defined in Source.obj
Error 4 error LNK1169: one or more multiply defined symbols found
However, when I moved all definitions in once source c++ file, it worked fine.
Below is my source code:
source.cpp file:
#include "dataClass.h"
void main(){
dataHolder v1;
for(int i=1;i<=10;i++)
v1.addData(i);
for(int i=1;i<=5;i++)
v1.addData(i);
v1.printData();
v1.findUnique();
}
dataClass.h file:
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include <map>
using namespace std;
class dataHolder{
public:
void printData();
void addData(int data);
void findUnique();
int uniqueData();
private:
vector<int> dataVector;
};
void dataHolder::addData(int val){
dataVector.push_back(val);
};
void dataHolder::printData(){
vector<int>::iterator vIt;
for(vIt=dataVector.begin();vIt<dataVector.end();vIt++){
cout<< *vIt<<endl;
};
};
void dataHolder::findUnique(){
map<int ,int> dataMap;
vector<int>::iterator vIt;
map<int ,int>::iterator mIt;
for(vIt=dataVector.begin();vIt<dataVector.end();vIt++){
if(dataMap.find(*vIt)==dataMap.end())
dataMap[*vIt]=1;
else
dataMap[*vIt] = dataMap[*vIt]+1;
};
for(mIt=dataMap.begin();mIt != dataMap.end();mIt++){
if(mIt -> second == 1)
cout<<mIt->first<<" is Unique"<<endl;
};
};
please guide for the issue.

The problem is that you define the dataHolder member functions in the header file. That means that every source file including your header file will have the definition of those member functions.
You can do that, but then you have to mark them as inline, or possibly static.
What you should do is make another source file, which contains the member function definitions, and include that source file in your project so it's compiled and linked with.

Move your implementations for the class methods into a cpp file (not the header file). This way, they don't get included multiple times.

You just should move class members implementation to .cpp file. For example dataClass.cpp:
#include "dataClass.h"
void dataHolder::addData(int val){
dataVector.push_back(val);
};
void dataHolder::printData(){
vector<int>::iterator vIt;
for(vIt=dataVector.begin();vIt<dataVector.end();vIt++){
cout<< *vIt<<endl;
};
};
void dataHolder::findUnique(){
map<int ,int> dataMap;
vector<int>::iterator vIt;
map<int ,int>::iterator mIt;
for(vIt=dataVector.begin();vIt<dataVector.end();vIt++){
if(dataMap.find(*vIt)==dataMap.end())
dataMap[*vIt]=1;
else
dataMap[*vIt] = dataMap[*vIt]+1;
};
for(mIt=dataMap.begin();mIt != dataMap.end();mIt++){
if(mIt -> second == 1)
cout<<mIt->first<<" is Unique"<<endl;
};
};

You could also use header guards to ensure that your header file is loaded only once.
#ifndef _DATA_CLASS_H_
#define _DATA_CLASS_H_
#include <...>
class dataHolder {
...
}
/* Function Definitions */
#endif /* _DATA_CLASS_H_ */
See this question: C++ - header guards

Related

How do I avoid `already defined` linking error with pugixml if two static libs contain pugixml objs?

So I have 2 static libs defined like this:
StaticLib1
// StaticLib1.h
#pragma once
class StaticLib1
{
public:
void doSomething1();
};
cpp:
// StaticLib1.cpp
#include "pugixml.hpp"
#include "StaticLib1.h"
void StaticLib1::doSomething1()
{
pugi::xml_node node;
}
StaticLib2
// StaticLib2.h
#pragma once
class StaticLib2
{
public:
void doSomething2();
};
cpp:
// StaticLib1.cpp
#include "pugixml.hpp"
#include "StaticLib2.h"
void StaticLib2::doSomething2()
{
pugi::xml_node node;
}
Main
#include <iostream>
#include "StaticLib1.h"
#include "StaticLib2.h"
int main(int argv, char** argc)
{
StaticLib1 staticlib1;
StaticLib2 staticlib2;
staticlib1.doSemething1();
staticlib2.doSemething2();
getchar();
return 0;
}
Now, if I build this. I get a lot of linking errors. Here are the first few linking errors:
3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "public: __thiscall pugi::xml_attribute::xml_attribute(struct pugi::xml_attribute_struct *)" (??0xml_attribute#pugi##QAE#PAUxml_attribute_struct#1##Z) already defined in StaticLib1.lib(StaticLib1.obj)
3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "public: __thiscall pugi::xml_attribute::xml_attribute(void)" (??0xml_attribute#pugi##QAE#XZ) already defined in StaticLib1.lib(StaticLib1.obj)
3>StaticLib2.lib(StaticLib2.obj) : error LNK2005: "private: __thiscall pugi::xml_attribute_iterator::xml_attribute_iterator(struct pugi::xml_attribute_struct *,struct pugi::xml_node_struct *)" (??0xml_attribute_iterator#pugi##AAE#PAUxml_attribute_struct#1#PAUxml_node_struct#1##Z) already defined in StaticLib1.lib(StaticLib1.obj)
...
...
Now, I understand that this linking error is because there is a pugixml.obj inside StaticLib1.lib, and there is pugixml.obj inside StaticLib2.lib. But I don't understand why this would cause linking error with pugixml signatures. Why would they be defined twice? If I call staticlib1.doSomething1() shouldn't main not care if there are multiple definitions of pugi? Shouldn't staticlib1.doSomething1() handle all of that?
on the pugiconfig.hpp I have these specific settings:
#ifndef HEADER_PUGICONFIG_HPP
#define HEADER_PUGICONFIG_HPP
#define PUGIXML_WCHAR_MODE
#define PUGIXML_HEAD_ONLY
#include "pugixml.cpp"
#endif
So yes, from user0042advice, I realize it is better to compile a pugixml.lib on your own rather than having #include "pugixml.cpp" on the config. I'm working with legacy code so these surprises are there. Now, I've fixed my issue and made my company code slightly cleaner.

Linker error LNK2019 and LNK1120 [duplicate]

This question already has answers here:
Why can templates only be implemented in the header file?
(17 answers)
Closed 7 years ago.
I know this problem is well known, but none of the solutions work for me. I know a popular cause of this error is the compiler can't find the definition of a function in any of the source files, but I have defined the function them.
I am using Visual studio 2015 community.
Form.h
#pragma once
template<typename T>
class Form
{
public:
void GenerateForm(T i);
};
Form.cpp
#include "stdafx.h"
#include "Form.h"
template<typename T>
void Form<T>::GenerateForm(T i)
{
std::cout << i << endl;
}
Main.cpp
#include "stdafx.h"
#include "Form.h"
int main()
{
Form<int> f;
f.GenerateForm(12);
return 0;
}
Error:
PrimeForm.obj : error LNK2019: unresolved external symbol "public: void __thiscall Formula<double>::GenerateForm(int)" (?GenerateForm#?$Formula#N##QAEXH#Z) referenced in function _main
C:\Users\John\Dropbox\Visual Studio 2015\PrimeForm\Debug\PrimeForm.exe : fatal error LNK1120: 1 unresolved externals
When you try to compile form.cpp the compiler doesn't know what type T will be. Therefore it won't be able to compile this as an object file to be linked with your compiled main.cpp object file.
You'll need to include all of the declarations and definitions of a templated class to the files that need it (in this case your main.cpp file).
This can be simply done as follows:
Form.h
#pragma once
template<typename T>
class Form
{
public:
void GenerateForm(T i);
};
#include "Form.template" /* Note include Form.template here */
Form.template
#include "stdafx.h"
/* Don't include form.h in this file */
template<typename T>
void Form<T>::GenerateForm(T i)
{
std::cout << i << std::endl;
}
main.cpp
#include "stdafx.h"
#include "Form.h" /* including Form.h will include Form.template as well */
int main()
{
Form<int> f; /* Compiler now knows to instantiate a Form class with type Int as the template parameter */
f.GenerateForm(12);
return 0;
}
Note the main difference is that you don't include "Form.h" in Form.template but include "Form.template" at the bottom of Form.h
It is better practice to use the ".template" file ending for templated class implementation files.

First c++ file and header LNK2019 error

This is my first time having separate files and first time writing a header file, however I keep getting the same error I can't fix. Here are the files:
//main.cpp
#include <iostream>
#include "Bike.h"
/*
class Bike{
public:
int tyreDiameter;
int getTyreDi(){
return tyreDiameter;
}
}; */
int main(){
Bike b;
b.tyreDiameter = 50;
std::cout << b.getTyreDi();
while (1){
continue;
}
return 0;
}
//Bike.cpp
class Bike{
public:
int tyreDiameter;
int getTyreDi(void){
return tyreDiameter;
}
};
//Bike.h
#ifndef BIKE_H
#define BIKE_H
class Bike{
public:
int tyreDiameter;
int getTyreDi(void);
};
#endif
Now if I have only one file and use the class that is commented out in main.cpp everything works fine. But as soon as I try to separate the Bike class into another cpp file I get this error:
Error 1 error LNK2019: unresolved external symbol "public: int
__thiscall Bike::getTyreDi(void)" (?getTyreDi#Bike##QAEHXZ)
Error 2 error LNK1120: 1 unresolved externals
I am using Microsoft Visual Studio 2013.
Any help would be much appreciated
Why are you defining class Bike twice? in the cpp and in the h, the correct way would be this:
header
//Bike.h
#ifndef BIKE_H
#define BIKE_H
class Bike{
public:
int tyreDiameter;
int getTyreDi(void);
};
#endif
cpp
//Bike.cpp
#include "Bike.h"
int Bike::getTyreDi(void)
{
//implementation like return tyreDiameter;
}

error LNK2005: quest_tree::enter_one(class quest_tree::quest_node * &,class std::basic_string<char,struct std::char_traits<char>

I've seen many posts on LNK2005 error, but decided to ask my own anyway.
Here is the error code:
1>setup_quest_tree.obj : error LNK2005: "private: void __thiscall quest_tree::enter_one(class quest_tree::quest_node * &,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (?enter_one#quest_tree##AAEXAAPAVquest_node#1#ABV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std###Z) already defined in mainFunction.obj
1>setup_quest_tree.obj : error LNK2005: "void __cdecl setup_quest_tree(void)" (?setup_quest_tree##YAXXZ) already defined in mainFunction.obj
1>C:\Users\Timothy\Documents\Visual Studio 2008\Projects\ttbag\Debug\TTBAG.exe : fatal error LNK1169: one or more multiply defined symbols found
I'm trying to get the program to compile but am running into linker errors while doing so, probably because I've included quest_tree.h twice, but when I got rid of one of the declarations of quest_tree.h in setup_quest_tree.cpp I run into this error:
1>c:\users\timothy\documents\visual studio 2008\projects\ttbag\ttbag\setup_quest_tree.cpp(8) : error C2065: 'quest_tree' : undeclared identifier
There are many files so I am only including the ones for my project that are related to the error.
setup_quest_tree.cpp:
#ifndef SETUP_QUEST_NODES_CPP
#define SETUP_QUEST_NODES_CPP
#include <string>
#include "quest_tree.h"
void setup_quest_tree() {
quest_tree quest_tree_obj; //start out with two quest nodes
std::string welcome_message = "debug-welcome message";
quest_tree_obj.enter(welcome_message);
}
#endif
setup_quest_tree.h:
#ifndef SETUP_QUEST_TREE_H
#define SETUP_QUEST_TREE_H
#include "quest_tree.h"
#include "setup_quest_tree.cpp"
//function declarations
void setup_quest_tree (quest_tree &quest_tree_obj);
#endif /* SETUP_QUEST_TREE_H */
mainFunction.cpp (just the include statements):
#define DEBUG_LINES_ON
#include <iostream>
#include <fstream>
#include <time.h>
#include "weather.h"
#include "item.h"
#include "map.h"
#include "person.h"
#include "location.h"
#include "bag.h"
#include "equipped_items.h"
#include "global_vars.h"
#include "setup_quest_tree.h"
int main() { ...
quest_tree.h:
#ifndef QUEST_TREE_H
#define QUEST_TREE_H
#include <string>
#include <cstdlib>
class quest_tree {
private:
// the basic node of the tree. Do way to read from file?
class quest_node {
private:
quest_node *quest_nodes; // pointer to array of quests that activate upon quest activation
public:
//std::string word; // we will replace this with our own data variable
std::string note_to_player; //note that is shown upon quest activation
/*
quest_node(){ // default constructor
note_to_player = "";
}
*/
quest_node(short int num_nodes = 2){
quest_nodes = new quest_node[num_nodes]; // problem: not declared in quest_tree but rather in quest_node
note_to_player = "";
}
friend class quest_tree;
};
// the top of the tree
quest_node * root;
// Enter a new node into the tree or sub-tree
void enter_one(quest_node *&node, const std::string& note_to_player);
public:
quest_tree() {root = NULL;} // constructor
// Add a new note_to_player to our tree
void enter(std::string& note_to_player) {
enter_one(root, note_to_player);
}
};
void quest_tree::enter_one(quest_node *&new_node, const std::string& note_to_player)
{
// see if we have reached the end
if (new_node == NULL) {
new_node = new quest_node;
for (short int index = 0; index < (sizeof(new_node->quest_nodes)/sizeof(new_node->quest_nodes[0])); index++) { // initialize quest_nodes
new_node->quest_nodes[index] = NULL;
}
new_node->note_to_player = note_to_player;
}
if (new_node->note_to_player == note_to_player)
return;
/*
if (new_node->note_to_player < note_to_player)
enter_one(new_node->right, word);
else
enter_one(new_node->left, word)
*/
}
#endif /* QUEST_TREE_H */
You have included the implementation in the setup_quest_tree.h header file
#include "setup_quest_tree.cpp"
and included it in several translation units.
To fix this, at least in setup_quest_tree.cpp just include the declarations from setup_quest_tree.h, and remove that #include "setup_quest_tree.cpp" statement from setup_quest_tree.h should fix your linker errors.
You have to provide exclusively one definition (implementation) for your class (see also this answer for "Is is a good practice to put the definition of C++ classes into the header file?").
If you put it there, just since you don't know how to add the setup_quest_tree.cpp to your program, check this Q&A please to learn more about the linking process.
Here's the relevant section from the current c++ standard
3.2 One definition rule [basic.def.odr]
1 No translation unit shall contain more than one definition of any variable, function, class type, enumeration
type, or template.

Namespaces and includes generate link error

I was playing around with namespaces when I encountered a lnk2005 error. I can't figure out how to get around the error. Here's the error:
1>Source.obj : error LNK2005: "int Chart::Bars::d" (?d#Bars#Chart##3HA) already defined in Chart.obj
1>Source.obj : error LNK2005: "class foo Chart::l" (?l#Chart##3Vfoo##A) already defined in Chart.obj
1>Source.obj : error LNK2005: "int Chart::t" (?t#Chart##3HA) already defined in Chart.obj
1>C:\Users\bnm\dev\examples\play\nmspca\Debug\nmspca.exe : fatal error LNK1169: one or more multiply defined symbols found
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.49
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Here's the code...
Chart.h
#pragma once
#include "foo.h"
namespace Chart
{
int t;
foo l;
namespace Bars
{
int d;
}
}
Foo.h
#pragma once
class foo
{
public:
int ss;
char* h;
};
Chart.cpp
#include "Chart.h"
using namespace Chart;
int main ()
{
l.h = "g";
}
Source.cpp
#include "Chart.h"
using namespace Chart;
int test()
{
l.ss = 0;
return l.ss;
}
When the #include "Chart.h" from Source.cpp is removed the problems goes away. However, Source.cpp needs #include "Chart.h" for the namespace definition.
What's the correct way to express that "namespace Chart" is needed in both Chart.cpp and Source.cpp so that everything compiles?
If you define any objects in a header file and include that header file in multiple translation units, those objects are now defined multiple times. This is the problem you're having. The declarations of t, l, and d introduce objects and you have done so in a header file.
The proper method for supporting namespace scope variables is to declare them as extern in the header file. This makes them declarations only and not definitions. Then, in a single implementation file, define them.
Change Chart.h to:
#pragma once
#include "foo.h"
namespace Chart
{
extern int t;
extern foo l;
namespace Bars
{
extern int d;
}
}
Then in an implementation file, perhaps Chart.cpp, do:
int Chart::t;
foo Chart::t;
int Chart::Bars::d;
Everywhere you're including Chart.h, you're effectively dropping variables t, l, and d into those objects. Declare them as extern, then define them in Chart.cpp
I've had the exact same problem and I found a workarroud.
chart.h becomes:
#pragma once
#include "foo.h"
class Chart{
static int t;
static foo l;
class Bars
{
static int d;
};
};
and define the variables in chart.cpp
int Chart::t;
foo Chart::l;
int Chart::Bars::d;
Ugly, I know, but at least the syntax is the same wherever you need to use the vars.
This way only ONE .obj file is created containing the variables which prevents the multiple definition erros.
I haven't tried if you can declare a static variable on a namespace which could solve the problem.
Edit:
P.S. this solution gives some weird errors on msvc, as if every time it is included, sections of the code reference differente variables
Tested on my own program the static-inside-namespace and it seems to work.
Example.h:
namespace sdl{
static SDL_Surface* screen;
static int xres = 640;
static int yres = 480;
static int bpp = 32;
static int flags = SDL_ASYNCBLIT;
};