Reputation: 51
I keep having problems with this. If I define an object in main.cc, how do I access that object from another .cc file?
main.cc:
#include "Class.h"
#include "header.h"
int main()
{
Class object;
return 0;
}
file.cc:
#include "header.h"
void function()
{
object.method(parameter);
}
What would I have to put in header.h to get this working? Any help would be appreciated.
Upvotes: 0
Views: 10755
Reputation: 5566
how do I access that object from another .cc file? What would I have to put in header.h to get this working?
The simple answer to is to "pass the object by reference".
An object created in main() lasts for the entire program. This is typical in embedded systems ... I have no issues with this aspect.
I would, however, put the long lasting object in dynamic memory (because the stack is more limited).
main.cc:
#include "Class.h"
#include "header.h"
int main()
{
Class* object = new Class;
function(*object); // <--- pass the object by reference
return 0;
}
file.cc:
#include "Class.h"
#include "header.h"
void function(Class& object) // <-- how to specify reference
{
object.method(parameter); // <-- you did not identify parameter
}
header.h
class Class; // <--- poor name choice
void function (Class& object); // <--- another poor name choice
// note that the compiler needs to know only that Class is a
// user defined type -- the compiler knows how big a reference
// or ptr to the class is, so you need not provide more Class info
// for this file
Of course, you still need to write Class.h and define Class
Update - You have marked this post as C++.
So, please consider the following (which sidesteps the pass by reference dilemma):
main.cc:
#include "Class.h"
#include "header.h"
int main()
{
Class* object = new Class;
//
// I recommend you do not pass instance to function.
//
// Instead, the C++ way is to invoke an instance method:
object->function();
// and, if you've been paying attention, you know that the method
// Class::function()
// has access to the 'this' pointer of the class
// and thus the 'passing' of this instance information
// is already coded!
// some of your peers would say you must:
delete object;
// others would say this is already accomplished by the task exit.
return 0;
}
Upvotes: 6
Reputation: 786
If you were to try something like...
file.cc:
#include main.cc
The compiler would be compiling main.cc twice -- which means it would see 2 definitions of everything in main.cc. This will cause you some problems.
It's better design (and actually compiles correctly! Bonus!) to create a custom header file for your classes, and then import this as necessary.
myclasses.h:
Class object;
file.cc:
#include myclasses.h
Upvotes: 0