How do I use the same object across two classes? - c++

I have a total of three classes...
1. Source.cpp (Where the main function is.)
2. Variables.h (Where I declared all my variables in, Variables.cpp is pretty much irrelevant)
3. Functions.cpp & .h (Where I make the functions to run in the main function in Source.cpp)
In main i have this
#include <iostream>
#include <cstdlib>
#include "Variables.h"
#include "Functions.h"
#include <ctime>
using namespace std;
Variables vari;
Functions func;
int main(){
cout << "\n\n>>> ";
cin >> vari.answer;
func.choiceChecker();
}
In Functions.cpp I have this
Variables vari;
void Functions::choiceChecker(){
if (vari.answer == 1){
scenario1();
}
else{
cout << "Failed";
}
}
I always get the output failed, instead of running the scenario1 function. I also get two errors.
1.Error 1 error LNK2005: "class Variables vari" (?vari##3VVariables##A) already defined in Source.obj C:\Users...\Desktop\Projects\ConsoleApplication1\ConsoleApplication1\Functions.obj ConsoleApplication1
2.Error 2 error LNK1169: one or more multiply defined symbols found C:\Users...\Desktop\Projects\ConsoleApplication1\Debug\ConsoleApplication1.exe ConsoleApplication1
I've tried using a new object in Functions.cpp, i get no errors but it doesn't get the same value from
cin >> vari.answer;

To use one global variable, you have to declare it once, then define it once (WhozCraig linked this question with its explanation).
The following should work in your situation:
Add extern Variables vari; in Variables.h (below the declaration of the Variables class or struct).
At the bottom of Variables.cpp add Variables vari;
In Functions.h you add #include Variables.h
In Source.cpp you remove #include Variables.h (because Functions.h already includes this)
Now you should be able to use vari in both Functions.cpp and Source.cpp.

Related

Need assistance with code where it claims code not declared in this scope (C++)

I am practicing using multiple files for C++ in Code::Blocks. I have three files, two source files named main.cpp and Cat.cpp, and a header file named Cat.h. Though I declare a function designed to output text in Cat.h, the implementation in the main function returns the error "'speak' was not declared in this scope."
I tried researching the error, but that was tricky because it's such a general error that can occur for a wide variety of reasons. I tried carefully checking for syntax errors or improper #include statements in my code, but I can't find anything.
This is in my main.cpp file:
#include <iostream>
#include "Cat.cpp"
#include "Cat.h"
using namespace std;
int main()
{
speak();
return 0;
}
this is my Cat.h file:
#ifndef CAT_H_INCLUDED
#define CAT_H_INCLUDED
void speak();
#endif
and this is my Cat.cpp file:
#include <iostream>
#include "Cat.h"
using namespace std;
void speak(){
cout << "Meow!!" << endl;
}
I am expecting speak() to run, but the error says it is not declared in this scope.

Define namespace scope function

I want to define public function in namespace scope (not in Class - this works)
Basically I want use it like for example the:
std::chrono::milliseconds(16)
I've tried many setups but here is the recent one:
TimeX.h
#ifndef TIMEX_H
#define TIMEX_H
namespace timee{
int now(int z);
}
#endif
TimeX.cpp
#include <chrono>
#include "TimeX.h"
using namespace timee;
int now(int z){return 4;}
Main.cpp
#include <iostream>
#include "TimeX.h"
using namespace timee;
int main(int argc, char** argv){
long c = now(2);
std::cout << "c" << c <<std::endl;
return 0;
}
And this gives me following error:
Main.obj : error LNK2019: unresolved external symbol "int __cdecl timee::now(int)" (?now#timee##YAHH#Z) referenced in function _SDL_main
What is the problem with this? It's confusing. Why linker tells me that this is referenced in _SDL_main? I use SDL library but what it has to do with my function?
Second problem related with this code.
And also one additional question (if it is not easy to answer I would start new topic). I'm using timee for namespace name because I've had an error telling that time name is used somewhere already Error C2757. I guess it is probably nested somewhere. How can I find out where it is used and is it possible to use the name anyway? I can't imagine how compiler have a problem in figuring out what I want to use.
You have to define the function like
int timee::now(int z){return 4;}
Or you could write for example this way
#include <chrono>
#include "TimeX.h"
namespace timee
{
int now(int z){return 4;}
}
Otherwise in the cpp module there is declared (and defined) another function with the same name in the global namespace
#include <chrono>
#include "TimeX.h"
using namespace timee;
int now(int z){return 4;}
That is these two definitions
int timee::now(int z){return 4;}
int now(int z){return 4;}
define different functions. The first one declares (and defines) the function in the namespace timee while the second one declares (and defines) another function with the same name in the global namespace.
As for the name time then it is defined in the global namespace and corresponds to the C standard function time. For example the header <chrono> can in turn include the header <time.h> where the name time is declared.

Simple calculator should take 2 seconds to fix its like 10 lines

Trying to make a simple Calculator but I can't even get my first function to work. I've been trying to be as organized as I can with my headers and .cpps because I remember back in the day those were important. Haha. I'm under the impression the header file is included in the main.cpp and it has the header guards. These are just declarations for my functions correct? And then Calculation'sFunctions.cpp is where I write the code for the previous declaration function I made on my header file. I'm also not sure when to include iostream and stdafx.h and all that etc. Anyway thanks in advance for your help guys, here is my 3 files all I'm trying at this point is to get an integer from the user.
Calculator.cpp
#include "stdafx.h"
#include <iostream>
#include "CalculatorDeclarations.h"
int main()
{
int getFirstInteger(int userInput)
return 0;
}
CalculatorDeclarations.h
#ifndef ADD_H
#define ADD_H
#include "stdafx.h"
#include <iostream>
int getFirstInteger();
#endif
CalculationsFunctions.cpp
#include "stdafx.h"
#include <iostream>
int getFirstInteger(int userInput)
{
std::cout << "Please enter the first integer you would like to use." << std::endl;
std::cin >> userInput;
return userInput;
}
Errors:
Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main##YAHXZ) ConsoleApplication1 c:\Users\Shane\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\MSVCRTD.lib(exe_main.obj) ‌​1
Error LNK1120 1 unresolved externals ConsoleApplication1 c:\users\shane\documents\visual studio 2015\Projects\ConsoleApplication1\Debug\ConsoleApplication1.exe 1
Well your first problem is your 'main' method
int main()
{
int getFirstInteger(int userInput)
return 0;
}
The syntax is incorrect (should be lined ended with a semi-colon). And you should be passing an int. So it could be modified to this
int main()
{
int j = 1;
getFirstInteger(j)
return 0;
}
But it's worth looking at the implementation here. You're getting the user input within that method, so no need to pass in anything. And you're not using the output, so no need to return anything.
Also you've double included #include<iostream> This won't be a big issue in a small program but it's a waste and bad practice. Only include this where it's needed (which is in CalculationsFunctions.cpp). Don't think you need #include "stdafx.h" at all.

How to use global variables in multiple .cpp files?

I have this simple program which tries to print my global variable in a separate file. I'm using the Visual Studio 2013 professional IDE.
print.h
#ifndef PRINT_H_
#define PRINT_H_
void Print();
#endif
print.cpp
#include "print.h"
#include <iostream>
void Print()
{
std::cout << g_x << '\n';
}
source.cpp
#include <iostream>
#include <limits>
#include "print.h"
extern int g_x = 5;
int main()
{
Print();
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
return 0;
}
I get a compiler error error C2065: 'g_x' : undeclared identifier.
I've searched through this forum and was unable to find anyone else having my problem. I've tried re-declaring my global variable in the separate .cpp file with no success. As you can see, I've included the necessary header guards and assigned my global variable the extern keyword. This is my first time testing global variables in multiple files. Obviously I'm missing something simple. What do I need to change or add to make my program work?
EDIT: I found this topic useful in understanding the difference between extern and the definition of a global variable.
The compiler is compiling print.cpp. It knows nothing about source.cpp while it is compiling print.cpp. Therefore that g_x that you placed in source.cpp does you absolutely no good when print.cpp is being compiled, that's why you get the error.
What you probably want to do is
1) place extern int g_x; inside of print.h. Then the compiler will see g_x when compiling print.cpp.
2) in source.cpp, remove the extern from the declaration of g_x:
int g_x = 5;
Move your global declaration to a common header, like common.h:
#ifndef COMMON_H_
#define COMMON_H_
extern int g_x; //tells the compiler that g_x exists somewhere
#endif
print.cpp:
#include <iostream>
#include "print.h"
#include "common.h"
void Print()
{
std::cout << g_x << '\n';
}
source.cpp:
#include <iostream>
#include <limits>
#include "print.h"
#include "common.h"
int g_x;
int main()
{
g_x = 5; //initialize global var
Print();
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
return 0;
}
In other .cpp files, you can access g_x including the common.h header.
extern int g_x;
belongs to .h, and you need to add
int g_x =5;
to some of .cpp.

