In a C program, when I have a set of global variables defined in the main.c file, how do I use their values in functions defined in different .c files? For example, the following files, when compiled using gcc -o my_prog main.c foo.c throws the following error:
foo.c: In function ‘foo’:
foo.c:5:9: error: ‘b’ undeclared (first use in this function)
main.c
#include <stdio.h>
#include "foo.h"
int b=4;
int main(void)
{
int y = foo(3); /* Use the function here */
printf("%d\n", y);
return 0;
}
foo.c
#include "foo.h"
int foo(int x) /* Function definition */
{
return x + b;
}
foo.h
#ifndef FOO_H_ /* Include guard */
#define FOO_H_
int foo(int x); /* An example function declaration */
#endif // FOO_H_
How do we get around this?