[C++]Variables cross .cpp files - c++

This is a silly question with something that must be an easy answer, but after hours of searching I cannot find the answer. What I need to do is have a pair of .cpp files, say main.cpp and help.cpp that have a variable, vars1 that they share and can both change the value and detect when that value has been changed. The way that would make sense to me is that I would simply declare the variable in a class inside a header file and include that header file in both .cpp files, but that doesn't seem to work.
Here is a copy of my code:
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "variables1.h"
using namespace std;
int main(){
variables1 vars1;
do {
cout << "Welcome\n If you need help, type 'yes' now\n";
cin.getline(vars1.input, 1024);
if (strcmp(vars1.input, "yes") == 0 || strcmp(vars1.input, "Yes") == 0){
vars1.helpvar = true;
cin.get();
}
else{
cout << "Okay then, glad that you know your way around\n";
}
cin.clear();
cout << "What would you like to do?\n";
cin.getline(vars1.input, 1024);
if (strcmp(vars1.input, "logon" ) == 0 ) {
}
} while (0 == 0);
}
help.cpp:
#include <iostream>
#include "variables1.h"
using namespace std;
int help(){
variables1 vars1;
do {
if (vars1.helpvar == true)
cout << "detecting";
} while (0 == 0);
}
variables1.h:
class variables1
{
public:
bool helpvar;
char input[1024];
};

Actually what you are doing is that for the main file and the help.cpp you are creating two different objects and are setting the helpvar variable for each of them separately. What you want is to have a single object that is used by both help.cpp and main to only modify a single instance of the helpvar variable.

Change your help function to be along the lines of
int help(const variables1& myHelpobject ){
if (myHelpobject.helpvar == true) {
cout << "detecting";
}
}
and then call the function in main as:
help(vars1)
What you were doing before was creating a separate, independent, help object.
Here we are creating the object in main and then passing a reference to it to the function.

The technique to use depends on the purpose of your variable.
If it is some sort of global parameters, that you have to use throughout all your code, the simplest is to define it as a global variable:
main file:
variables1 vars1; // outside all functions
int main(){
...
}
Either in variables1.h or in the other cpp files using the variable:
extern variables1 vars1; //outside all functions
However the code to initialise and maintain these variables in a should also be defined in the class. The constructor shall for example define the values by default, such as if help is enable or disabled.
If your variables are for communicating between different parts of your code, and especially if the main goal of some code is to process the content of these variables, then should better make this clear by passing the variable as parameter (by reference (&) if the communication is bidirectional, or by value).

There are 2 main issues with the code as posted:
int help() is never run
Something needs to call this function for it to run. There isn't anything doing that so regardless of the value of vars1.helpvar you are never going to see "detecting" output.
Consider adding a help.hpp with the definition of the function and call the function from main.
vars1.helpvar is not shared between main and int help()
Currently you have two instances of variables1 and helpvar is a member variable so each instance has a separate copy.
You could either:
Make helpvar a static member of variables1
Share once instance of variables1 between both main and help.
The use of static variables is more likely give design problem later so I'd favour option 2.

Related

While seperating classes, using a function in cpp file causes errors

So i just learned how to seperate classes and the youtube totourial is stressing on doing this alot, here's the link
https://www.youtube.com/watch?v=NTip15BHVZc&list=PLAE85DE8440AA6B83&index=15
My code is the exact same as his, and in the cpp file theres this thing:
mainClass::myfunction; (mainclass is the name of my class, myfunction is my function)
when i try to execute my program, it gives an error:
unidentified reference to 'mainClass::myfunction()'
here's my main.cpp file code:
#include <iostream>
#include "mainclass.h"
using namespace std;
int main()
{
mainClass bo;
bo.myfunction();
return 0;
}
here's my mainclass.h code:
#ifndef MAINCLASS_H
#define MAINCLASS_H
class mainClass
{
public:
myfunction();
};
#endif // MAINCLASS_H
my mainclass.cpp:
#include "mainclass.h"
#include <iostream>
using namespace std;
mainClass::myfunction()
{
cout << "I am a banana" << endl;
}
I don't know much about these so could you just tell me what the errors here are, because i copied everything correctly from the guy's totourial but still it doesn't work
P.S: this happens to me alot, i understand everything, nothing works, i copy everything, nothing works, and then i literally do exactly what the person is doing, still nothing works on all three of PC's, so i dont think the problem is with the devices lol
I doubt you completely copied and pasted that code because I'm fairly sure a teacher shouldn't be teaching having functions without a specified return type, but let's jump into it anyways...
Possibility #1
You meant to create a constructor for the class. In that case, please make sure the constructor function has the same name as the class. Also, you can't call it through .mainClass(), as it is a constructor.
class mainClass
{
public:
mainClass();
};
mainClass::mainClass()
{
cout << "I am a banana" << endl;
}
Possibility #2 You meant to create the class member function myfunction. You really should be specifying what return type your function is of. Some compilers will auto-assume int return type, and so the function you created is int myfunction();, but you really should be specifying it as void myfunction(); since you didn't return anything. Addl. info: Does C++ allow default return types for functions?
Next, change how you are giving the definition, by adding the return type.
void mainClass::myfunction()
{
cout << "I am a banana" << endl;
}
Possibility #3 Those should work, but another issue is that you might not have linked mainclass.cpp, so there is no definition available. In code blocks, right click on the project name and hit Add Files, then add the mainclass.cpp so the linker can define mainClass::myfunction().
To troubleshoot if the mainclass.cpp is being built with the project, try adding
#error I'm included! to the file mainclass.cpp after #include "mainclass.h". If you get an error I'm included!, then it is linked and you can remove the #error.

