Search code examples
ccompiler-errorsglobal-variablesextern

Example of extern global variable - Error


I'd like to understand which mistake i did in the following example. There are three file: main.c, libreria_mia.c and libreria_mia.h.

// main.c
#include <stdio.h>
#include "libreria_mia.h"

int x = 5;

int main()
{
    int y = quadrato();
    printf("%d\n", y);
    return 0;
}


// libreria_mia.h
extern int x;
int quadrato(void);


// libreria_mia.c
int quadrato(void)
{
    x = x * x;
}

Error:

libreria_mia.c:5:2: error: ‘x’ undeclared (first use in this function)

Thank you for your time.


Solution

  • When you compile libreria_mia.c, the compiler does not automatically know about libreria_mia.h or the declarations within it. To provide a declaration for x while compiling libreria_mia.c, libreria_mia.c must include a header that declares x or have a declaration of x directly in libreria_mia.c.

    Additionally, it is conventional for a header named file.h to declare things defined in file.c (not necessarily all things defined in file.c, just those intended to be used outside it). But you have x declared in libreria_mia.h but defined in main.c. Normally, one would either define x in libreria_mia.c or declare it in main.h, and usually the former as main.c is more commonly a user of all other things in the program rather than a provider.