2

Let's say I have two C modules: The first module is a "file1.c" and "file1.h". The second module is "file2.c" and "file2.h". The first source file contains a variable called sharedVariable.

file1.c

/* Includes */
#include "stdlib.h"

int sharedVariable; // Global variable

/* Some C code */

file2.c

/* Includes */
#include "stdlib.h"

extern int sharedVariable; // Global variable

/* Some C code */

My question is: To make sharedVariable visible in file2.c, should I add #include "file1.h"? If yes, should I put something in it or I just leave it empty? If adding the header of the first file is unnecessary, how could the compiler identify the origin of sharedVariable?

EDIT:

I am looking for good practices to share a variable between two files. One of them is the owner and the other one is just a kind of reader. I used to put getters and setters in the owner file (setters are static functions) and expose the getter to the other one. But I am just curious about extern in C. Is it a good practice to use it instead?

Pryda
  • 899
  • 5
  • 14
  • 37
  • How do you compile and link the `.c` files? Also what are the contents of the header files? – Sourav Ghosh Nov 15 '18 at 14:31
  • 1
    Unless you need something else from `file1.h`, then you don't need to include it. However, it might be a good idea to move the declaration from `file2.c` into `file1.h` and include it. Then you will have the declaration in a single place and can reuse it in multiple source file. – Some programmer dude Nov 15 '18 at 14:32
  • A better idea might be to not use global variables at all, if possible. – Some programmer dude Nov 15 '18 at 14:33
  • @Someprogrammerdude I am looking for good practices to share a variable between two files. One of them is the owner and the other one is just a kind of reader. I used to put getters and setters in the owner file (setters are static functions) and expose the getter to the other one. But I am just curious about extern in C. Is it a good practice to use it instead? – Pryda Nov 15 '18 at 14:36
  • You should move the `extern int sharedVariable;` line into `file1.h`. Both `file1.c` and `file2.c` will include `file1.h`, so that the header can be used to cross-check that the files have a consistent view of the variable. You should not declare `extern` variables in a source file; you should include the correct header. You should not define variables in header files (so adding `int sharedVariable;` to `file1.h` would be a disaster. Headers declare the facilities made available by a source file. They're the glue that holds a project together. – Jonathan Leffler Nov 15 '18 at 14:38

0 Answers0