How to make a variable available to multiple .cpp files using a class?

This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.

How to access non member functions that are in a seperate file (.cpp) than main

So I am working on my first multiple file, non-toy, c++ project. I have a class that represents a multi-spectral image and all the information that goes along with it.
My problem is how to design the part of the program that loads and object of this class with a file from disk!
I don't think I need a class for this. Would switching to a functional approach be better for the file loading. This way I can have just a source file (.cpp) that has functions I can call while passing in pointers to the relevant objects that will be updated by the file accessed by the function.
I don't think static functions are what I want to use? As I understand it they(static functions) are for accessing static variables within a class, aren't they?
If I go the functional route, from main(), how do I access these functions? I assume I would include the functions .cpp file at the beginning of the main() containing file. From there how do I call the functions. Do i just use the function name or do I have to pre-pend something similar to what you have to pre-pend when including a class and then calling its methods.
Here is some example code of what I have tried and the errors I get.
OpenMultiSpec.cpp
#include <iostream>
void test(){
std::cout << "Test function accessed successfully" << std::endl;
}
main.cpp
int main(){
test();
return 1;
}
The error says " 'test' was not declared in this scope "
OpenMultiSpec.h
void test();
main.cpp
#include "OpenMultiSpec.h"
int main(){
test();
return 1;
}
If they're in two separate files, and in your case, one being a header, use
#include "OpenMultiSpec.h"
If you decide to only use one file (as your comment says above), you won't need #include for your header file. Just place your function declaration anywhere before you call it.
#include <iostream>
void test() {
std::cout << "Test function accessed successfully" << std::endl;
}
int main() {
test();
return 1;
}

Vector of function pointers emptying itself

I was working on a project and started a new class. I wanted to use a vector to store pointers of functions and then call them. Getting the function pointer and calling it was not a problem, however storing them was. I tried storing them in a vector, but it keeps emptying itself. I've tried making the vector a member of a class and an extern, both don't work. I've never had this problem ever before, and I have no clue why this is happening. Here is my current code:
TickHandler.h:
#include <iostream>
#include <ctime>
#include <vector>
class tickHandler {
public:
void addTickingFunction(void(*func)());
void onTick(void);
std::vector<void(*)()>funcs;
};
extern tickHandler TickHandler;
TickHandler.cpp:
#include "TickHandler.h"
tickHandler TickHandler;
void tickHandler::addTickingFunction(void(*func)())
{
funcs.push_back(func);
std::cout << funcs.size() << std::endl;
}
void tickHandler::onTick()
{
std::cout << funcs.size() << std::endl;
for (int i = 0; i< funcs.size();i++)
{
funcs[i]();
}
}
The expected output would be:
1
1
but instead it is:
1
0
Any help would be greatly appreciated.
EDIT: There is a lot of code in the project, but the class is only being accessed by 2 functions:
TickHandler.addTickingFunction(&physicsTick);
and
TickHandler.onTick();
Firstly, I'd suggest you put some guards around that header file, e.g.:
#ifndef TICKHANDLER_H
#define TICKHANDLER_H
// Class declaration.
#endif
I am taking a shot in the dark here, but I think your problem is that you are adding your physics tick functions to one instance of a tick handler, but running them in another. I don't think they are disappearing.
You've somehow got two instances of the TickHandler class lying about. Given this is C++ and it is an object-orientated language, the extern TickHandler and the global instance created in your .cpp file is setting off alarm bells for me.

Accessing variables outside the program in C++

id.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
static int a;
};
int A::a=20;
class b
{
public:
b()
{
cout<<A::a<<endl;
}
};
int main()
{
b *b1 = new b();
return 0;
}
id1.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class c
{
public:
int get()
{
cout<<A::a<<endl;
}
};
int main()
{
c c1;
c1.get();
return 0;
}
This is the way they have declared and got the output in one program but when I'm trying it I'm getting errors as the class is not a namespace or the program id is not included in the id1 file... How to get the variable that is stored in one file into the other file without using namespace and including the header file is there any option for it?
Two separate programs as shown (they're separate because they both define main()) cannot share variables in any simple way.
If the two separate files were to be integrated into a single program, so one of the main() programs was replaced, then you would fall back on the standard techniques of declaring the variable A::a in a header and using that header in both modules. The header would also define class A. This is the only sane way to do it.
You could write the definition of the class twice, once in each file, and declare the variable as an extern in one file and define it in the other, but that is not particularly sensible even in this simple case and rapidly degenerates into unmaintainable disaster if the code gets any more complex and there are more shared variables.
Of course, you might want to consider not using a global variable at all, but provide instead an accessor function. However, you still end up with a header declaring the services provided by the class A and the code implementing those services, and the code consuming those services.