How to access a variable in mumtiple cpp files contain main section in each file? - global

I want to access a variable in multiple .cpp files. I looked into several resources. I could not solve it though. I am using cmake to build all the codes in this project. Following is an example that exactly matches with my problem. Basically, I want val to print 42 in both code1.cpp and code2.cpp. When, I build these three files it complains: undefined reference to 'he::val' collect2: error:ld returned 1 exit status for both the .cpp files.
header1.h
#ifndef HEADER1_H
#define HEADER1_H
#include <iostream>
namespace he {
extern int val;
}
#endif // HEADER1_H
code1.cpp
#include "header1.h"
#include <iostream>
using namespace he;
int func()
{
std::cout << val << std::endl;
}
int main()
{
val=20;
func();
return 0;
}
code2.cpp
#include <iostream>
#include "header1.h"
using namespace he;
int main()
{
std::cout << val << std::endl;
}

extern int val;
Is a variable declaration. You need, somewhere (in one of your cpp files), to define the variable:
int val;
Actually, since you have two main() functions, these are two separate programs. Then your variable definition needs to be in both, like this:
namespace he {
int val;
}
But your extern declaration in the header file makes your variable global, which is usually frowned upon. It all depends, of course on what your purpose is.
Also, since two main() functions mean two separate programs, there is no variable sharing.

Related

The rule of The Big Three

Iam confused with the below question I did the program as per my understanding but it crashes what am I doing wrong? If someone can please assist me it would be much appreciated.
my main.cpp looks like this:
#include <iostream>
#include <iomanip>
#include "Number.h"
using namespace std;
int main()
{
Number n1(10);
Number n2 = n1;
n2.printNum();
n2.addOne();
n1 = n2;
n1.printNum();
return 0;
}
Then my header file looks like this:
#include <iostream>
using namespace std;
class Number
{
int *p;
public:
Number(int);
void addOne();
void printNum();
};
And the below parts for the constructor I need to complete there where it shows comments that's the part I should complete:
#include <iostream>
#include "Number.h"
using namespace std;
Number::Number(int a1)
{
*p = a1;//write the code needed to initialise the value of the member variable with a1
}
void Number::printNum()
{
cout << "The number is " << *p << endl;
}
void Number::addOne()
{
*p++;//write the code needed to increment the value of the member variable by one.
}
Then the question asks the below what should I do to the code to use the BIG THREE?
Consider the following program. Complete the class definition (where you are asked to) and check the output. You can see that that program works without error once it is completed. However, experts suggest that in any class that uses pointers and the new operator it is better to follow the rule of The Big Three. Modify the class definition to follow the rule of The Big Three and submit the new program and the output. Demonstrate the use of this pointer.
Thank you
Rohan

C++ - Why do I have to include .cpp file along with/ instead of .h file to acces the value of a global variable in the following case?

I am trying to properly declare and define global variables in separate files and include them in a third file which deals with class declaration.
The three files are:
1) global.h
#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED
extern const int marker_num;
extern const int dim;
using namespace std;
#endif // GLOBAL_H_INCLUDED
2) global.cpp
#include <iostream>
#include <cstdio>
#include <cmath>
#include "global.h"
#include "WorldState.h"
#include "Robot.h"
#include "Sensor.h"
#include "Marker.h"
constexpr const int marker_num = 10;
constexpr const int dim = (2 * marker_num) + 3;
3) WorldState.h
#ifndef WORLDSTATE_H
#define WORLDSTATE_H
#include "global.h"
#include "global.cpp"
class WorldState{
public:
WorldState(float a[], float b[dim][dim]);
get_wstate();
protected:
private:
float w_state[];
float covar_matrix[dim][dim];
};
#endif // WORLDSTATE_H
I am using the global variable dim to declare and define a multidimensional array. I have declared dim inside global.h and defined it inside global.cpp. Now, I have a class called WorldState and inside its header, I am using dim. If I comment out #include "global.cpp", it throws the following error:
C:\Users\syamp\Documents\codeblocks\slam\WorldState.h|10|error: array bound is not an integer constant before ']' token
My understanding is that including the .h file includes the corresponding .cpp as well, and that all declarations should be inside .h and all definitions should be inside .cpp. However, it doesn't seem to work in this case.
1) If I decide to include global.cpp file inside WorldState.h, isn't it bad programming practice? I am trying to write a good code not just a code that works.
2) An alternative is to define values of variable(s) dim (and marker_num) inside global.h. Is that good programming practice?
3) I believe there is something that I am missing. Kindly suggest the best method to resolve this issue. I am using codeblocks and C++11. Thanks in advance.
I am using the global variable dim to declare and define a multidimensional array.
When declaring a fixed-length array at compile-time, the value(s) of its dimension(s) must be known to the compiler, but your separation prevents the value of dim from being known to the compiler at all, so dim cannot be used to specify fixed array dimensions. Any code that uses dim will just compile into a reference to it, and then the linker will resolve the references after compilation is done. Just because dim is declared as const does not make it suitable as a compile-time constant. To do that, you must define its value in its declaration, eg:
#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED
static constexpr const int marker_num = 10;
static constexpr const int dim = (2 * marker_num);
using namespace std;
#endif // GLOBAL_H_INCLUDED
Otherwise, if you keep dim's declaration and definition in separate files, you will have to dynamically allocate the array at run-time instead of statically at compile-time.
I have declared dim inside global.h and defined it inside global.cpp.
That is fine for values you don't need to use until run-time. That will not work for values you need to use at compile-time.
My understanding is that including the .h file includes the corresponding .cpp as well
That is not even remotely true. The project/makefile brings in the .cpp file when invoking the compiler. The .h file has nothing to do with that.
that all declarations should be inside .h and all definitions should be inside .cpp.
Typically yes, but not always.
If I decide to include global.cpp file inside WorldState.h, isn't it bad programming practice?
Yes.
An alternative is to define values of variable(s) dim (and marker_num) inside global.h. Is that good programming practice?
Yes, if you want to use them where compile-time constants are expected.