Unresolved external symbol error while using vectors defined in a header file

I am new to C++. I had an unresolved external symbol error while using vectors and didn't know what was going wrong so I've replicated it here.
I am using MS Visual Studio 2011. The exact error is:
error LNK2001: unresolved external symbol "class std::vector > abc"
(?abc##3V?$vector#VmyClass##V?$allocator#VmyClass###std###std##A)
I have my class declaration in myClass.h:
#ifndef __MYCLASS__
#define __MYCLASS__
class myClass{
public:
int var;
myClass(void);
myClass (int k);
};
#endif
and my class definition in myClass.cpp:
#include"myClass.h"
myClass::myClass(void){
var=0;
}
myClass::myClass (int k){
var=k;
}
header.h :
ifndef __HEADER__
#define __HEADER__
#include<iostream>
#include<vector>
#include"myClass.h"
using namespace std;
extern std::vector<myClass> abc;
#endif
main.cpp :
#include <iostream>
#include <vector>
#include "myClass.h"
#include "header.h"
using namespace std;
int main(){
abc.push_back(myClass(5));
return 1;
}
This is where I get the unresolved external symbol error. Now I tried putting all of these in a single file and it compiled alright.
THE FOLLOWING FILE IS NOT INCLUDED IN THE ABOVE PROJECT.
#include<iostream>
#include<vector>
#include"myClass.h"
using namespace std;
class myClass{
public:
int var;
myClass(void){
var=0;
}
myClass (int k){
var=k;
}
};
int main(){
std::vector<myClass> abc;
abc.push_back(myClass(5));
return 1;
}
The solution has been given at What is an undefined reference/unresolved external symbol error and how do I fix it?
but I can't figure out how to implement it.
You do not have a definition for this vector:
extern std::vector<myClass> abc;
An extern declaration only tells the compiler that the object exists and it is defined somewhere. But you haven't defined it anywhere.
Add this at global namespace scope in one (and only one!) of your .cpp files:
std::vector<myClass> abc;
Actually, considering that you are not using abc from different translation units (i.e. .cpp files) you do not need the extern declaration at all. Just place your vector in main.cpp, since that is the only place where you are using it.
Also, avoid using directives, especially at namespace scope (since it easily leads to nasty name clashes with entities from the Standard Library):
using namespace std; // THIS IS BAD, DON'T DO IT
Considering that you are qualifying the names of entities from the std namespace already, you don't really need the above.
You declared abc as extern but you never provided definition for it.
Try add definition inside main.cpp:
#include <iostream>
#include <vector>
#include "myClass.h"
#include "header.h"
using namespace std;
std::vector<myClass> abc; //^^add this line
int main(){
abc.push_back(myClass(5));
return 1;
}
However, IMHO using extern here in your code seems useless. Meanwhile, I don't think it is good to name a header file as header.h.
You have abc as a local variable. It should be a global variable. Only then extern would work.
But if you only want to access it as a local variable from within main() and not from another compiled CPP file/object, then it is pointless to use an extern. The extern is only needed if the variable is global and to be accessed from another compiled CPP/object.