I have a data member in computer.h called "status" that I calculate a value for in computer.c. I would like to access this exact value and print it in a different file called display.c.
The problem is I'm not exactly sure how I can access that variable. I'm not allowed to change the parameters of display_status() and I'm assuming creating a new computer_data struct to access the status member in that function will just create a new local variable and won't work.
I'm not exactly sure how I can access the value of computer_data->status in display.c and would appreciate any help. Would I create a getter function for status specifically or something?
computer.h
struct computer_data {
struct param *status;
}
computer.c
static void computer_assign_status(){
struct computer_data *computer = computer_get_data();
computer->status = calculateStat();
}
display.c
#include "computer.h"
void display_status(){
struct computer_data *computer = computer_get_data();
printf("computer->status: %d /n", computer->status);
}
Note: Also computer_get_data() as a function is defined as "struct computer_data *computer_get_data()"
CodePudding user response:
Using a get function is a good start. You just have to make it known in the other file.
In computer.h
add a declaration:
struct computer_data {
struct param *status;
}
struct computer_data *computer_get_data(void);
Then you can use it in display.c
.
But, of course for printing status
you cannot use %d
format specifier as it is a pointer to a struct.
Also in computer.c
you have an error:
struct void computer_assign_status(){
That should just be void
as return type.
Would I create a getter function for status specifically or something?
This totally depends on your needs. If you want to hide everything else that might be in that struct from a caller, then you might provide a function only returning pointer to the status part. Otherwise you can just do it as now where you return pointer to whole data struct.
CodePudding user response:
None of your examples accesses any data defined in another compilation unit. BTW your examples are written sloppy: as an example struct void
. Put some more effort when asking questions here
You can only access global (more precisely static storage with external linkage) variables defined in other compilation units.
in computer.h
struct computer_data {
struct param *status;
}
extern struct computer_data computer;
in computer.c
#include "computer.h"
struct computer_data computer;
void computer_assign_status(void)
{
computer.status = calculateStat();
}
in display.c
#include "computer.h"
void display_status()
{
printf("computer->status: %d /n", computer.status);
}
CodePudding user response:
In display.c
do:
extern struct computer_data * computer = computer_get_data()
instead.
This works because with the extern
keyword the compiler you're using will be forced to look for the variable in an external file.