Classes (located in different headers) that use each other's objects

The class called Universes uses a data member of type States, whilst States uses an object of type Universes. I'm using Visual C++ 2010 Express (if that makes any difference).
States.h:
class Universes;
extern Universes universe;
class States
{
public:
int relations;
States();
};
States::States()
{
relations = universe.state_no;
}
Universes.h
#include "States.h"
class Universes
{
public:
States state;
int state_no;
};
Test.cpp
#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include "Universes.h"
using namespace System;
int main(array<System::String ^> ^args)
{
Universes universe;
_getch();
return 0;
}
I keep getting the following errors:
States.h(16): error C2027: use of undefined type 'Universes'
States.h(1) : see declaration of 'Universes'
States.h(16): error C2228: left of '.state_no' must have class/struct/union
At the point where you try to access universe.state_no, the Universes class is incomplete (it's forward-declared).
A clean way to fix this is to move the definition of States::States into States.cpp, and make sure States.cpp #includes Universes.h.

What is the required lifetime of objects returned by import() and exect_file()?

Below is a condensed form of this example: http://www.boost.org/doc/libs/1_51_0/libs/python/doc/v2/exec.html#examples
Python function to call from C++, stored in the file script.py:
def greet():
return 'Hello from Python!'
The C++ code to execute the Python function:
#include <iostream>
#include <string>
#include <boost/python.hpp>
using namespace boost::python;
void greet()
{
object main = import("__main__");
object global(main.attr("__dict__"));
object result = exec_file("script.py", global, global);
object greet = global["greet"];
std::string message = extract<std::string>(greet());
std::cout << message << std::endl;
}
My question is: do I need to keep the main, global and result objects alive to be able to call greet?
No, you don't. Everything that needs to be alive is kept alive by references held by the greet object, you don't need to hold objects around yourself.

Eclipse undefined reference

I'm using Eclipse and MinGW. I've got undefined reference to error to all that I write in h files, that I do include in cpp-file where main located. I create an empty project, and the same thing again (
main.cpp
#include <iostream>
#include "Stack.h"
using namespace std;
int main(){
Stack<int> stack(10);
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
stack.h
#ifndef STACK_H_
#define STACK_H_
template <class T>
class Stack{
private:
struct StackEl;
StackEl *top;
public:
Stack();
Stack(T el);
~Stack();
void Push(const T& el);
T Pop();
};
#endif /* STACK_H_ */
and stack.cpp inplements everything from stack.h
If I include not h-file, but cpp - all works. Help please!
I've got following errors
D:/Workspacee/Stack2/Debug/../src/Stack2.cpp:16: undefined reference to `Stack<int>::Stack(int)'
D:/Workspacee/Stack2/Debug/../src/Stack2.cpp:18: undefined reference to `Stack<int>::~Stack()'
D:/Workspacee/Stack2/Debug/../src/Stack2.cpp:18: undefined reference to `Stack<int>::~Stack()'
This is a linker error. I'm no Eclipse expert, but you have to tell it somehow to add Stack.o to the linking command.
If you include Stack.cpp instead of Stack.h, the implementations from the cpp-file get included into main.cpp by the preprocessor before compilation, so the linking stage has no unresolved references to outside functions.
My bad, that is becouse templates! When you use template, all code, including realization of functions, must be in header-file, or you have to write prototypes for every type you are going to use you template-functions with. I've forgot about that working with templates is not the same as with usual function :(