I define a variable in a C file: int x, and I know I should use extern int x to declare it in other files if I want to use it in other files.
My question is: where should I declare it in other files?
Outside of all functions,
// in file a.c: int x; // in file b.c: extern int x; void foo() { printf("%d\n", x); }within the function(s) that will use it?
// in file b.c: void foo() { extern int x; printf("%d\n", x); }
My doubts are:
- Which one is correct?, or
- Which is preferred if both are correct?
externvariables in C for an extensive disquisition on the subject. The declaration should be in a header so that it is only written once — this means you can change it much more easily than if there are twenty copies of the declaration in twenty functions in six source files. Botha.candb.cinclude the header — it's included ina.cto ensure that the declaration matches the definition. Both variants that you show are 'technically correct'; they work as you want. Neither is desirable, though.