I’ve been doing a fair amount of reading on passing a struct member to a function. However if someone could clarify where I am going wrong I would appreciate it. I predict this is more a compile order / definition error than anything, although there may be syntax errors also.
As I understand it, I am able to modify the struct members data, and avoid any copying by passing as a reference (in this case NOT a pointer). This method will also allow me to keep the dotted notation for accessing individual members inside the function.
Main.cpp:
// include headers
struct foo{
int a;
int b;
}foo_data;
int main(){
foo_data.a = 1; // assign some values to the member in standard format.
foo_data.b = 2;
function(foo_data);
// should this be &foo_data, am I passing by value here as it is
// or is the declaration taking care of that?
}
functions.h:
void function(foo &) // function declaration reference of type foo
functions.cpp:
void function(foo &foo_data) // function definition reference of type foo
{
foo_data.a; // should == 1
foo_data.b; // should == 2
}
The errors typically relate to undeclared identifiers, being foo_data. Do I need to tell tell the declaration in functions.h I am passing it a struct, or in fact an int (reference?)
Thanks!
Root Cause:
You get the error because compiler does not know/understand the type
foowhich you use in your cpp file. It can know the type only if it sees its definition.Solution:
You need to put the declaration of the structure in a header file and include that header file in both the header where you declare the function and the cpp file where you define it.
functions.h
functions.cpp
Main.cpp
EDIT:
Your comments suggest you want to share a
foo_datainstance across multiple source files, in that case you should useextern, I modified the above code sample to do so, note that insidefunction()the localfoo_datainstance will hide the global instance and to if you want to use the global object then you have to use it as::foo_data.