-2

assume there is a header file: a.h and source file : a1.c a2.c ... an.c; n>=1, which means it may only have one source file, or have several source files.

my question is that how to define a global variable g in a.h; which should be visible by a1.c ... an.c.

there are restrictions:

  1. in a1.c a2.c ... an.c; "a.h" can only be included in the first line, which means there should be no code in the source file before the line of #include "a.h"

  2. g must be defined in the a.h.

  3. can only compile the code by the following way:

    gcc -c a1.c  -o  a1.o
    ...       
    gcc -c an.c  -o  an.o
    gcc  -o a.exe    a1.o ... an.o
    

there is an answer that define g in a.h like this: extern int g; however, according to the c's specification J.5.11; it's undefined behavior.

is there any other solution?

user3998686
  • 1
  • 1
  • 3
  • 3
    You need to learn how to capital first letter of the sentence. – Krypton Sep 02 '14 at 01:44
  • You're looking for the [`extern`](http://en.cppreference.com/w/cpp/language/storage_duration) keyword. – Captain Obvlious Sep 02 '14 at 01:46
  • 1
    See: [**How to correctly use the extern keyword in C**](http://stackoverflow.com/questions/496448/how-to-correctly-use-the-extern-keyword-in-c) – David C. Rankin Sep 02 '14 at 01:56
  • possible duplicate of [How do I share a variable between source files in C? With \`extern\`, but how?](http://stackoverflow.com/questions/1433204/how-do-i-share-a-variable-between-source-files-in-c-with-extern-but-how) – n0p Sep 02 '14 at 07:52

1 Answers1

4

As you said, variable must be defined in the c file and declaration should be located in header file.
You have to define a global variable in any c file and declare 'extern' in header file.

Example)

1) define global variable in a1.c
    int g;

2) declare global variable in a.h
    extern int g;

3) include header file in other c files
    #include "a.h"
    // to do something