0

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?

  • Add `int b;` to your `foo.h`. – EOF Jul 26 '16 at 19:02
  • Compiler doesn't know anything about `b` when compiling `foo.c`. Tell him something. – Eugene Sh. Jul 26 '16 at 19:09
  • 1
    @EOF I would rather say `extern int b;` – Eugene Sh. Jul 26 '16 at 19:10
  • so I have to declare the variable b twice? –  Jul 26 '16 at 19:17
  • @EugeneSh. Looking at C11 draft standard n1570, *6.9.2 External object definitions* it seems it will have external linkage. It may nevertheless be a good idea to make this explicit. – EOF Jul 26 '16 at 19:18
  • @EOF AFAIK the tentative definitions are working in the current translation unit only: "*A tentative definition becomes a full definition if the end of the translation unit is reached and no definition has appeared with an initializer for the identifier*". So It wont be tentative, but full. – Eugene Sh. Jul 26 '16 at 19:20
  • @PintoDoido It would be a good idea for you to learn a bit about how compiler and linker are working together. Specifically read about `extern` keyword and wht it does. – Eugene Sh. Jul 26 '16 at 19:23

0 Answers0