0

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?

4

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.