Home > Back-end >  Variable in file 2 is not accessible in file 1
Variable in file 2 is not accessible in file 1

Time:08-17

My file1.c is as follows

#include <stdio.h>
int main(int argc, char *argv[])
{ 

    printf("x = %d\n", x);
    
    return 0;
}  

And file2.c is as follows

int x = 12;

When I compile both files with gcc -std=c17 file1.c file2.c, I get the error.

error: ‘x’ undeclared (first use in this function)

Now, in my file2.c, x is a global variable. So, even if I don't declare it in file1.c, it should be seen in file1.c. So, why am I getting this error ?

CodePudding user response:

x is a global variable. So, even if I don't declare it in file1.c, it should be seen in file1.c. So, why am I getting this error ?

No, code in file1.c does not know anything about code in the file2.c. Global variables are visible only in one compilation unit (ie file).

In file1.c you need to add (before main)

extern int x;

This declaration will tell the compiler that somewhere in the project there is a definition of the variable x having the type int

#include <stdio.h>

extern int x;

int main(int argc, char *argv[])
{ 

    printf("x = %d\n", x);
    
    return 0;
}  

CodePudding user response:

Like @0___________ said above you need to declare the symbol x so my answer is just spelling it out in a bit more detail. It is customary to move declarations into a file2.h file so it's easy to reference in multiple places (especially if there is more than one symbol):

#ifndef FILE2_H
#define FILE2_H

extern int x;

#endif

Then modify file1.c and file2.c to include it:

#include <stdio.h>
#include "file2.h"

int main() {
        printf("x = %d\n", x);
        return 0;
}
#include "file2.h"

int x = 12;

Finally, you compile (-std=c17 makes not difference in this sample) and link the two files. Subsequently execute the binary::

$ gcc -std=c17 file1.c file2.c && ./a.out
x = 12

If you prefer a Makefile:

.PHONY: all clean
CFLAGS = -std=c17

all: a.out

clean: 
          rm -f a.out file1.o file2.o

a.out: file1.o file2.o
          $(CC) $^ -o $@

file1.o: file2.h

file2.o: file2.h

and it's then:

$ make && ./a.out
x = 12
  •  Tags:  
  • c
  • Related