I want to include a variable declared in an external file in C.
My project structure looks like this.
foo.h
foo.c
variable.c
main.c
What I'm doing right now is
/* main.c */
#include "foo.h"
#include <stdio.h>
#include <stdlib.h>
int main() {
bar();
printf("%d\n", a);
return 0;
}
/* foo.h */
#ifndef FOO_H
#define FOO_H
#include "variable.c"
extern const int a;
extern const int b[];
int bar();
#endif
/* foo.c */
#include "foo.h"
#include <stdio.h>
int bar () {
printf("tururu\n");
printf("%d\n", b[0]);
return 0;
}
/* variable.c */
const int a = 2;
const int b[3] = {1, 2, 3};
The variables I want to define this way are constant (read-only).
I do not know beforehand the size of the array, it depends on the definition in variable.c.
So my question is:
Is this the proper way to include some constant variables from an external source?
If it is, what am I doing wrong and how could be fixed?
Thank you
EDIT: I have updated my code with an example that can be tested. This code is not compiling because it says 'b' is undeclared in function bar. If I comment out the printf in bar it compiles and run. So the variables can be seen by main but not by foo.c?
EDIT2: Variables included this way are read-only. I have updated the code and add the include of foo.h in foo.c and now the compiler tell that there are multiple definitions of 'a' and 'b'
EDIT3: Clean up the code and the question trying to be more clear.