Sign in to follow this  

extern help

This topic is 3559 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
You need to separate struct and class definitions into files separate from the implementation of the functions:

super.h
[source language="cpp"]#pragma once

struct 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!

Share this post


Link to post
Share on other sites
Hi. I think you mean something Like this

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();



Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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):

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
// somewhere
extern 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).

Share this post


Link to post
Share on other sites

This topic is 3559 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this