What will be the fastest and better way to access the variables from that struct in the different functions ? // The functions using these variables are in the same C file.
Using a pointer to that struct.
Example:
int getHeight(struct Data *data)
{
data->percentage_Height = getIncline()/90.0;
data->speed_Height = db_speed_sensor();
data->time_Height = 0.000027; // [h] , 100ms
data->distance_Height=0;
if (data->percentage_Height == 0)
{
data->percentage_Height = 1;
}
data->distance_Height = data->speed_Height * data->time_Height * data->percentage_Height * 100;
return data->distance_Height;
}
int main(int argc, char *argv[])
{
struct Data data;
load_data(&data); // function to initialize data
distance_Height = getHeight(&data);
return distance_Height;
}
Let the compiler decides when to inline those functions to improve performance, you should be worried about the readability and organization of your code.
Also - do I need to declare the struct in the header file, in order to use it other C file ?
If you want to direct access its members in other sources, you need to define it in a header, but you could just declare that you have that struct in you C, and create function to access the values of you struct. In this case you could define the struct only in the source file, and declare it in a header or any other source files you need this declaration.
Example:
file1:
#include <stdlib.h>
struct my_struct_s {
int value;
};
struct my_struct_s *create_my_struct(void)
{
return malloc(sizeof(struct my_struct_s));
}
void destroy_my_struct(struct my_struct_s *my_struct)
{
free(my_struct);
}
void set_my_struct(struct my_struct_s *my_struct, int value)
{
my_struct->value = value;
}
int get_my_struct(struct my_struct_s *my_struct)
{
return my_struct->value;
}
file 2:
#include <stdio.h>
#include <string.h>
struct my_struct_s;
struct my_struct_s *create_my_struct(void);
void destroy_my_struct(struct my_struct_s *my_struct);
void set_my_struct(struct my_struct_s *my_struct, int value);
int get_my_struct(struct my_struct_s *my_struct);
int main() {
struct my_struct_s *my_struct;
my_struct = create_my_struct();
set_my_struct(my_struct, 10);
printf("my_struct value = %d\n", get_my_struct(my_struct));
destroy_my_struct(my_struct);
return 0;
}
It would be better to have a header with the declarations needed to access the struct of file1
, and include this header in file2
, just made it this way to show you that it is possible, and maybe give you a clue about the difference between definition and declaration