extern help
suppose my code in c++ has two cpp files
one of them defines an structure and makes a array of objects
then a function is being called from the first file .the function is being placed in second file. how to make it accesses structures array without passing it
i tried to use extern but cant do it.
thanks
You need to separate struct and class definitions into files separate from the implementation of the functions:
super.h
super.cpp
Then, in the other cpp file:
Hope this helps!
super.h
[source language="cpp"]#pragma oncestruct Super { int blah; void myFunc();};int arr[3]; // Not generally a good idea, but legal
super.cpp
[source language="cpp"]#include "super.h"Super::myFunc() { // code here}
Then, in the other cpp file:
[source language="cpp"]void main(){ Super s; s.myFunc(); arr[2] = 4;}
Hope this helps!
Hi. I think you mean something Like this
file foo.h
in main you define it.
foo myfoo;
in some cpp file where you need foo you write
extern foo myfoo;//same name as in main .cpp
then you can use myfoo like this in this cpp file
myfoo.Bar();
file foo.h
class foo{public;Members};
in main you define it.
foo myfoo;
in some cpp file where you need foo you write
extern foo myfoo;//same name as in main .cpp
then you can use myfoo like this in this cpp file
myfoo.Bar();
im one file i have
file1.cpp
struct struct_a
{
int used;
int do;
};
struct_a c_o[MAXIMUM];
in file2.cpp i have
extern struct struct_a c_o[MAXIMUM_2];
still there are errors
how to correct them
thanks
file1.cpp
struct struct_a
{
int used;
int do;
};
struct_a c_o[MAXIMUM];
in file2.cpp i have
extern struct struct_a c_o[MAXIMUM_2];
still there are errors
how to correct them
thanks
errors are of the form
invalid use of undefined type `struct struct_a'
forward declaration of `struct struct_a'
Declarations that will be used external to the interface should be declared inside of header files.
i.e., Your files should look like this:
file1.h (interface):
file1.cpp (implementations):
Any part of your software that requires access to the interface should #include "file1.h" (As it contains the declaration of the structure).
i.e., Your files should look like this:
file1.h (interface):
struct struct_a{int used;int do;};// You should define MAXIMUM in this header file. This does NOT// define the variable--it only indicates that the variable is defined// somewhereextern struct_a c_o[MAXIMUM];
file1.cpp (implementations):
#include "file1.h"// Here is where we actually define the variable.struct_a c_o[MAXIMUM];
Any part of your software that requires access to the interface should #include "file1.h" (As it contains the declaration of the structure).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement